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