git-svn: move canonicalization to Git::SVN::Utils
[git] / git-svn.perl
1 #!/usr/bin/perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use 5.008;
5 use warnings;
6 use strict;
7 use vars qw/    $AUTHOR $VERSION
8                 $sha1 $sha1_short $_revision $_repository
9                 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
12
13 use Carp qw/croak/;
14 use Digest::MD5;
15 use IO::File qw//;
16 use File::Basename qw/dirname basename/;
17 use File::Path qw/mkpath/;
18 use File::Spec;
19 use File::Find;
20 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
21 use IPC::Open3;
22 use Memoize;
23
24 use Git::SVN;
25 use Git::SVN::Editor;
26 use Git::SVN::Fetcher;
27 use Git::SVN::Ra;
28 use Git::SVN::Prompt;
29 use Git::SVN::Log;
30 use Git::SVN::Migration;
31
32 use Git::SVN::Utils qw(
33         fatal
34         can_compress
35         canonicalize_path
36         canonicalize_url
37 );
38
39 use Git qw(
40         git_cmd_try
41         command
42         command_oneline
43         command_noisy
44         command_output_pipe
45         command_close_pipe
46         command_bidi_pipe
47         command_close_bidi_pipe
48 );
49
50 BEGIN {
51         Memoize::memoize 'Git::config';
52         Memoize::memoize 'Git::config_bool';
53 }
54
55
56 # From which subdir have we been invoked?
57 my $cmd_dir_prefix = eval {
58         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
59 } || '';
60
61 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
62 $ENV{GIT_DIR} ||= '.git';
63 $Git::SVN::Ra::_log_window_size = 100;
64
65 if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
66         $ENV{SVN_SSH} = $ENV{GIT_SSH};
67 }
68
69 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
70         $ENV{SVN_SSH} =~ s/\\/\\\\/g;
71         $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
72 }
73
74 $Git::SVN::Log::TZ = $ENV{TZ};
75 $ENV{TZ} = 'UTC';
76 $| = 1; # unbuffer STDOUT
77
78 # All SVN commands do it.  Otherwise we may die on SIGPIPE when the remote
79 # repository decides to close the connection which we expect to be kept alive.
80 $SIG{PIPE} = 'IGNORE';
81
82 # Given a dot separated version number, "subtract" it from
83 # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
84 # is at least at the version the caller asked for.
85 sub compare_svn_version {
86         my (@ours) = split(/\./, $SVN::Core::VERSION);
87         my (@theirs) = split(/\./, $_[0]);
88         my ($i, $diff);
89
90         for ($i = 0; $i < @ours && $i < @theirs; $i++) {
91                 $diff = $ours[$i] - $theirs[$i];
92                 return $diff if ($diff);
93         }
94         return 1 if ($i < @ours);
95         return -1 if ($i < @theirs);
96         return 0;
97 }
98
99 sub _req_svn {
100         require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
101         require SVN::Ra;
102         require SVN::Delta;
103         if (::compare_svn_version('1.1.0') < 0) {
104                 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
105         }
106 }
107
108 $sha1 = qr/[a-f\d]{40}/;
109 $sha1_short = qr/[a-f\d]{4,40}/;
110 my ($_stdin, $_help, $_edit,
111         $_message, $_file, $_branch_dest,
112         $_template, $_shared,
113         $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
114         $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
115         $_prefix, $_no_checkout, $_url, $_verbose,
116         $_commit_url, $_tag, $_merge_info, $_interactive);
117
118 # This is a refactoring artifact so Git::SVN can get at this git-svn switch.
119 sub opt_prefix { return $_prefix || '' }
120
121 $Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
122 $_q ||= 0;
123 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
124                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
125                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
126                     'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
127                     'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
128 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
129                 'authors-file|A=s' => \$_authors,
130                 'authors-prog=s' => \$_authors_prog,
131                 'repack:i' => \$Git::SVN::_repack,
132                 'noMetadata' => \$Git::SVN::_no_metadata,
133                 'useSvmProps' => \$Git::SVN::_use_svm_props,
134                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
135                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
136                 'no-checkout' => \$_no_checkout,
137                 'quiet|q+' => \$_q,
138                 'repack-flags|repack-args|repack-opts=s' =>
139                    \$Git::SVN::_repack_flags,
140                 'use-log-author' => \$Git::SVN::_use_log_author,
141                 'add-author-from' => \$Git::SVN::_add_author_from,
142                 'localtime' => \$Git::SVN::_localtime,
143                 %remote_opts );
144
145 my ($_trunk, @_tags, @_branches, $_stdlayout);
146 my %icv;
147 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
148                   'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
149                   'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
150                   'stdlayout|s' => \$_stdlayout,
151                   'minimize-url|m!' => \$Git::SVN::_minimize_url,
152                   'no-metadata' => sub { $icv{noMetadata} = 1 },
153                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
154                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
155                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
156                   'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
157                   %remote_opts );
158 my %cmt_opts = ( 'edit|e' => \$_edit,
159                 'rmdir' => \$Git::SVN::Editor::_rmdir,
160                 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
161                 'l=i' => \$Git::SVN::Editor::_rename_limit,
162                 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
163 );
164
165 my %cmd = (
166         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
167                         { 'revision|r=s' => \$_revision,
168                           'fetch-all|all' => \$_fetch_all,
169                           'parent|p' => \$_fetch_parent,
170                            %fc_opts } ],
171         clone => [ \&cmd_clone, "Initialize and fetch revisions",
172                         { 'revision|r=s' => \$_revision,
173                           'preserve-empty-dirs' =>
174                                 \$Git::SVN::Fetcher::_preserve_empty_dirs,
175                           'placeholder-filename=s' =>
176                                 \$Git::SVN::Fetcher::_placeholder_filename,
177                            %fc_opts, %init_opts } ],
178         init => [ \&cmd_init, "Initialize a repo for tracking" .
179                           " (requires URL argument)",
180                           \%init_opts ],
181         'multi-init' => [ \&cmd_multi_init,
182                           "Deprecated alias for ".
183                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
184                           \%init_opts ],
185         dcommit => [ \&cmd_dcommit,
186                      'Commit several diffs to merge with upstream',
187                         { 'merge|m|M' => \$_merge,
188                           'strategy|s=s' => \$_strategy,
189                           'verbose|v' => \$_verbose,
190                           'dry-run|n' => \$_dry_run,
191                           'fetch-all|all' => \$_fetch_all,
192                           'commit-url=s' => \$_commit_url,
193                           'revision|r=i' => \$_revision,
194                           'no-rebase' => \$_no_rebase,
195                           'mergeinfo=s' => \$_merge_info,
196                           'interactive|i' => \$_interactive,
197                         %cmt_opts, %fc_opts } ],
198         branch => [ \&cmd_branch,
199                     'Create a branch in the SVN repository',
200                     { 'message|m=s' => \$_message,
201                       'destination|d=s' => \$_branch_dest,
202                       'dry-run|n' => \$_dry_run,
203                       'tag|t' => \$_tag,
204                       'username=s' => \$Git::SVN::Prompt::_username,
205                       'commit-url=s' => \$_commit_url } ],
206         tag => [ sub { $_tag = 1; cmd_branch(@_) },
207                  'Create a tag in the SVN repository',
208                  { 'message|m=s' => \$_message,
209                    'destination|d=s' => \$_branch_dest,
210                    'dry-run|n' => \$_dry_run,
211                    'username=s' => \$Git::SVN::Prompt::_username,
212                    'commit-url=s' => \$_commit_url } ],
213         'set-tree' => [ \&cmd_set_tree,
214                         "Set an SVN repository to a git tree-ish",
215                         { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
216         'create-ignore' => [ \&cmd_create_ignore,
217                              'Create a .gitignore per svn:ignore',
218                              { 'revision|r=i' => \$_revision
219                              } ],
220         'mkdirs' => [ \&cmd_mkdirs ,
221                       "recreate empty directories after a checkout",
222                       { 'revision|r=i' => \$_revision } ],
223         'propget' => [ \&cmd_propget,
224                        'Print the value of a property on a file or directory',
225                        { 'revision|r=i' => \$_revision } ],
226         'proplist' => [ \&cmd_proplist,
227                        'List all properties of a file or directory',
228                        { 'revision|r=i' => \$_revision } ],
229         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
230                         { 'revision|r=i' => \$_revision
231                         } ],
232         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
233                         { 'revision|r=i' => \$_revision
234                         } ],
235         'multi-fetch' => [ \&cmd_multi_fetch,
236                            "Deprecated alias for $0 fetch --all",
237                            { 'revision|r=s' => \$_revision, %fc_opts } ],
238         'migrate' => [ sub { },
239                        # no-op, we automatically run this anyways,
240                        'Migrate configuration/metadata/layout from
241                         previous versions of git-svn',
242                        { 'minimize' => \$Git::SVN::Migration::_minimize,
243                          %remote_opts } ],
244         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
245                         { 'limit=i' => \$Git::SVN::Log::limit,
246                           'revision|r=s' => \$_revision,
247                           'verbose|v' => \$Git::SVN::Log::verbose,
248                           'incremental' => \$Git::SVN::Log::incremental,
249                           'oneline' => \$Git::SVN::Log::oneline,
250                           'show-commit' => \$Git::SVN::Log::show_commit,
251                           'non-recursive' => \$Git::SVN::Log::non_recursive,
252                           'authors-file|A=s' => \$_authors,
253                           'color' => \$Git::SVN::Log::color,
254                           'pager=s' => \$Git::SVN::Log::pager
255                         } ],
256         'find-rev' => [ \&cmd_find_rev,
257                         "Translate between SVN revision numbers and tree-ish",
258                         {} ],
259         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
260                         { 'merge|m|M' => \$_merge,
261                           'verbose|v' => \$_verbose,
262                           'strategy|s=s' => \$_strategy,
263                           'local|l' => \$_local,
264                           'fetch-all|all' => \$_fetch_all,
265                           'dry-run|n' => \$_dry_run,
266                           'preserve-merges|p' => \$_preserve_merges,
267                           %fc_opts } ],
268         'commit-diff' => [ \&cmd_commit_diff,
269                            'Commit a diff between two trees',
270                         { 'message|m=s' => \$_message,
271                           'file|F=s' => \$_file,
272                           'revision|r=s' => \$_revision,
273                         %cmt_opts } ],
274         'info' => [ \&cmd_info,
275                     "Show info about the latest SVN revision
276                      on the current branch",
277                     { 'url' => \$_url, } ],
278         'blame' => [ \&Git::SVN::Log::cmd_blame,
279                     "Show what revision and author last modified each line of a file",
280                     { 'git-format' => \$Git::SVN::Log::_git_format } ],
281         'reset' => [ \&cmd_reset,
282                      "Undo fetches back to the specified SVN revision",
283                      { 'revision|r=s' => \$_revision,
284                        'parent|p' => \$_fetch_parent } ],
285         'gc' => [ \&cmd_gc,
286                   "Compress unhandled.log files in .git/svn and remove " .
287                   "index files in .git/svn",
288                 {} ],
289 );
290
291 use Term::ReadLine;
292 package FakeTerm;
293 sub new {
294         my ($class, $reason) = @_;
295         return bless \$reason, shift;
296 }
297 sub readline {
298         my $self = shift;
299         die "Cannot use readline on FakeTerm: $$self";
300 }
301 package main;
302
303 my $term = eval {
304         $ENV{"GIT_SVN_NOTTY"}
305                 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
306                 : new Term::ReadLine 'git-svn';
307 };
308 if ($@) {
309         $term = new FakeTerm "$@: going non-interactive";
310 }
311
312 my $cmd;
313 for (my $i = 0; $i < @ARGV; $i++) {
314         if (defined $cmd{$ARGV[$i]}) {
315                 $cmd = $ARGV[$i];
316                 splice @ARGV, $i, 1;
317                 last;
318         } elsif ($ARGV[$i] eq 'help') {
319                 $cmd = $ARGV[$i+1];
320                 usage(0);
321         }
322 };
323
324 # make sure we're always running at the top-level working directory
325 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
326         unless (-d $ENV{GIT_DIR}) {
327                 if ($git_dir_user_set) {
328                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
329                             "but it is not a directory\n";
330                 }
331                 my $git_dir = delete $ENV{GIT_DIR};
332                 my $cdup = undef;
333                 git_cmd_try {
334                         $cdup = command_oneline(qw/rev-parse --show-cdup/);
335                         $git_dir = '.' unless ($cdup);
336                         chomp $cdup if ($cdup);
337                         $cdup = "." unless ($cdup && length $cdup);
338                 } "Already at toplevel, but $git_dir not found\n";
339                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
340                 unless (-d $git_dir) {
341                         die "$git_dir still not found after going to ",
342                             "'$cdup'\n";
343                 }
344                 $ENV{GIT_DIR} = $git_dir;
345         }
346         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
347 }
348
349 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
350
351 read_git_config(\%opts);
352 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
353         Getopt::Long::Configure('pass_through');
354 }
355 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
356                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
357                     'id|i=s' => \$Git::SVN::default_ref_id,
358                     'svn-remote|remote|R=s' => sub {
359                        $Git::SVN::no_reuse_existing = 1;
360                        $Git::SVN::default_repo_id = $_[1] });
361 exit 1 if (!$rv && $cmd && $cmd ne 'log');
362
363 usage(0) if $_help;
364 version() if $_version;
365 usage(1) unless defined $cmd;
366 load_authors() if $_authors;
367 if (defined $_authors_prog) {
368         $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
369 }
370
371 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
372         Git::SVN::Migration::migration_check();
373 }
374 Git::SVN::init_vars();
375 eval {
376         Git::SVN::verify_remotes_sanity();
377         $cmd{$cmd}->[0]->(@ARGV);
378         post_fetch_checkout();
379 };
380 fatal $@ if $@;
381 exit 0;
382
383 ####################### primary functions ######################
384 sub usage {
385         my $exit = shift || 0;
386         my $fd = $exit ? \*STDERR : \*STDOUT;
387         print $fd <<"";
388 git-svn - bidirectional operations between a single Subversion tree and git
389 Usage: git svn <command> [options] [arguments]\n
390
391         print $fd "Available commands:\n" unless $cmd;
392
393         foreach (sort keys %cmd) {
394                 next if $cmd && $cmd ne $_;
395                 next if /^multi-/; # don't show deprecated commands
396                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
397                 foreach (sort keys %{$cmd{$_}->[2]}) {
398                         # mixed-case options are for .git/config only
399                         next if /[A-Z]/ && /^[a-z]+$/i;
400                         # prints out arguments as they should be passed:
401                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
402                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
403                                                         "--$_" : "-$_" }
404                                                 split /\|/,$_)," $x\n";
405                 }
406         }
407         print $fd <<"";
408 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
409 arbitrary identifier if you're tracking multiple SVN branches/repositories in
410 one git repository and want to keep them separate.  See git-svn(1) for more
411 information.
412
413         exit $exit;
414 }
415
416 sub version {
417         ::_req_svn();
418         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
419         exit 0;
420 }
421
422 sub ask {
423         my ($prompt, %arg) = @_;
424         my $valid_re = $arg{valid_re};
425         my $default = $arg{default};
426         my $resp;
427         my $i = 0;
428
429         if ( !( defined($term->IN)
430             && defined( fileno($term->IN) )
431             && defined( $term->OUT )
432             && defined( fileno($term->OUT) ) ) ){
433                 return defined($default) ? $default : undef;
434         }
435
436         while ($i++ < 10) {
437                 $resp = $term->readline($prompt);
438                 if (!defined $resp) { # EOF
439                         print "\n";
440                         return defined $default ? $default : undef;
441                 }
442                 if ($resp eq '' and defined $default) {
443                         return $default;
444                 }
445                 if (!defined $valid_re or $resp =~ /$valid_re/) {
446                         return $resp;
447                 }
448         }
449         return undef;
450 }
451
452 sub do_git_init_db {
453         unless (-d $ENV{GIT_DIR}) {
454                 my @init_db = ('init');
455                 push @init_db, "--template=$_template" if defined $_template;
456                 if (defined $_shared) {
457                         if ($_shared =~ /[a-z]/) {
458                                 push @init_db, "--shared=$_shared";
459                         } else {
460                                 push @init_db, "--shared";
461                         }
462                 }
463                 command_noisy(@init_db);
464                 $_repository = Git->repository(Repository => ".git");
465         }
466         my $set;
467         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
468         foreach my $i (keys %icv) {
469                 die "'$set' and '$i' cannot both be set\n" if $set;
470                 next unless defined $icv{$i};
471                 command_noisy('config', "$pfx.$i", $icv{$i});
472                 $set = $i;
473         }
474         my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
475         command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
476                 if defined $$ignore_paths_regex;
477         my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
478         command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
479                 if defined $$ignore_refs_regex;
480
481         if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
482                 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
483                 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
484                 command_noisy('config', "$pfx.placeholder-filename", $$fname);
485         }
486 }
487
488 sub init_subdir {
489         my $repo_path = shift or return;
490         mkpath([$repo_path]) unless -d $repo_path;
491         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
492         $ENV{GIT_DIR} = '.git';
493         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
494 }
495
496 sub cmd_clone {
497         my ($url, $path) = @_;
498         if (!defined $path &&
499             (defined $_trunk || @_branches || @_tags ||
500              defined $_stdlayout) &&
501             $url !~ m#^[a-z\+]+://#) {
502                 $path = $url;
503         }
504         $path = basename($url) if !defined $path || !length $path;
505         my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
506         cmd_init($url, $path);
507         command_oneline('config', 'svn.authorsfile', $authors_absolute)
508             if $_authors;
509         Git::SVN::fetch_all($Git::SVN::default_repo_id);
510 }
511
512 sub cmd_init {
513         if (defined $_stdlayout) {
514                 $_trunk = 'trunk' if (!defined $_trunk);
515                 @_tags = 'tags' if (! @_tags);
516                 @_branches = 'branches' if (! @_branches);
517         }
518         if (defined $_trunk || @_branches || @_tags) {
519                 return cmd_multi_init(@_);
520         }
521         my $url = shift or die "SVN repository location required ",
522                                "as a command-line argument\n";
523         $url = canonicalize_url($url);
524         init_subdir(@_);
525         do_git_init_db();
526
527         if ($Git::SVN::_minimize_url eq 'unset') {
528                 $Git::SVN::_minimize_url = 0;
529         }
530
531         Git::SVN->init($url);
532 }
533
534 sub cmd_fetch {
535         if (grep /^\d+=./, @_) {
536                 die "'<rev>=<commit>' fetch arguments are ",
537                     "no longer supported.\n";
538         }
539         my ($remote) = @_;
540         if (@_ > 1) {
541                 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
542         }
543         $Git::SVN::no_reuse_existing = undef;
544         if ($_fetch_parent) {
545                 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
546                 unless ($gs) {
547                         die "Unable to determine upstream SVN information from ",
548                             "working tree history\n";
549                 }
550                 # just fetch, don't checkout.
551                 $_no_checkout = 'true';
552                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
553         } elsif ($_fetch_all) {
554                 cmd_multi_fetch();
555         } else {
556                 $remote ||= $Git::SVN::default_repo_id;
557                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
558         }
559 }
560
561 sub cmd_set_tree {
562         my (@commits) = @_;
563         if ($_stdin || !@commits) {
564                 print "Reading from stdin...\n";
565                 @commits = ();
566                 while (<STDIN>) {
567                         if (/\b($sha1_short)\b/o) {
568                                 unshift @commits, $1;
569                         }
570                 }
571         }
572         my @revs;
573         foreach my $c (@commits) {
574                 my @tmp = command('rev-parse',$c);
575                 if (scalar @tmp == 1) {
576                         push @revs, $tmp[0];
577                 } elsif (scalar @tmp > 1) {
578                         push @revs, reverse(command('rev-list',@tmp));
579                 } else {
580                         fatal "Failed to rev-parse $c";
581                 }
582         }
583         my $gs = Git::SVN->new;
584         my ($r_last, $cmt_last) = $gs->last_rev_commit;
585         $gs->fetch;
586         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
587                 fatal "There are new revisions that were fetched ",
588                       "and need to be merged (or acknowledged) ",
589                       "before committing.\nlast rev: $r_last\n",
590                       " current: $gs->{last_rev}";
591         }
592         $gs->set_tree($_) foreach @revs;
593         print "Done committing ",scalar @revs," revisions to SVN\n";
594         unlink $gs->{index};
595 }
596
597 sub split_merge_info_range {
598         my ($range) = @_;
599         if ($range =~ /(\d+)-(\d+)/) {
600                 return (int($1), int($2));
601         } else {
602                 return (int($range), int($range));
603         }
604 }
605
606 sub combine_ranges {
607         my ($in) = @_;
608
609         my @fnums = ();
610         my @arr = split(/,/, $in);
611         for my $element (@arr) {
612                 my ($start, $end) = split_merge_info_range($element);
613                 push @fnums, $start;
614         }
615
616         my @sorted = @arr [ sort {
617                 $fnums[$a] <=> $fnums[$b]
618         } 0..$#arr ];
619
620         my @return = ();
621         my $last = -1;
622         my $first = -1;
623         for my $element (@sorted) {
624                 my ($start, $end) = split_merge_info_range($element);
625
626                 if ($last == -1) {
627                         $first = $start;
628                         $last = $end;
629                         next;
630                 }
631                 if ($start <= $last+1) {
632                         if ($end > $last) {
633                                 $last = $end;
634                         }
635                         next;
636                 }
637                 if ($first == $last) {
638                         push @return, "$first";
639                 } else {
640                         push @return, "$first-$last";
641                 }
642                 $first = $start;
643                 $last = $end;
644         }
645
646         if ($first != -1) {
647                 if ($first == $last) {
648                         push @return, "$first";
649                 } else {
650                         push @return, "$first-$last";
651                 }
652         }
653
654         return join(',', @return);
655 }
656
657 sub merge_revs_into_hash {
658         my ($hash, $minfo) = @_;
659         my @lines = split(' ', $minfo);
660
661         for my $line (@lines) {
662                 my ($branchpath, $revs) = split(/:/, $line);
663
664                 if (exists($hash->{$branchpath})) {
665                         # Merge the two revision sets
666                         my $combined = "$hash->{$branchpath},$revs";
667                         $hash->{$branchpath} = combine_ranges($combined);
668                 } else {
669                         # Just do range combining for consolidation
670                         $hash->{$branchpath} = combine_ranges($revs);
671                 }
672         }
673 }
674
675 sub merge_merge_info {
676         my ($mergeinfo_one, $mergeinfo_two) = @_;
677         my %result_hash = ();
678
679         merge_revs_into_hash(\%result_hash, $mergeinfo_one);
680         merge_revs_into_hash(\%result_hash, $mergeinfo_two);
681
682         my $result = '';
683         # Sort below is for consistency's sake
684         for my $branchname (sort keys(%result_hash)) {
685                 my $revlist = $result_hash{$branchname};
686                 $result .= "$branchname:$revlist\n"
687         }
688         return $result;
689 }
690
691 sub populate_merge_info {
692         my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
693
694         my %parentshash;
695         read_commit_parents(\%parentshash, $d);
696         my @parents = @{$parentshash{$d}};
697         if ($#parents > 0) {
698                 # Merge commit
699                 my $all_parents_ok = 1;
700                 my $aggregate_mergeinfo = '';
701                 my $rooturl = $gs->repos_root;
702
703                 if (defined($rewritten_parent)) {
704                         # Replace first parent with newly-rewritten version
705                         shift @parents;
706                         unshift @parents, $rewritten_parent;
707                 }
708
709                 foreach my $parent (@parents) {
710                         my ($branchurl, $svnrev, $paruuid) =
711                                 cmt_metadata($parent);
712
713                         unless (defined($svnrev)) {
714                                 # Should have been caught be preflight check
715                                 fatal "merge commit $d has ancestor $parent, but that change "
716                      ."does not have git-svn metadata!";
717                         }
718                         unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
719                                 fatal "commit $parent git-svn metadata changed mid-run!";
720                         }
721                         my $branchpath = $1;
722
723                         my $ra = Git::SVN::Ra->new($branchurl);
724                         my (undef, undef, $props) =
725                                 $ra->get_dir(canonicalize_path("."), $svnrev);
726                         my $par_mergeinfo = $props->{'svn:mergeinfo'};
727                         unless (defined $par_mergeinfo) {
728                                 $par_mergeinfo = '';
729                         }
730                         # Merge previous mergeinfo values
731                         $aggregate_mergeinfo =
732                                 merge_merge_info($aggregate_mergeinfo,
733                                                                  $par_mergeinfo, 0);
734
735                         next if $parent eq $parents[0]; # Skip first parent
736                         # Add new changes being placed in tree by merge
737                         my @cmd = (qw/rev-list --reverse/,
738                                            $parent, qw/--not/);
739                         foreach my $par (@parents) {
740                                 unless ($par eq $parent) {
741                                         push @cmd, $par;
742                                 }
743                         }
744                         my @revsin = ();
745                         my ($revlist, $ctx) = command_output_pipe(@cmd);
746                         while (<$revlist>) {
747                                 my $irev = $_;
748                                 chomp $irev;
749                                 my (undef, $csvnrev, undef) =
750                                         cmt_metadata($irev);
751                                 unless (defined $csvnrev) {
752                                         # A child is missing SVN annotations...
753                                         # this might be OK, or might not be.
754                                         warn "W:child $irev is merged into revision "
755                                                  ."$d but does not have git-svn metadata. "
756                                                  ."This means git-svn cannot determine the "
757                                                  ."svn revision numbers to place into the "
758                                                  ."svn:mergeinfo property. You must ensure "
759                                                  ."a branch is entirely committed to "
760                                                  ."SVN before merging it in order for "
761                                                  ."svn:mergeinfo population to function "
762                                                  ."properly";
763                                 }
764                                 push @revsin, $csvnrev;
765                         }
766                         command_close_pipe($revlist, $ctx);
767
768                         last unless $all_parents_ok;
769
770                         # We now have a list of all SVN revnos which are
771                         # merged by this particular parent. Integrate them.
772                         next if $#revsin == -1;
773                         my $newmergeinfo = "$branchpath:" . join(',', @revsin);
774                         $aggregate_mergeinfo =
775                                 merge_merge_info($aggregate_mergeinfo,
776                                                                  $newmergeinfo, 1);
777                 }
778                 if ($all_parents_ok and $aggregate_mergeinfo) {
779                         return $aggregate_mergeinfo;
780                 }
781         }
782
783         return undef;
784 }
785
786 sub cmd_dcommit {
787         my $head = shift;
788         command_noisy(qw/update-index --refresh/);
789         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
790                 'Cannot dcommit with a dirty index.  Commit your changes first, '
791                 . "or stash them with `git stash'.\n";
792         $head ||= 'HEAD';
793
794         my $old_head;
795         if ($head ne 'HEAD') {
796                 $old_head = eval {
797                         command_oneline([qw/symbolic-ref -q HEAD/])
798                 };
799                 if ($old_head) {
800                         $old_head =~ s{^refs/heads/}{};
801                 } else {
802                         $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
803                 }
804                 command(['checkout', $head], STDERR => 0);
805         }
806
807         my @refs;
808         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
809         unless ($gs) {
810                 die "Unable to determine upstream SVN information from ",
811                     "$head history.\nPerhaps the repository is empty.";
812         }
813
814         if (defined $_commit_url) {
815                 $url = $_commit_url;
816         } else {
817                 $url = eval { command_oneline('config', '--get',
818                               "svn-remote.$gs->{repo_id}.commiturl") };
819                 if (!$url) {
820                         $url = $gs->full_pushurl
821                 }
822         }
823
824         my $last_rev = $_revision if defined $_revision;
825         if ($url) {
826                 print "Committing to $url ...\n";
827         }
828         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
829         if ($_no_rebase && scalar(@$linear_refs) > 1) {
830                 warn "Attempting to commit more than one change while ",
831                      "--no-rebase is enabled.\n",
832                      "If these changes depend on each other, re-running ",
833                      "without --no-rebase may be required."
834         }
835
836         if (defined $_interactive){
837                 my $ask_default = "y";
838                 foreach my $d (@$linear_refs){
839                         my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
840                         while (<$fh>){
841                                 print $_;
842                         }
843                         command_close_pipe($fh, $ctx);
844                         $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
845                                  valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
846                                  default => $ask_default);
847                         die "Commit this patch reply required" unless defined $_;
848                         if (/^[nq]/i) {
849                                 exit(0);
850                         } elsif (/^a/i) {
851                                 last;
852                         }
853                 }
854         }
855
856         my $expect_url = $url;
857
858         my $push_merge_info = eval {
859                 command_oneline(qw/config --get svn.pushmergeinfo/)
860                 };
861         if (not defined($push_merge_info)
862                         or $push_merge_info eq "false"
863                         or $push_merge_info eq "no"
864                         or $push_merge_info eq "never") {
865                 $push_merge_info = 0;
866         }
867
868         unless (defined($_merge_info) || ! $push_merge_info) {
869                 # Preflight check of changes to ensure no issues with mergeinfo
870                 # This includes check for uncommitted-to-SVN parents
871                 # (other than the first parent, which we will handle),
872                 # information from different SVN repos, and paths
873                 # which are not underneath this repository root.
874                 my $rooturl = $gs->repos_root;
875                 foreach my $d (@$linear_refs) {
876                         my %parentshash;
877                         read_commit_parents(\%parentshash, $d);
878                         my @realparents = @{$parentshash{$d}};
879                         if ($#realparents > 0) {
880                                 # Merge commit
881                                 shift @realparents; # Remove/ignore first parent
882                                 foreach my $parent (@realparents) {
883                                         my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
884                                         unless (defined $paruuid) {
885                                                 # A parent is missing SVN annotations...
886                                                 # abort the whole operation.
887                                                 fatal "$parent is merged into revision $d, "
888                                                          ."but does not have git-svn metadata. "
889                                                          ."Either dcommit the branch or use a "
890                                                          ."local cherry-pick, FF merge, or rebase "
891                                                          ."instead of an explicit merge commit.";
892                                         }
893
894                                         unless ($paruuid eq $uuid) {
895                                                 # Parent has SVN metadata from different repository
896                                                 fatal "merge parent $parent for change $d has "
897                                                          ."git-svn uuid $paruuid, while current change "
898                                                          ."has uuid $uuid!";
899                                         }
900
901                                         unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
902                                                 # This branch is very strange indeed.
903                                                 fatal "merge parent $parent for $d is on branch "
904                                                          ."$branchurl, which is not under the "
905                                                          ."git-svn root $rooturl!";
906                                         }
907                                 }
908                         }
909                 }
910         }
911
912         my $rewritten_parent;
913         Git::SVN::remove_username($expect_url);
914         if (defined($_merge_info)) {
915                 $_merge_info =~ tr{ }{\n};
916         }
917         while (1) {
918                 my $d = shift @$linear_refs or last;
919                 unless (defined $last_rev) {
920                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
921                         unless (defined $last_rev) {
922                                 fatal "Unable to extract revision information ",
923                                       "from commit $d~1";
924                         }
925                 }
926                 if ($_dry_run) {
927                         print "diff-tree $d~1 $d\n";
928                 } else {
929                         my $cmt_rev;
930
931                         unless (defined($_merge_info) || ! $push_merge_info) {
932                                 $_merge_info = populate_merge_info($d, $gs,
933                                                              $uuid,
934                                                              $linear_refs,
935                                                              $rewritten_parent);
936                         }
937
938                         my %ed_opts = ( r => $last_rev,
939                                         log => get_commit_entry($d)->{log},
940                                         ra => Git::SVN::Ra->new($url),
941                                         config => SVN::Core::config_get_config(
942                                                 $Git::SVN::Ra::config_dir
943                                         ),
944                                         tree_a => "$d~1",
945                                         tree_b => $d,
946                                         editor_cb => sub {
947                                                print "Committed r$_[0]\n";
948                                                $cmt_rev = $_[0];
949                                         },
950                                         mergeinfo => $_merge_info,
951                                         svn_path => '');
952                         if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
953                                 print "No changes\n$d~1 == $d\n";
954                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
955                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
956                                                                $parents->{$d};
957                         }
958                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
959                         $last_rev = $cmt_rev;
960                         next if $_no_rebase;
961
962                         # we always want to rebase against the current HEAD,
963                         # not any head that was passed to us
964                         my @diff = command('diff-tree', $d,
965                                            $gs->refname, '--');
966                         my @finish;
967                         if (@diff) {
968                                 @finish = rebase_cmd();
969                                 print STDERR "W: $d and ", $gs->refname,
970                                              " differ, using @finish:\n",
971                                              join("\n", @diff), "\n";
972                         } else {
973                                 print "No changes between current HEAD and ",
974                                       $gs->refname,
975                                       "\nResetting to the latest ",
976                                       $gs->refname, "\n";
977                                 @finish = qw/reset --mixed/;
978                         }
979                         command_noisy(@finish, $gs->refname);
980
981                         $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
982
983                         if (@diff) {
984                                 @refs = ();
985                                 my ($url_, $rev_, $uuid_, $gs_) =
986                                               working_head_info('HEAD', \@refs);
987                                 my ($linear_refs_, $parents_) =
988                                               linearize_history($gs_, \@refs);
989                                 if (scalar(@$linear_refs) !=
990                                     scalar(@$linear_refs_)) {
991                                         fatal "# of revisions changed ",
992                                           "\nbefore:\n",
993                                           join("\n", @$linear_refs),
994                                           "\n\nafter:\n",
995                                           join("\n", @$linear_refs_), "\n",
996                                           'If you are attempting to commit ',
997                                           "merges, try running:\n\t",
998                                           'git rebase --interactive',
999                                           '--preserve-merges ',
1000                                           $gs->refname,
1001                                           "\nBefore dcommitting";
1002                                 }
1003                                 if ($url_ ne $expect_url) {
1004                                         if ($url_ eq $gs->metadata_url) {
1005                                                 print
1006                                                   "Accepting rewritten URL:",
1007                                                   " $url_\n";
1008                                         } else {
1009                                                 fatal
1010                                                   "URL mismatch after rebase:",
1011                                                   " $url_ != $expect_url";
1012                                         }
1013                                 }
1014                                 if ($uuid_ ne $uuid) {
1015                                         fatal "uuid mismatch after rebase: ",
1016                                               "$uuid_ != $uuid";
1017                                 }
1018                                 # remap parents
1019                                 my (%p, @l, $i);
1020                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1021                                         my $new = $linear_refs_->[$i] or next;
1022                                         $p{$new} =
1023                                                 $parents->{$linear_refs->[$i]};
1024                                         push @l, $new;
1025                                 }
1026                                 $parents = \%p;
1027                                 $linear_refs = \@l;
1028                         }
1029                 }
1030         }
1031
1032         if ($old_head) {
1033                 my $new_head = command_oneline(qw/rev-parse HEAD/);
1034                 my $new_is_symbolic = eval {
1035                         command_oneline(qw/symbolic-ref -q HEAD/);
1036                 };
1037                 if ($new_is_symbolic) {
1038                         print "dcommitted the branch ", $head, "\n";
1039                 } else {
1040                         print "dcommitted on a detached HEAD because you gave ",
1041                               "a revision argument.\n",
1042                               "The rewritten commit is: ", $new_head, "\n";
1043                 }
1044                 command(['checkout', $old_head], STDERR => 0);
1045         }
1046
1047         unlink $gs->{index};
1048 }
1049
1050 sub cmd_branch {
1051         my ($branch_name, $head) = @_;
1052
1053         unless (defined $branch_name && length $branch_name) {
1054                 die(($_tag ? "tag" : "branch") . " name required\n");
1055         }
1056         $head ||= 'HEAD';
1057
1058         my (undef, $rev, undef, $gs) = working_head_info($head);
1059         my $src = $gs->full_pushurl;
1060
1061         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1062         my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1063         my $glob;
1064         if ($#{$allglobs} == 0) {
1065                 $glob = $allglobs->[0];
1066         } else {
1067                 unless(defined $_branch_dest) {
1068                         die "Multiple ",
1069                             $_tag ? "tag" : "branch",
1070                             " paths defined for Subversion repository.\n",
1071                             "You must specify where you want to create the ",
1072                             $_tag ? "tag" : "branch",
1073                             " with the --destination argument.\n";
1074                 }
1075                 foreach my $g (@{$allglobs}) {
1076                         my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
1077                         if ($_branch_dest =~ /$re/) {
1078                                 $glob = $g;
1079                                 last;
1080                         }
1081                 }
1082                 unless (defined $glob) {
1083                         my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1084                         foreach my $g (@{$allglobs}) {
1085                                 $g->{path}->{left} =~ /$dest_re/ or next;
1086                                 if (defined $glob) {
1087                                         die "Ambiguous destination: ",
1088                                             $_branch_dest, "\nmatches both '",
1089                                             $glob->{path}->{left}, "' and '",
1090                                             $g->{path}->{left}, "'\n";
1091                                 }
1092                                 $glob = $g;
1093                         }
1094                         unless (defined $glob) {
1095                                 die "Unknown ",
1096                                     $_tag ? "tag" : "branch",
1097                                     " destination $_branch_dest\n";
1098                         }
1099                 }
1100         }
1101         my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1102         my $url;
1103         if (defined $_commit_url) {
1104                 $url = $_commit_url;
1105         } else {
1106                 $url = eval { command_oneline('config', '--get',
1107                         "svn-remote.$gs->{repo_id}.commiturl") };
1108                 if (!$url) {
1109                         $url = $remote->{pushurl} || $remote->{url};
1110                 }
1111         }
1112         my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1113
1114         if ($dst =~ /^https:/ && $src =~ /^http:/) {
1115                 $src=~s/^http:/https:/;
1116         }
1117
1118         ::_req_svn();
1119
1120         my $ctx = SVN::Client->new(
1121                 auth    => Git::SVN::Ra::_auth_providers(),
1122                 log_msg => sub {
1123                         ${ $_[0] } = defined $_message
1124                                 ? $_message
1125                                 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1126                                 . $branch_name;
1127                 },
1128         );
1129
1130         eval {
1131                 $ctx->ls($dst, 'HEAD', 0);
1132         } and die "branch ${branch_name} already exists\n";
1133
1134         print "Copying ${src} at r${rev} to ${dst}...\n";
1135         $ctx->copy($src, $rev, $dst)
1136                 unless $_dry_run;
1137
1138         $gs->fetch_all;
1139 }
1140
1141 sub cmd_find_rev {
1142         my $revision_or_hash = shift or die "SVN or git revision required ",
1143                                             "as a command-line argument\n";
1144         my $result;
1145         if ($revision_or_hash =~ /^r\d+$/) {
1146                 my $head = shift;
1147                 $head ||= 'HEAD';
1148                 my @refs;
1149                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1150                 unless ($gs) {
1151                         die "Unable to determine upstream SVN information from ",
1152                             "$head history\n";
1153                 }
1154                 my $desired_revision = substr($revision_or_hash, 1);
1155                 $result = $gs->rev_map_get($desired_revision, $uuid);
1156         } else {
1157                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1158                 $result = $rev;
1159         }
1160         print "$result\n" if $result;
1161 }
1162
1163 sub auto_create_empty_directories {
1164         my ($gs) = @_;
1165         my $var = eval { command_oneline('config', '--get', '--bool',
1166                                          "svn-remote.$gs->{repo_id}.automkdirs") };
1167         # By default, create empty directories by consulting the unhandled log,
1168         # but allow setting it to 'false' to skip it.
1169         return !($var && $var eq 'false');
1170 }
1171
1172 sub cmd_rebase {
1173         command_noisy(qw/update-index --refresh/);
1174         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1175         unless ($gs) {
1176                 die "Unable to determine upstream SVN information from ",
1177                     "working tree history\n";
1178         }
1179         if ($_dry_run) {
1180                 print "Remote Branch: " . $gs->refname . "\n";
1181                 print "SVN URL: " . $url . "\n";
1182                 return;
1183         }
1184         if (command(qw/diff-index HEAD --/)) {
1185                 print STDERR "Cannot rebase with uncommited changes:\n";
1186                 command_noisy('status');
1187                 exit 1;
1188         }
1189         unless ($_local) {
1190                 # rebase will checkout for us, so no need to do it explicitly
1191                 $_no_checkout = 'true';
1192                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1193         }
1194         command_noisy(rebase_cmd(), $gs->refname);
1195         if (auto_create_empty_directories($gs)) {
1196                 $gs->mkemptydirs;
1197         }
1198 }
1199
1200 sub cmd_show_ignore {
1201         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1202         $gs ||= Git::SVN->new;
1203         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1204         $gs->prop_walk($gs->path, $r, sub {
1205                 my ($gs, $path, $props) = @_;
1206                 print STDOUT "\n# $path\n";
1207                 my $s = $props->{'svn:ignore'} or return;
1208                 $s =~ s/[\r\n]+/\n/g;
1209                 $s =~ s/^\n+//;
1210                 chomp $s;
1211                 $s =~ s#^#$path#gm;
1212                 print STDOUT "$s\n";
1213         });
1214 }
1215
1216 sub cmd_show_externals {
1217         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1218         $gs ||= Git::SVN->new;
1219         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1220         $gs->prop_walk($gs->path, $r, sub {
1221                 my ($gs, $path, $props) = @_;
1222                 print STDOUT "\n# $path\n";
1223                 my $s = $props->{'svn:externals'} or return;
1224                 $s =~ s/[\r\n]+/\n/g;
1225                 chomp $s;
1226                 $s =~ s#^#$path#gm;
1227                 print STDOUT "$s\n";
1228         });
1229 }
1230
1231 sub cmd_create_ignore {
1232         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1233         $gs ||= Git::SVN->new;
1234         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1235         $gs->prop_walk($gs->path, $r, sub {
1236                 my ($gs, $path, $props) = @_;
1237                 # $path is of the form /path/to/dir/
1238                 $path = '.' . $path;
1239                 # SVN can have attributes on empty directories,
1240                 # which git won't track
1241                 mkpath([$path]) unless -d $path;
1242                 my $ignore = $path . '.gitignore';
1243                 my $s = $props->{'svn:ignore'} or return;
1244                 open(GITIGNORE, '>', $ignore)
1245                   or fatal("Failed to open `$ignore' for writing: $!");
1246                 $s =~ s/[\r\n]+/\n/g;
1247                 $s =~ s/^\n+//;
1248                 chomp $s;
1249                 # Prefix all patterns so that the ignore doesn't apply
1250                 # to sub-directories.
1251                 $s =~ s#^#/#gm;
1252                 print GITIGNORE "$s\n";
1253                 close(GITIGNORE)
1254                   or fatal("Failed to close `$ignore': $!");
1255                 command_noisy('add', '-f', $ignore);
1256         });
1257 }
1258
1259 sub cmd_mkdirs {
1260         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1261         $gs ||= Git::SVN->new;
1262         $gs->mkemptydirs($_revision);
1263 }
1264
1265 # get_svnprops(PATH)
1266 # ------------------
1267 # Helper for cmd_propget and cmd_proplist below.
1268 sub get_svnprops {
1269         my $path = shift;
1270         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1271         $gs ||= Git::SVN->new;
1272
1273         # prefix THE PATH by the sub-directory from which the user
1274         # invoked us.
1275         $path = $cmd_dir_prefix . $path;
1276         fatal("No such file or directory: $path") unless -e $path;
1277         my $is_dir = -d $path ? 1 : 0;
1278         $path = $gs->{path} . '/' . $path;
1279
1280         # canonicalize the path (otherwise libsvn will abort or fail to
1281         # find the file)
1282         $path = canonicalize_path($path);
1283
1284         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1285         my $props;
1286         if ($is_dir) {
1287                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1288         }
1289         else {
1290                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1291         }
1292         return $props;
1293 }
1294
1295 # cmd_propget (PROP, PATH)
1296 # ------------------------
1297 # Print the SVN property PROP for PATH.
1298 sub cmd_propget {
1299         my ($prop, $path) = @_;
1300         $path = '.' if not defined $path;
1301         usage(1) if not defined $prop;
1302         my $props = get_svnprops($path);
1303         if (not defined $props->{$prop}) {
1304                 fatal("`$path' does not have a `$prop' SVN property.");
1305         }
1306         print $props->{$prop} . "\n";
1307 }
1308
1309 # cmd_proplist (PATH)
1310 # -------------------
1311 # Print the list of SVN properties for PATH.
1312 sub cmd_proplist {
1313         my $path = shift;
1314         $path = '.' if not defined $path;
1315         my $props = get_svnprops($path);
1316         print "Properties on '$path':\n";
1317         foreach (sort keys %{$props}) {
1318                 print "  $_\n";
1319         }
1320 }
1321
1322 sub cmd_multi_init {
1323         my $url = shift;
1324         unless (defined $_trunk || @_branches || @_tags) {
1325                 usage(1);
1326         }
1327
1328         $_prefix = '' unless defined $_prefix;
1329         if (defined $url) {
1330                 $url = canonicalize_url($url);
1331                 init_subdir(@_);
1332         }
1333         do_git_init_db();
1334         if (defined $_trunk) {
1335                 $_trunk =~ s#^/+##;
1336                 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1337                 # try both old-style and new-style lookups:
1338                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1339                 unless ($gs_trunk) {
1340                         my ($trunk_url, $trunk_path) =
1341                                               complete_svn_url($url, $_trunk);
1342                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1343                                                    undef, $trunk_ref);
1344                 }
1345         }
1346         return unless @_branches || @_tags;
1347         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1348         foreach my $path (@_branches) {
1349                 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1350         }
1351         foreach my $path (@_tags) {
1352                 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1353         }
1354 }
1355
1356 sub cmd_multi_fetch {
1357         $Git::SVN::no_reuse_existing = undef;
1358         my $remotes = Git::SVN::read_all_remotes();
1359         foreach my $repo_id (sort keys %$remotes) {
1360                 if ($remotes->{$repo_id}->{url}) {
1361                         Git::SVN::fetch_all($repo_id, $remotes);
1362                 }
1363         }
1364 }
1365
1366 # this command is special because it requires no metadata
1367 sub cmd_commit_diff {
1368         my ($ta, $tb, $url) = @_;
1369         my $usage = "Usage: $0 commit-diff -r<revision> ".
1370                     "<tree-ish> <tree-ish> [<URL>]";
1371         fatal($usage) if (!defined $ta || !defined $tb);
1372         my $svn_path = '';
1373         if (!defined $url) {
1374                 my $gs = eval { Git::SVN->new };
1375                 if (!$gs) {
1376                         fatal("Needed URL or usable git-svn --id in ",
1377                               "the command-line\n", $usage);
1378                 }
1379                 $url = $gs->url;
1380                 $svn_path = $gs->path;
1381         }
1382         unless (defined $_revision) {
1383                 fatal("-r|--revision is a required argument\n", $usage);
1384         }
1385         if (defined $_message && defined $_file) {
1386                 fatal("Both --message/-m and --file/-F specified ",
1387                       "for the commit message.\n",
1388                       "I have no idea what you mean");
1389         }
1390         if (defined $_file) {
1391                 $_message = file_to_s($_file);
1392         } else {
1393                 $_message ||= get_commit_entry($tb)->{log};
1394         }
1395         my $ra ||= Git::SVN::Ra->new($url);
1396         my $r = $_revision;
1397         if ($r eq 'HEAD') {
1398                 $r = $ra->get_latest_revnum;
1399         } elsif ($r !~ /^\d+$/) {
1400                 die "revision argument: $r not understood by git-svn\n";
1401         }
1402         my %ed_opts = ( r => $r,
1403                         log => $_message,
1404                         ra => $ra,
1405                         tree_a => $ta,
1406                         tree_b => $tb,
1407                         editor_cb => sub { print "Committed r$_[0]\n" },
1408                         svn_path => $svn_path );
1409         if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1410                 print "No changes\n$ta == $tb\n";
1411         }
1412 }
1413
1414 sub escape_uri_only {
1415         my ($uri) = @_;
1416         my @tmp;
1417         foreach (split m{/}, $uri) {
1418                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1419                 push @tmp, $_;
1420         }
1421         join('/', @tmp);
1422 }
1423
1424 sub escape_url {
1425         my ($url) = @_;
1426         if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1427                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1428                 $url = "$scheme://$domain$uri";
1429         }
1430         $url;
1431 }
1432
1433 sub cmd_info {
1434         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1435         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1436         if (exists $_[1]) {
1437                 die "Too many arguments specified\n";
1438         }
1439
1440         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1441
1442         if (!$file_type && !$diff_status) {
1443                 print STDERR "svn: '$path' is not under version control\n";
1444                 exit 1;
1445         }
1446
1447         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1448         unless ($gs) {
1449                 die "Unable to determine upstream SVN information from ",
1450                     "working tree history\n";
1451         }
1452
1453         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1454         $path = "." if $path eq "";
1455
1456         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1457
1458         if ($_url) {
1459                 print escape_url($full_url), "\n";
1460                 return;
1461         }
1462
1463         my $result = "Path: $path\n";
1464         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1465         $result .= "URL: " . escape_url($full_url) . "\n";
1466
1467         eval {
1468                 my $repos_root = $gs->repos_root;
1469                 Git::SVN::remove_username($repos_root);
1470                 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1471         };
1472         if ($@) {
1473                 $result .= "Repository Root: (offline)\n";
1474         }
1475         ::_req_svn();
1476         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1477                 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1478         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1479
1480         $result .= "Node Kind: " .
1481                    ($file_type eq "dir" ? "directory" : "file") . "\n";
1482
1483         my $schedule = $diff_status eq "A"
1484                        ? "add"
1485                        : ($diff_status eq "D" ? "delete" : "normal");
1486         $result .= "Schedule: $schedule\n";
1487
1488         if ($diff_status eq "A") {
1489                 print $result, "\n";
1490                 return;
1491         }
1492
1493         my ($lc_author, $lc_rev, $lc_date_utc);
1494         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1495         my $log = command_output_pipe(@args);
1496         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1497         while (<$log>) {
1498                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1499                         $lc_author = $1;
1500                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1501                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1502                         (undef, $lc_rev, undef) = ::extract_metadata($1);
1503                 }
1504         }
1505         close $log;
1506
1507         Git::SVN::Log::set_local_timezone();
1508
1509         $result .= "Last Changed Author: $lc_author\n";
1510         $result .= "Last Changed Rev: $lc_rev\n";
1511         $result .= "Last Changed Date: " .
1512                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1513
1514         if ($file_type ne "dir") {
1515                 my $text_last_updated_date =
1516                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1517                 $result .=
1518                     "Text Last Updated: " .
1519                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
1520                     "\n";
1521                 my $checksum;
1522                 if ($diff_status eq "D") {
1523                         my ($fh, $ctx) =
1524                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
1525                         if ($file_type eq "link") {
1526                                 my $file_name = <$fh>;
1527                                 $checksum = md5sum("link $file_name");
1528                         } else {
1529                                 $checksum = md5sum($fh);
1530                         }
1531                         command_close_pipe($fh, $ctx);
1532                 } elsif ($file_type eq "link") {
1533                         my $file_name =
1534                             command(qw(cat-file blob), "HEAD:$path");
1535                         $checksum =
1536                             md5sum("link " . $file_name);
1537                 } else {
1538                         open FILE, "<", $path or die $!;
1539                         $checksum = md5sum(\*FILE);
1540                         close FILE or die $!;
1541                 }
1542                 $result .= "Checksum: " . $checksum . "\n";
1543         }
1544
1545         print $result, "\n";
1546 }
1547
1548 sub cmd_reset {
1549         my $target = shift || $_revision or die "SVN revision required\n";
1550         $target = $1 if $target =~ /^r(\d+)$/;
1551         $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1552         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1553         unless ($gs) {
1554                 die "Unable to determine upstream SVN information from ".
1555                     "history\n";
1556         }
1557         my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1558         die "Cannot find SVN revision $target\n" unless defined($c);
1559         $gs->rev_map_set($r, $c, 'reset', $uuid);
1560         print "r$r = $c ($gs->{ref_id})\n";
1561 }
1562
1563 sub cmd_gc {
1564         if (!can_compress()) {
1565                 warn "Compress::Zlib could not be found; unhandled.log " .
1566                      "files will not be compressed.\n";
1567         }
1568         find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1569 }
1570
1571 ########################### utility functions #########################
1572
1573 sub rebase_cmd {
1574         my @cmd = qw/rebase/;
1575         push @cmd, '-v' if $_verbose;
1576         push @cmd, qw/--merge/ if $_merge;
1577         push @cmd, "--strategy=$_strategy" if $_strategy;
1578         push @cmd, "--preserve-merges" if $_preserve_merges;
1579         @cmd;
1580 }
1581
1582 sub post_fetch_checkout {
1583         return if $_no_checkout;
1584         return if verify_ref('HEAD^0');
1585         my $gs = $Git::SVN::_head or return;
1586
1587         # look for "trunk" ref if it exists
1588         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1589         my $fetch = $remote->{fetch};
1590         if ($fetch) {
1591                 foreach my $p (keys %$fetch) {
1592                         basename($fetch->{$p}) eq 'trunk' or next;
1593                         $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1594                         last;
1595                 }
1596         }
1597
1598         command_noisy(qw(update-ref HEAD), $gs->refname);
1599         return unless verify_ref('HEAD^0');
1600
1601         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1602         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1603         return if -f $index;
1604
1605         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1606         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1607         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1608         print STDERR "Checked out HEAD:\n  ",
1609                      $gs->full_url, " r", $gs->last_rev, "\n";
1610         if (auto_create_empty_directories($gs)) {
1611                 $gs->mkemptydirs($gs->last_rev);
1612         }
1613 }
1614
1615 sub complete_svn_url {
1616         my ($url, $path) = @_;
1617         $path =~ s#/+$##;
1618
1619         # If the path is not a URL...
1620         if ($path !~ m#^[a-z\+]+://#) {
1621                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1622                         fatal("E: '$path' is not a complete URL ",
1623                               "and a separate URL is not specified");
1624                 }
1625                 return ($url, $path);
1626         }
1627         return ($path, '');
1628 }
1629
1630 sub complete_url_ls_init {
1631         my ($ra, $repo_path, $switch, $pfx) = @_;
1632         unless ($repo_path) {
1633                 print STDERR "W: $switch not specified\n";
1634                 return;
1635         }
1636         $repo_path =~ s#/+$##;
1637         if ($repo_path =~ m#^[a-z\+]+://#) {
1638                 $ra = Git::SVN::Ra->new($repo_path);
1639                 $repo_path = '';
1640         } else {
1641                 $repo_path =~ s#^/+##;
1642                 unless ($ra) {
1643                         fatal("E: '$repo_path' is not a complete URL ",
1644                               "and a separate URL is not specified");
1645                 }
1646         }
1647         my $url = $ra->url;
1648         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1649         my $k = "svn-remote.$gs->{repo_id}.url";
1650         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1651         if ($orig_url && ($orig_url ne $gs->url)) {
1652                 die "$k already set: $orig_url\n",
1653                     "wanted to set to: $gs->url\n";
1654         }
1655         command_oneline('config', $k, $gs->url) unless $orig_url;
1656
1657         my $remote_path = $gs->path . "/$repo_path";
1658         $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1659         $remote_path =~ s#/+#/#g;
1660         $remote_path =~ s#^/##g;
1661         $remote_path .= "/*" if $remote_path !~ /\*/;
1662         my ($n) = ($switch =~ /^--(\w+)/);
1663         if (length $pfx && $pfx !~ m#/$#) {
1664                 die "--prefix='$pfx' must have a trailing slash '/'\n";
1665         }
1666         command_noisy('config',
1667                       '--add',
1668                       "svn-remote.$gs->{repo_id}.$n",
1669                       "$remote_path:refs/remotes/$pfx*" .
1670                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1671 }
1672
1673 sub verify_ref {
1674         my ($ref) = @_;
1675         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1676                                { STDERR => 0 }); };
1677 }
1678
1679 sub get_tree_from_treeish {
1680         my ($treeish) = @_;
1681         # $treeish can be a symbolic ref, too:
1682         my $type = command_oneline(qw/cat-file -t/, $treeish);
1683         my $expected;
1684         while ($type eq 'tag') {
1685                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1686         }
1687         if ($type eq 'commit') {
1688                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1689                                                     $treeish))[0];
1690                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1691                 die "Unable to get tree from $treeish\n" unless $expected;
1692         } elsif ($type eq 'tree') {
1693                 $expected = $treeish;
1694         } else {
1695                 die "$treeish is a $type, expected tree, tag or commit\n";
1696         }
1697         return $expected;
1698 }
1699
1700 sub get_commit_entry {
1701         my ($treeish) = shift;
1702         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1703         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1704         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1705         open my $log_fh, '>', $commit_editmsg or croak $!;
1706
1707         my $type = command_oneline(qw/cat-file -t/, $treeish);
1708         if ($type eq 'commit' || $type eq 'tag') {
1709                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1710                                                          $type, $treeish);
1711                 my $in_msg = 0;
1712                 my $author;
1713                 my $saw_from = 0;
1714                 my $msgbuf = "";
1715                 while (<$msg_fh>) {
1716                         if (!$in_msg) {
1717                                 $in_msg = 1 if (/^\s*$/);
1718                                 $author = $1 if (/^author (.*>)/);
1719                         } elsif (/^git-svn-id: /) {
1720                                 # skip this for now, we regenerate the
1721                                 # correct one on re-fetch anyways
1722                                 # TODO: set *:merge properties or like...
1723                         } else {
1724                                 if (/^From:/ || /^Signed-off-by:/) {
1725                                         $saw_from = 1;
1726                                 }
1727                                 $msgbuf .= $_;
1728                         }
1729                 }
1730                 $msgbuf =~ s/\s+$//s;
1731                 if ($Git::SVN::_add_author_from && defined($author)
1732                     && !$saw_from) {
1733                         $msgbuf .= "\n\nFrom: $author";
1734                 }
1735                 print $log_fh $msgbuf or croak $!;
1736                 command_close_pipe($msg_fh, $ctx);
1737         }
1738         close $log_fh or croak $!;
1739
1740         if ($_edit || ($type eq 'tree')) {
1741                 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1742                 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1743         }
1744         rename $commit_editmsg, $commit_msg or croak $!;
1745         {
1746                 require Encode;
1747                 # SVN requires messages to be UTF-8 when entering the repo
1748                 local $/;
1749                 open $log_fh, '<', $commit_msg or croak $!;
1750                 binmode $log_fh;
1751                 chomp($log_entry{log} = <$log_fh>);
1752
1753                 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1754                 my $msg = $log_entry{log};
1755
1756                 eval { $msg = Encode::decode($enc, $msg, 1) };
1757                 if ($@) {
1758                         die "Could not decode as $enc:\n", $msg,
1759                             "\nPerhaps you need to set i18n.commitencoding\n";
1760                 }
1761
1762                 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1763                 die "Could not encode as UTF-8:\n$msg\n" if $@;
1764
1765                 $log_entry{log} = $msg;
1766
1767                 close $log_fh or croak $!;
1768         }
1769         unlink $commit_msg;
1770         \%log_entry;
1771 }
1772
1773 sub s_to_file {
1774         my ($str, $file, $mode) = @_;
1775         open my $fd,'>',$file or croak $!;
1776         print $fd $str,"\n" or croak $!;
1777         close $fd or croak $!;
1778         chmod ($mode &~ umask, $file) if (defined $mode);
1779 }
1780
1781 sub file_to_s {
1782         my $file = shift;
1783         open my $fd,'<',$file or croak "$!: file: $file\n";
1784         local $/;
1785         my $ret = <$fd>;
1786         close $fd or croak $!;
1787         $ret =~ s/\s*$//s;
1788         return $ret;
1789 }
1790
1791 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1792 sub load_authors {
1793         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1794         my $log = $cmd eq 'log';
1795         while (<$authors>) {
1796                 chomp;
1797                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1798                 my ($user, $name, $email) = ($1, $2, $3);
1799                 if ($log) {
1800                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1801                 } else {
1802                         $users{$user} = [$name, $email];
1803                 }
1804         }
1805         close $authors or croak $!;
1806 }
1807
1808 # convert GetOpt::Long specs for use by git-config
1809 sub read_git_config {
1810         my $opts = shift;
1811         my @config_only;
1812         foreach my $o (keys %$opts) {
1813                 # if we have mixedCase and a long option-only, then
1814                 # it's a config-only variable that we don't need for
1815                 # the command-line.
1816                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1817                 my $v = $opts->{$o};
1818                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1819                 $key =~ s/-//g;
1820                 my $arg = 'git config';
1821                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1822                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1823                 if (ref $v eq 'ARRAY') {
1824                         chomp(my @tmp = `$arg --get-all svn.$key`);
1825                         @$v = @tmp if @tmp;
1826                 } else {
1827                         chomp(my $tmp = `$arg --get svn.$key`);
1828                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1829                                 $$v = $tmp;
1830                         }
1831                 }
1832         }
1833         delete @$opts{@config_only} if @config_only;
1834 }
1835
1836 sub extract_metadata {
1837         my $id = shift or return (undef, undef, undef);
1838         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1839                                                         \s([a-f\d\-]+)$/ix);
1840         if (!defined $rev || !$uuid || !$url) {
1841                 # some of the original repositories I made had
1842                 # identifiers like this:
1843                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1844         }
1845         return ($url, $rev, $uuid);
1846 }
1847
1848 sub cmt_metadata {
1849         return extract_metadata((grep(/^git-svn-id: /,
1850                 command(qw/cat-file commit/, shift)))[-1]);
1851 }
1852
1853 sub cmt_sha2rev_batch {
1854         my %s2r;
1855         my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1856         my $list = shift;
1857
1858         foreach my $sha (@{$list}) {
1859                 my $first = 1;
1860                 my $size = 0;
1861                 print $out $sha, "\n";
1862
1863                 while (my $line = <$in>) {
1864                         if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1865                                 last;
1866                         } elsif ($first &&
1867                                $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1868                                 $first = 0;
1869                                 $size = $1;
1870                                 next;
1871                         } elsif ($line =~ /^(git-svn-id: )/) {
1872                                 my (undef, $rev, undef) =
1873                                                       extract_metadata($line);
1874                                 $s2r{$sha} = $rev;
1875                         }
1876
1877                         $size -= length($line);
1878                         last if ($size == 0);
1879                 }
1880         }
1881
1882         command_close_bidi_pipe($pid, $in, $out, $ctx);
1883
1884         return \%s2r;
1885 }
1886
1887 sub working_head_info {
1888         my ($head, $refs) = @_;
1889         my @args = qw/rev-list --first-parent --pretty=medium/;
1890         my ($fh, $ctx) = command_output_pipe(@args, $head);
1891         my $hash;
1892         my %max;
1893         while (<$fh>) {
1894                 if ( m{^commit ($::sha1)$} ) {
1895                         unshift @$refs, $hash if $hash and $refs;
1896                         $hash = $1;
1897                         next;
1898                 }
1899                 next unless s{^\s*(git-svn-id:)}{$1};
1900                 my ($url, $rev, $uuid) = extract_metadata($_);
1901                 if (defined $url && defined $rev) {
1902                         next if $max{$url} and $max{$url} < $rev;
1903                         if (my $gs = Git::SVN->find_by_url($url)) {
1904                                 my $c = $gs->rev_map_get($rev, $uuid);
1905                                 if ($c && $c eq $hash) {
1906                                         close $fh; # break the pipe
1907                                         return ($url, $rev, $uuid, $gs);
1908                                 } else {
1909                                         $max{$url} ||= $gs->rev_map_max;
1910                                 }
1911                         }
1912                 }
1913         }
1914         command_close_pipe($fh, $ctx);
1915         (undef, undef, undef, undef);
1916 }
1917
1918 sub read_commit_parents {
1919         my ($parents, $c) = @_;
1920         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1921         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1922         @{$parents->{$c}} = split(/ /, $p);
1923 }
1924
1925 sub linearize_history {
1926         my ($gs, $refs) = @_;
1927         my %parents;
1928         foreach my $c (@$refs) {
1929                 read_commit_parents(\%parents, $c);
1930         }
1931
1932         my @linear_refs;
1933         my %skip = ();
1934         my $last_svn_commit = $gs->last_commit;
1935         foreach my $c (reverse @$refs) {
1936                 next if $c eq $last_svn_commit;
1937                 last if $skip{$c};
1938
1939                 unshift @linear_refs, $c;
1940                 $skip{$c} = 1;
1941
1942                 # we only want the first parent to diff against for linear
1943                 # history, we save the rest to inject when we finalize the
1944                 # svn commit
1945                 my $fp_a = verify_ref("$c~1");
1946                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1947                 if (!$fp_a || !$fp_b) {
1948                         die "Commit $c\n",
1949                             "has no parent commit, and therefore ",
1950                             "nothing to diff against.\n",
1951                             "You should be working from a repository ",
1952                             "originally created by git-svn\n";
1953                 }
1954                 if ($fp_a ne $fp_b) {
1955                         die "$c~1 = $fp_a, however parsing commit $c ",
1956                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1957                 }
1958
1959                 foreach my $p (@{$parents{$c}}) {
1960                         $skip{$p} = 1;
1961                 }
1962         }
1963         (\@linear_refs, \%parents);
1964 }
1965
1966 sub find_file_type_and_diff_status {
1967         my ($path) = @_;
1968         return ('dir', '') if $path eq '';
1969
1970         my $diff_output =
1971             command_oneline(qw(diff --cached --name-status --), $path) || "";
1972         my $diff_status = (split(' ', $diff_output))[0] || "";
1973
1974         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1975
1976         return (undef, undef) if !$diff_status && !$ls_tree;
1977
1978         if ($diff_status eq "A") {
1979                 return ("link", $diff_status) if -l $path;
1980                 return ("dir", $diff_status) if -d $path;
1981                 return ("file", $diff_status);
1982         }
1983
1984         my $mode = (split(' ', $ls_tree))[0] || "";
1985
1986         return ("link", $diff_status) if $mode eq "120000";
1987         return ("dir", $diff_status) if $mode eq "040000";
1988         return ("file", $diff_status);
1989 }
1990
1991 sub md5sum {
1992         my $arg = shift;
1993         my $ref = ref $arg;
1994         my $md5 = Digest::MD5->new();
1995         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1996                 $md5->addfile($arg) or croak $!;
1997         } elsif ($ref eq 'SCALAR') {
1998                 $md5->add($$arg) or croak $!;
1999         } elsif (!$ref) {
2000                 $md5->add($arg) or croak $!;
2001         } else {
2002                 fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2003         }
2004         return $md5->hexdigest();
2005 }
2006
2007 sub gc_directory {
2008         if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
2009                 my $out_filename = $_ . ".gz";
2010                 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2011                 binmode $in_fh;
2012                 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2013                                 die "Unable to open $out_filename: $!\n";
2014
2015                 my $res;
2016                 while ($res = sysread($in_fh, my $str, 1024)) {
2017                         $gz->gzwrite($str) or
2018                                 die "Unable to write: ".$gz->gzerror()."!\n";
2019                 }
2020                 unlink $_ or die "unlink $File::Find::name: $!\n";
2021         } elsif (-f $_ && basename($_) eq "index") {
2022                 unlink $_ or die "unlink $_: $!\n";
2023         }
2024 }
2025
2026 __END__
2027
2028 Data structures:
2029
2030
2031 $remotes = { # returned by read_all_remotes()
2032         'svn' => {
2033                 # svn-remote.svn.url=https://svn.musicpd.org
2034                 url => 'https://svn.musicpd.org',
2035                 # svn-remote.svn.fetch=mpd/trunk:trunk
2036                 fetch => {
2037                         'mpd/trunk' => 'trunk',
2038                 },
2039                 # svn-remote.svn.tags=mpd/tags/*:tags/*
2040                 tags => {
2041                         path => {
2042                                 left => 'mpd/tags',
2043                                 right => '',
2044                                 regex => qr!mpd/tags/([^/]+)$!,
2045                                 glob => 'tags/*',
2046                         },
2047                         ref => {
2048                                 left => 'tags',
2049                                 right => '',
2050                                 regex => qr!tags/([^/]+)$!,
2051                                 glob => 'tags/*',
2052                         },
2053                 }
2054         }
2055 };
2056
2057 $log_entry hashref as returned by libsvn_log_entry()
2058 {
2059         log => 'whitespace-formatted log entry
2060 ',                                              # trailing newline is preserved
2061         revision => '8',                        # integer
2062         date => '2004-02-24T17:01:44.108345Z',  # commit date
2063         author => 'committer name'
2064 };
2065
2066
2067 # this is generated by generate_diff();
2068 @mods = array of diff-index line hashes, each element represents one line
2069         of diff-index output
2070
2071 diff-index line ($m hash)
2072 {
2073         mode_a => first column of diff-index output, no leading ':',
2074         mode_b => second column of diff-index output,
2075         sha1_b => sha1sum of the final blob,
2076         chg => change type [MCRADT],
2077         file_a => original file name of a file (iff chg is 'C' or 'R')
2078         file_b => new/current file name of a file (any chg)
2079 }
2080 ;
2081
2082 # retval of read_url_paths{,_all}();
2083 $l_map = {
2084         # repository root url
2085         'https://svn.musicpd.org' => {
2086                 # repository path               # GIT_SVN_ID
2087                 'mpd/trunk'             =>      'trunk',
2088                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
2089         },
2090 }
2091
2092 Notes:
2093         I don't trust the each() function on unless I created %hash myself
2094         because the internal iterator may not have started at base.