Code

git-svn: cleanup: avoid re-use()ing Git.pm in sub-packages
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $SVN_URL
8                 $GIT_SVN_INDEX $GIT_SVN
9                 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 use Cwd qw/abs_path/;
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
17 my $LC_ALL = $ENV{LC_ALL};
18 my $TZ = $ENV{TZ};
19 # make sure the svn binary gives consistent output between locales and TZs:
20 $ENV{TZ} = 'UTC';
21 $ENV{LC_ALL} = 'C';
22 $| = 1; # unbuffer STDOUT
24 # properties that we do not log:
25 my %SKIP = ( 'svn:wc:ra_dav:version-url' => 1,
26              'svn:special' => 1,
27              'svn:executable' => 1,
28              'svn:entry:committed-rev' => 1,
29              'svn:entry:last-author' => 1,
30              'svn:entry:uuid' => 1,
31              'svn:entry:committed-date' => 1,
32 );
34 sub fatal (@) { print STDERR @_; exit 1 }
35 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
36 require SVN::Ra;
37 require SVN::Delta;
38 if ($SVN::Core::VERSION lt '1.1.0') {
39         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
40 }
41 push @Git::SVN::Ra::ISA, 'SVN::Ra';
42 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
43 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
44 use Carp qw/croak/;
45 use IO::File qw//;
46 use File::Basename qw/dirname basename/;
47 use File::Path qw/mkpath/;
48 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
49 use POSIX qw/strftime/;
50 use IPC::Open3;
51 use Memoize;
52 use Git;
53 memoize('revisions_eq');
54 memoize('cmt_metadata');
55 memoize('get_commit_time');
57 BEGIN {
58         my $s;
59         foreach (qw/command command_oneline command_noisy command_output_pipe
60                     command_input_pipe command_close_pipe/) {
61                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
62                       "*$_ = *Git::$_; ";
63         }
64         eval $s;
65 }
67 my ($SVN);
69 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
70 my $sha1 = qr/[a-f\d]{40}/;
71 my $sha1_short = qr/[a-f\d]{4,40}/;
72 my $_esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
73 my ($_revision,$_stdin,$_help,$_rmdir,$_edit,
74         $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
75         $_repack, $_repack_nr, $_repack_flags, $_q,
76         $_message, $_file, $_no_metadata,
77         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
78         $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
79         $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
80         $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
81         $_pager, $_color, $_prefix);
82 my (@_branch_from, %tree_map, %users, %rusers);
83 my @repo_path_split_cache;
84 use vars qw/$_follow_parent/;
86 my %fc_opts = ( 'branch|b=s' => \@_branch_from,
87                 'follow-parent|follow' => \$_follow_parent,
88                 'branch-all-refs|B' => \$_branch_all_refs,
89                 'authors-file|A=s' => \$_authors,
90                 'repack:i' => \$_repack,
91                 'no-metadata' => \$_no_metadata,
92                 'quiet|q' => \$_q,
93                 'username=s' => \$Git::SVN::Prompt::_username,
94                 'config-dir=s' => \$Git::SVN::Ra::config_dir,
95                 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96                 'ignore-nodate' => \$_ignore_nodate,
97                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
99 my ($_trunk, $_tags, $_branches);
100 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
101                 'tags|t=s' => \$_tags,
102                 'branches|b=s' => \$_branches );
103 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
104 my %cmt_opts = ( 'edit|e' => \$_edit,
105                 'rmdir' => \$_rmdir,
106                 'find-copies-harder' => \$_find_copies_harder,
107                 'l=i' => \$_l,
108                 'copy-similarity|C=i'=> \$_cp_similarity
109 );
111 my %cmd = (
112         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
113                         { 'revision|r=s' => \$_revision, %fc_opts } ],
114         init => [ \&init, "Initialize a repo for tracking" .
115                           " (requires URL argument)",
116                           \%init_opts ],
117         dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
118                         { 'merge|m|M' => \$_merge,
119                           'strategy|s=s' => \$_strategy,
120                           'dry-run|n' => \$_dry_run,
121                         %cmt_opts, %fc_opts } ],
122         'set-tree' => [ \&commit, "Set an SVN repository to a git tree-ish",
123                         {       'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
124         'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
125                         { 'revision|r=i' => \$_revision } ],
126         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
127                         { 'copy-remote|remote=s' => \$_cp_remote,
128                           'upgrade' => \$_upgrade } ],
129         'graft-branches' => [ \&graft_branches,
130                         'Detect merges/branches from already imported history',
131                         { 'merge-rx|m' => \@_opt_m,
132                           'branch|b=s' => \@_branch_from,
133                           'branch-all-refs|B' => \$_branch_all_refs,
134                           'no-default-regex' => \$_no_default_regex,
135                           'no-graft-copy' => \$_no_graft_copy } ],
136         'multi-init' => [ \&multi_init,
137                         'Initialize multiple trees (like git-svnimport)',
138                         { %multi_opts, %init_opts,
139                          'revision|r=i' => \$_revision,
140                          'username=s' => \$Git::SVN::Prompt::_username,
141                          'config-dir=s' => \$Git::SVN::Ra::config_dir,
142                          'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
143                          'prefix=s' => \$_prefix,
144                         } ],
145         'multi-fetch' => [ \&multi_fetch,
146                         'Fetch multiple trees (like git-svnimport)',
147                         \%fc_opts ],
148         'log' => [ \&show_log, 'Show commit logs',
149                         { 'limit=i' => \$_limit,
150                           'revision|r=s' => \$_revision,
151                           'verbose|v' => \$_verbose,
152                           'incremental' => \$_incremental,
153                           'oneline' => \$_oneline,
154                           'show-commit' => \$_show_commit,
155                           'non-recursive' => \$_non_recursive,
156                           'authors-file|A=s' => \$_authors,
157                           'color' => \$_color,
158                           'pager=s' => \$_pager,
159                         } ],
160         'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
161                         { 'message|m=s' => \$_message,
162                           'file|F=s' => \$_file,
163                           'revision|r=s' => \$_revision,
164                         %cmt_opts } ],
165 );
167 my $cmd;
168 for (my $i = 0; $i < @ARGV; $i++) {
169         if (defined $cmd{$ARGV[$i]}) {
170                 $cmd = $ARGV[$i];
171                 splice @ARGV, $i, 1;
172                 last;
173         }
174 };
176 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
178 read_repo_config(\%opts);
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
180                                 'version|V' => \$_version,
181                                 'id|i=s' => \$GIT_SVN);
182 exit 1 if (!$rv && $cmd ne 'log');
184 set_default_vals();
185 usage(0) if $_help;
186 version() if $_version;
187 usage(1) unless defined $cmd;
188 init_vars();
189 load_authors() if $_authors;
190 load_all_refs() if $_branch_all_refs;
191 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
192 $cmd{$cmd}->[0]->(@ARGV);
193 exit 0;
195 ####################### primary functions ######################
196 sub usage {
197         my $exit = shift || 0;
198         my $fd = $exit ? \*STDERR : \*STDOUT;
199         print $fd <<"";
200 git-svn - bidirectional operations between a single Subversion tree and git
201 Usage: $0 <command> [options] [arguments]\n
203         print $fd "Available commands:\n" unless $cmd;
205         foreach (sort keys %cmd) {
206                 next if $cmd && $cmd ne $_;
207                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
208                 foreach (keys %{$cmd{$_}->[2]}) {
209                         # prints out arguments as they should be passed:
210                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
211                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
212                                                         "--$_" : "-$_" }
213                                                 split /\|/,$_)," $x\n";
214                 }
215         }
216         print $fd <<"";
217 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
218 arbitrary identifier if you're tracking multiple SVN branches/repositories in
219 one git repository and want to keep them separate.  See git-svn(1) for more
220 information.
222         exit $exit;
225 sub version {
226         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
227         exit 0;
230 sub rebuild {
231         if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
232                 copy_remote_ref();
233         }
234         $SVN_URL = shift or undef;
235         my $newest_rev = 0;
236         if ($_upgrade) {
237                 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
238                               $GIT_SVN-HEAD");
239         } else {
240                 check_upgrade_needed();
241         }
243         my ($rev_list, $ctx) = command_output_pipe("rev-list",
244                                                    "refs/remotes/$GIT_SVN");
245         my $latest;
246         my $svn_uuid;
247         while (<$rev_list>) {
248                 chomp;
249                 my $c = $_;
250                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
251                 my @commit = grep(/^git-svn-id: /,
252                                   command(qw/cat-file commit/, $c));
253                 next if (!@commit); # skip merges
254                 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
255                 if (!defined $rev || !$uuid) {
256                         croak "Unable to extract revision or UUID from ",
257                                 "$c, $commit[$#commit]\n";
258                 }
260                 # if we merged or otherwise started elsewhere, this is
261                 # how we break out of it
262                 next if (defined $svn_uuid && ($uuid ne $svn_uuid));
263                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
265                 unless (defined $latest) {
266                         if (!$SVN_URL && !$url) {
267                                 croak "SVN repository location required: $url\n";
268                         }
269                         $SVN_URL ||= $url;
270                         $svn_uuid ||= $uuid;
271                         setup_git_svn();
272                         $latest = $rev;
273                 }
274                 revdb_set($REVDB, $rev, $c);
275                 print "r$rev = $c\n";
276                 $newest_rev = $rev if ($rev > $newest_rev);
277         }
278         command_close_pipe($rev_list, $ctx);
281 sub init {
282         my $url = shift or die "SVN repository location required " .
283                                 "as a command-line argument\n";
284         $url =~ s!/+$!!; # strip trailing slash
286         if (my $repo_path = shift) {
287                 unless (-d $repo_path) {
288                         mkpath([$repo_path]);
289                 }
290                 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
291                 init_vars();
292         }
294         $SVN_URL = $url;
295         unless (-d $GIT_DIR) {
296                 my @init_db = ('init');
297                 push @init_db, "--template=$_template" if defined $_template;
298                 push @init_db, "--shared" if defined $_shared;
299                 command_noisy(@init_db);
300         }
301         setup_git_svn();
304 sub cmd_fetch {
305         fetch_child_id($GIT_SVN, @_);
308 sub fetch {
309         check_upgrade_needed();
310         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
311         my $ret = fetch_lib(@_);
312         if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
313                 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
314         }
315         return $ret;
318 sub fetch_lib {
319         my (@parents) = @_;
320         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
321         $SVN ||= Git::SVN::Ra->new($SVN_URL);
322         my ($last_rev, $last_commit) = svn_grab_base_rev();
323         my ($base, $head) = libsvn_parse_revision($last_rev);
324         if ($base > $head) {
325                 return { revision => $last_rev, commit => $last_commit }
326         }
327         my $index = set_index($GIT_SVN_INDEX);
329         # limit ourselves and also fork() since get_log won't release memory
330         # after processing a revision and SVN stuff seems to leak
331         my $inc = 1000;
332         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
333         if (defined $last_commit) {
334                 unless (-e $GIT_SVN_INDEX) {
335                         command_noisy('read-tree', $last_commit);
336                 }
337                 my $x = command_oneline('write-tree');
338                 my ($y) = (command(qw/cat-file commit/, $last_commit)
339                                                         =~ /^tree ($sha1)/m);
340                 if ($y ne $x) {
341                         unlink $GIT_SVN_INDEX or croak $!;
342                         command_noisy('read-tree', $last_commit);
343                 }
344                 $x = command_oneline('write-tree');
345                 if ($y ne $x) {
346                         print STDERR "trees ($last_commit) $y != $x\n",
347                                  "Something is seriously wrong...\n";
348                 }
349         }
350         while (1) {
351                 # fork, because using SVN::Pool with get_log() still doesn't
352                 # seem to help enough to keep memory usage down.
353                 defined(my $pid = fork) or croak $!;
354                 if (!$pid) {
355                         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
357                         # Yes I'm perfectly aware that the fourth argument
358                         # below is the limit revisions number.  Unfortunately
359                         # performance sucks with it enabled, so it's much
360                         # faster to fetch revision ranges instead of relying
361                         # on the limiter.
362                         $SVN->dup->get_log([''], $min, $max, 0, 1, 1,
363                                 sub {
364                                         my $log_msg;
365                                         if ($last_commit) {
366                                                 $log_msg = libsvn_fetch(
367                                                         $last_commit, @_);
368                                                 $last_commit = git_commit(
369                                                         $log_msg,
370                                                         $last_commit,
371                                                         @parents);
372                                         } else {
373                                                 $log_msg = libsvn_new_tree(@_);
374                                                 $last_commit = git_commit(
375                                                         $log_msg, @parents);
376                                         }
377                                 });
378                         exit 0;
379                 }
380                 waitpid $pid, 0;
381                 croak $? if $?;
382                 ($last_rev, $last_commit) = svn_grab_base_rev();
383                 last if ($max >= $head);
384                 $min = $max + 1;
385                 $max += $inc;
386                 $max = $head if ($max > $head);
387                 $SVN = Git::SVN::Ra->new($SVN_URL);
388         }
389         restore_index($index);
390         return { revision => $last_rev, commit => $last_commit };
393 sub commit {
394         my (@commits) = @_;
395         check_upgrade_needed();
396         if ($_stdin || !@commits) {
397                 print "Reading from stdin...\n";
398                 @commits = ();
399                 while (<STDIN>) {
400                         if (/\b($sha1_short)\b/o) {
401                                 unshift @commits, $1;
402                         }
403                 }
404         }
405         my @revs;
406         foreach my $c (@commits) {
407                 my @tmp = command('rev-parse',$c);
408                 if (scalar @tmp == 1) {
409                         push @revs, $tmp[0];
410                 } elsif (scalar @tmp > 1) {
411                         push @revs, reverse(command('rev-list',@tmp));
412                 } else {
413                         die "Failed to rev-parse $c\n";
414                 }
415         }
416         commit_lib(@revs);
417         print "Done committing ",scalar @revs," revisions to SVN\n";
420 sub commit_lib {
421         my (@revs) = @_;
422         my ($r_last, $cmt_last) = svn_grab_base_rev();
423         defined $r_last or die "Must have an existing revision to commit\n";
424         my $fetched = fetch();
425         if ($r_last != $fetched->{revision}) {
426                 print STDERR "There are new revisions that were fetched ",
427                                 "and need to be merged (or acknowledged) ",
428                                 "before committing.\n",
429                                 "last rev: $r_last\n",
430                                 " current: $fetched->{revision}\n";
431                 exit 1;
432         }
433         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
435         my $repo;
436         set_svn_commit_env();
437         foreach my $c (@revs) {
438                 my $log_msg = get_commit_message($c, $commit_msg);
440                 # fork for each commit because there's a memory leak I
441                 # can't track down... (it's probably in the SVN code)
442                 defined(my $pid = open my $fh, '-|') or croak $!;
443                 if (!$pid) {
444                         my $pool = SVN::Pool->new;
445                         my $ed = SVN::Git::Editor->new(
446                                         {       r => $r_last,
447                                                 ra => $SVN->dup,
448                                                 c => $c,
449                                                 svn_path => $SVN->{svn_path},
450                                         },
451                                         $SVN->get_commit_editor(
452                                                 $log_msg->{msg},
453                                                 sub {
454                                                         libsvn_commit_cb(
455                                                                 @_, $c,
456                                                                 $log_msg->{msg},
457                                                                 $r_last,
458                                                                 $cmt_last)
459                                                 }, $pool)
460                                         );
461                         my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
462                         if (@$mods == 0) {
463                                 print "No changes\nr$r_last = $cmt_last\n";
464                                 $ed->abort_edit;
465                         } else {
466                                 $ed->close_edit;
467                         }
468                         $pool->clear;
469                         exit 0;
470                 }
471                 my ($r_new, $cmt_new, $no);
472                 while (<$fh>) {
473                         print $_;
474                         chomp;
475                         if (/^r(\d+) = ($sha1)$/o) {
476                                 ($r_new, $cmt_new) = ($1, $2);
477                         } elsif ($_ eq 'No changes') {
478                                 $no = 1;
479                         }
480                 }
481                 close $fh or exit 1;
482                 if (! defined $r_new && ! defined $cmt_new) {
483                         unless ($no) {
484                                 die "Failed to parse revision information\n";
485                         }
486                 } else {
487                         ($r_last, $cmt_last) = ($r_new, $cmt_new);
488                 }
489         }
490         $ENV{LC_ALL} = 'C';
491         unlink $commit_msg;
494 sub dcommit {
495         my $head = shift || 'HEAD';
496         my $gs = "refs/remotes/$GIT_SVN";
497         my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
498         my $last_rev;
499         foreach my $d (reverse @refs) {
500                 if (!verify_ref("$d~1")) {
501                         die "Commit $d\n",
502                             "has no parent commit, and therefore ",
503                             "nothing to diff against.\n",
504                             "You should be working from a repository ",
505                             "originally created by git-svn\n";
506                 }
507                 unless (defined $last_rev) {
508                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
509                         unless (defined $last_rev) {
510                                 die "Unable to extract revision information ",
511                                     "from commit $d~1\n";
512                         }
513                 }
514                 if ($_dry_run) {
515                         print "diff-tree $d~1 $d\n";
516                 } else {
517                         if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
518                                 $last_rev = $r;
519                         } # else: no changes, same $last_rev
520                 }
521         }
522         return if $_dry_run;
523         fetch();
524         my @diff = command('diff-tree', 'HEAD', $gs, '--');
525         my @finish;
526         if (@diff) {
527                 @finish = qw/rebase/;
528                 push @finish, qw/--merge/ if $_merge;
529                 push @finish, "--strategy=$_strategy" if $_strategy;
530                 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
531         } else {
532                 print "No changes between current HEAD and $gs\n",
533                       "Resetting to the latest $gs\n";
534                 @finish = qw/reset --mixed/;
535         }
536         command_noisy(@finish, $gs);
539 sub show_ignore {
540         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
541         my $repo;
542         $SVN ||= Git::SVN::Ra->new($SVN_URL);
543         my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
544         libsvn_traverse_ignore(\*STDOUT, '', $r);
547 sub graft_branches {
548         my $gr_file = "$GIT_DIR/info/grafts";
549         my ($grafts, $comments) = read_grafts($gr_file);
550         my $gr_sha1;
552         if (%$grafts) {
553                 # temporarily disable our grafts file to make this idempotent
554                 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
555                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
556         }
558         my $l_map = read_url_paths();
559         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
560         unless ($_no_default_regex) {
561                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
562                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
563                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
564         }
565         foreach my $u (keys %$l_map) {
566                 if (@re) {
567                         foreach my $p (keys %{$l_map->{$u}}) {
568                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
569                         }
570                 }
571                 unless ($_no_graft_copy) {
572                         graft_file_copy_lib($grafts,$l_map,$u);
573                 }
574         }
575         graft_tree_joins($grafts);
577         write_grafts($grafts, $comments, $gr_file);
578         unlink "$gr_file~$gr_sha1" if $gr_sha1;
581 sub multi_init {
582         my $url = shift;
583         unless (defined $_trunk || defined $_branches || defined $_tags) {
584                 usage(1);
585         }
586         if (defined $_trunk) {
587                 my $trunk_url = complete_svn_url($url, $_trunk);
588                 my $ch_id;
589                 if ($GIT_SVN eq 'git-svn') {
590                         $ch_id = 1;
591                         $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
592                 }
593                 init_vars();
594                 unless (-d $GIT_SVN_DIR) {
595                         if ($ch_id) {
596                                 print "GIT_SVN_ID set to 'trunk' for ",
597                                       "$trunk_url ($_trunk)\n";
598                         }
599                         init($trunk_url);
600                         command_noisy('config', 'svn.trunk', $trunk_url);
601                 }
602         }
603         $_prefix = '' unless defined $_prefix;
604         complete_url_ls_init($url, $_branches, '--branches/-b', $_prefix);
605         complete_url_ls_init($url, $_tags, '--tags/-t', $_prefix . 'tags/');
608 sub multi_fetch {
609         # try to do trunk first, since branches/tags
610         # may be descended from it.
611         if (-e "$GIT_DIR/svn/trunk/info/url") {
612                 fetch_child_id('trunk', @_);
613         }
614         rec_fetch('', "$GIT_DIR/svn", @_);
617 sub show_log {
618         my (@args) = @_;
619         my ($r_min, $r_max);
620         my $r_last = -1; # prevent dupes
621         rload_authors() if $_authors;
622         if (defined $TZ) {
623                 $ENV{TZ} = $TZ;
624         } else {
625                 delete $ENV{TZ};
626         }
627         if (defined $_revision) {
628                 if ($_revision =~ /^(\d+):(\d+)$/) {
629                         ($r_min, $r_max) = ($1, $2);
630                 } elsif ($_revision =~ /^\d+$/) {
631                         $r_min = $r_max = $_revision;
632                 } else {
633                         print STDERR "-r$_revision is not supported, use ",
634                                 "standard \'git log\' arguments instead\n";
635                         exit 1;
636                 }
637         }
639         config_pager();
640         @args = (git_svn_log_cmd($r_min, $r_max), @args);
641         my $log = command_output_pipe(@args);
642         run_pager();
643         my (@k, $c, $d);
645         while (<$log>) {
646                 if (/^${_esc_color}commit ($sha1_short)/o) {
647                         my $cmt = $1;
648                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
649                                 $r_last = $c->{r};
650                                 process_commit($c, $r_min, $r_max, \@k) or
651                                                                 goto out;
652                         }
653                         $d = undef;
654                         $c = { c => $cmt };
655                 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
656                         get_author_info($c, $1, $2, $3);
657                 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
658                         # ignore
659                 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
660                         push @{$c->{raw}}, $_;
661                 } elsif (/^${_esc_color}[ACRMDT]\t/) {
662                         # we could add $SVN->{svn_path} here, but that requires
663                         # remote access at the moment (repo_path_split)...
664                         s#^(${_esc_color})([ACRMDT])\t#$1   $2 #;
665                         push @{$c->{changed}}, $_;
666                 } elsif (/^${_esc_color}diff /) {
667                         $d = 1;
668                         push @{$c->{diff}}, $_;
669                 } elsif ($d) {
670                         push @{$c->{diff}}, $_;
671                 } elsif (/^${_esc_color}    (git-svn-id:.+)$/) {
672                         ($c->{url}, $c->{r}, undef) = extract_metadata($1);
673                 } elsif (s/^${_esc_color}    //) {
674                         push @{$c->{l}}, $_;
675                 }
676         }
677         if ($c && defined $c->{r} && $c->{r} != $r_last) {
678                 $r_last = $c->{r};
679                 process_commit($c, $r_min, $r_max, \@k);
680         }
681         if (@k) {
682                 my $swap = $r_max;
683                 $r_max = $r_min;
684                 $r_min = $swap;
685                 process_commit($_, $r_min, $r_max) foreach reverse @k;
686         }
687 out:
688         close $log;
689         print '-' x72,"\n" unless $_incremental || $_oneline;
692 sub commit_diff_usage {
693         print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
694         exit 1
697 sub commit_diff {
698         my $ta = shift or commit_diff_usage();
699         my $tb = shift or commit_diff_usage();
700         if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
701                 print STDERR "Needed URL or usable git-svn id command-line\n";
702                 commit_diff_usage();
703         }
704         my $r = shift;
705         unless (defined $r) {
706                 if (defined $_revision) {
707                         $r = $_revision
708                 } else {
709                         die "-r|--revision is a required argument\n";
710                 }
711         }
712         if (defined $_message && defined $_file) {
713                 print STDERR "Both --message/-m and --file/-F specified ",
714                                 "for the commit message.\n",
715                                 "I have no idea what you mean\n";
716                 exit 1;
717         }
718         if (defined $_file) {
719                 $_message = file_to_s($_file);
720         } else {
721                 $_message ||= get_commit_message($tb,
722                                         "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
723         }
724         $SVN ||= Git::SVN::Ra->new($SVN_URL);
725         if ($r eq 'HEAD') {
726                 $r = $SVN->get_latest_revnum;
727         } elsif ($r !~ /^\d+$/) {
728                 die "revision argument: $r not understood by git-svn\n";
729         }
730         my $rev_committed;
731         my $pool = SVN::Pool->new;
732         my $ed = SVN::Git::Editor->new({        r => $r,
733                                                 ra => $SVN->dup,
734                                                 c => $tb,
735                                                 svn_path => $SVN->{svn_path}
736                                         },
737                                 $SVN->get_commit_editor($_message,
738                                         sub {
739                                                 $rev_committed = $_[0];
740                                                 print "Committed $_[0]\n";
741                                         },
742                                         $pool)
743                                 );
744         eval {
745                 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
746                 if (@$mods == 0) {
747                         print "No changes\n$ta == $tb\n";
748                         $ed->abort_edit;
749                 } else {
750                         $ed->close_edit;
751                 }
752         };
753         $pool->clear;
754         fatal "$@\n" if $@;
755         $_message = $_file = undef;
756         return $rev_committed;
759 ########################### utility functions #########################
761 sub cmt_showable {
762         my ($c) = @_;
763         return 1 if defined $c->{r};
764         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
765                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
766                 my @msg = command(qw/cat-file commit/, $c->{c});
767                 shift @msg while ($msg[0] ne "\n");
768                 shift @msg;
769                 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
771                 (undef, $c->{r}, undef) = extract_metadata(
772                                 (grep(/^git-svn-id: /, @msg))[-1]);
773         }
774         return defined $c->{r};
777 sub log_use_color {
778         return 1 if $_color;
779         my ($dc, $dcvar);
780         $dcvar = 'color.diff';
781         $dc = `git-config --get $dcvar`;
782         if ($dc eq '') {
783                 # nothing at all; fallback to "diff.color"
784                 $dcvar = 'diff.color';
785                 $dc = `git-config --get $dcvar`;
786         }
787         chomp($dc);
788         if ($dc eq 'auto') {
789                 my $pc;
790                 $pc = `git-config --get color.pager`;
791                 if ($pc eq '') {
792                         # does not have it -- fallback to pager.color
793                         $pc = `git-config --bool --get pager.color`;
794                 }
795                 else {
796                         $pc = `git-config --bool --get color.pager`;
797                         if ($?) {
798                                 $pc = 'false';
799                         }
800                 }
801                 chomp($pc);
802                 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
803                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
804                 }
805                 return 0;
806         }
807         return 0 if $dc eq 'never';
808         return 1 if $dc eq 'always';
809         chomp($dc = `git-config --bool --get $dcvar`);
810         return ($dc eq 'true');
813 sub git_svn_log_cmd {
814         my ($r_min, $r_max) = @_;
815         my @cmd = (qw/log --abbrev-commit --pretty=raw
816                         --default/, "refs/remotes/$GIT_SVN");
817         push @cmd, '-r' unless $_non_recursive;
818         push @cmd, qw/--raw --name-status/ if $_verbose;
819         push @cmd, '--color' if log_use_color();
820         return @cmd unless defined $r_max;
821         if ($r_max == $r_min) {
822                 push @cmd, '--max-count=1';
823                 if (my $c = revdb_get($REVDB, $r_max)) {
824                         push @cmd, $c;
825                 }
826         } else {
827                 my ($c_min, $c_max);
828                 $c_max = revdb_get($REVDB, $r_max);
829                 $c_min = revdb_get($REVDB, $r_min);
830                 if (defined $c_min && defined $c_max) {
831                         if ($r_max > $r_max) {
832                                 push @cmd, "$c_min..$c_max";
833                         } else {
834                                 push @cmd, "$c_max..$c_min";
835                         }
836                 } elsif ($r_max > $r_min) {
837                         push @cmd, $c_max;
838                 } else {
839                         push @cmd, $c_min;
840                 }
841         }
842         return @cmd;
845 sub fetch_child_id {
846         my $id = shift;
847         print "Fetching $id\n";
848         my $ref = "$GIT_DIR/refs/remotes/$id";
849         defined(my $pid = open my $fh, '-|') or croak $!;
850         if (!$pid) {
851                 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
852                 init_vars();
853                 fetch(@_);
854                 exit 0;
855         }
856         while (<$fh>) {
857                 print $_;
858                 check_repack() if (/^r\d+ = $sha1/o);
859         }
860         close $fh or croak $?;
863 sub rec_fetch {
864         my ($pfx, $p, @args) = @_;
865         my @dir;
866         foreach (sort <$p/*>) {
867                 if (-r "$_/info/url") {
868                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
869                         my $id = $pfx . basename $_;
870                         next if $id eq 'trunk';
871                         fetch_child_id($id, @args);
872                 } elsif (-d $_) {
873                         push @dir, $_;
874                 }
875         }
876         foreach (@dir) {
877                 my $x = $_;
878                 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
879                 rec_fetch($x, $_);
880         }
883 sub complete_svn_url {
884         my ($url, $path) = @_;
885         $path =~ s#/+$##;
886         $url =~ s#/+$## if $url;
887         if ($path !~ m#^[a-z\+]+://#) {
888                 $path = '/' . $path if ($path !~ m#^/#);
889                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
890                         fatal("E: '$path' is not a complete URL ",
891                               "and a separate URL is not specified\n");
892                 }
893                 $path = $url . $path;
894         }
895         return $path;
898 sub complete_url_ls_init {
899         my ($url, $path, $switch, $pfx) = @_;
900         unless ($path) {
901                 print STDERR "W: $switch not specified\n";
902                 return;
903         }
904         my $full_url = complete_svn_url($url, $path);
905         my @ls = libsvn_ls_fullurl($full_url);
906         defined(my $pid = fork) or croak $!;
907         if (!$pid) {
908                 foreach my $u (map { "$full_url/$_" } (grep m!/$!, @ls)) {
909                         $u =~ s#/+$##;
910                         if ($u !~ m!\Q$full_url\E/(.+)$!) {
911                                 print STDERR "W: Unrecognized URL: $u\n";
912                                 die "This should never happen\n";
913                         }
914                         # don't try to init already existing refs
915                         my $id = $pfx.$1;
916                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
917                         init_vars();
918                         unless (-d $GIT_SVN_DIR) {
919                                 print "init $u => $id\n";
920                                 init($u);
921                         }
922                 }
923                 exit 0;
924         }
925         waitpid $pid, 0;
926         croak $? if $?;
927         my ($n) = ($switch =~ /^--(\w+)/);
928         command_noisy('config', "svn.$n", $full_url);
931 sub common_prefix {
932         my $paths = shift;
933         my %common;
934         foreach (@$paths) {
935                 my @tmp = split m#/#, $_;
936                 my $p = '';
937                 while (my $x = shift @tmp) {
938                         $p .= "/$x";
939                         $common{$p} ||= 0;
940                         $common{$p}++;
941                 }
942         }
943         foreach (sort {length $b <=> length $a} keys %common) {
944                 if ($common{$_} == @$paths) {
945                         return $_;
946                 }
947         }
948         return '';
951 # grafts set here are 'stronger' in that they're based on actual tree
952 # matches, and won't be deleted from merge-base checking in write_grafts()
953 sub graft_tree_joins {
954         my $grafts = shift;
955         map_tree_joins() if (@_branch_from && !%tree_map);
956         return unless %tree_map;
958         git_svn_each(sub {
959                 my $i = shift;
960                 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
961                 my ($fh, $ctx) = command_output_pipe(@args);
962                 while (<$fh>) {
963                         next unless /^commit ($sha1)$/o;
964                         my $c = $1;
965                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
966                         next unless $tree_map{$t};
968                         my $l;
969                         do {
970                                 $l = readline $fh;
971                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
973                         my ($s, $tz) = ($1, $2);
974                         if ($tz =~ s/^\+//) {
975                                 $s += tz_to_s_offset($tz);
976                         } elsif ($tz =~ s/^\-//) {
977                                 $s -= tz_to_s_offset($tz);
978                         }
980                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
982                         foreach my $p (@{$tree_map{$t}}) {
983                                 next if $p eq $c;
984                                 my $mb = eval { command('merge-base', $c, $p) };
985                                 next unless ($@ || $?);
986                                 if (defined $r_a) {
987                                         # see if SVN says it's a relative
988                                         my ($url_b, $r_b, $uuid_b) =
989                                                         cmt_metadata($p);
990                                         next if (defined $url_b &&
991                                                         defined $url_a &&
992                                                         ($url_a eq $url_b) &&
993                                                         ($uuid_a eq $uuid_b));
994                                         if ($uuid_a eq $uuid_b) {
995                                                 if ($r_b < $r_a) {
996                                                         $grafts->{$c}->{$p} = 2;
997                                                         next;
998                                                 } elsif ($r_b > $r_a) {
999                                                         $grafts->{$p}->{$c} = 2;
1000                                                         next;
1001                                                 }
1002                                         }
1003                                 }
1004                                 my $ct = get_commit_time($p);
1005                                 if ($ct < $s) {
1006                                         $grafts->{$c}->{$p} = 2;
1007                                 } elsif ($ct > $s) {
1008                                         $grafts->{$p}->{$c} = 2;
1009                                 }
1010                                 # what should we do when $ct == $s ?
1011                         }
1012                 }
1013                 command_close_pipe($fh, $ctx);
1014         });
1017 sub graft_file_copy_lib {
1018         my ($grafts, $l_map, $u) = @_;
1019         my $tree_paths = $l_map->{$u};
1020         my $pfx = common_prefix([keys %$tree_paths]);
1021         my ($repo, $path) = repo_path_split($u.$pfx);
1022         $SVN = Git::SVN::Ra->new($repo);
1024         my ($base, $head) = libsvn_parse_revision();
1025         my $inc = 1000;
1026         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1027         my $eh = $SVN::Error::handler;
1028         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1029         while (1) {
1030                 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
1031                         sub {
1032                                 libsvn_graft_file_copies($grafts, $tree_paths,
1033                                                         $path, @_);
1034                         });
1035                 last if ($max >= $head);
1036                 $min = $max + 1;
1037                 $max += $inc;
1038                 $max = $head if ($max > $head);
1039         }
1040         $SVN::Error::handler = $eh;
1043 sub process_merge_msg_matches {
1044         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1045         my (@strong, @weak);
1046         foreach (@matches) {
1047                 # merging with ourselves is not interesting
1048                 next if $_ eq $p;
1049                 if ($l_map->{$u}->{$_}) {
1050                         push @strong, $_;
1051                 } else {
1052                         push @weak, $_;
1053                 }
1054         }
1055         foreach my $w (@weak) {
1056                 last if @strong;
1057                 # no exact match, use branch name as regexp.
1058                 my $re = qr/\Q$w\E/i;
1059                 foreach (keys %{$l_map->{$u}}) {
1060                         if (/$re/) {
1061                                 push @strong, $l_map->{$u}->{$_};
1062                                 last;
1063                         }
1064                 }
1065                 last if @strong;
1066                 $w = basename($w);
1067                 $re = qr/\Q$w\E/i;
1068                 foreach (keys %{$l_map->{$u}}) {
1069                         if (/$re/) {
1070                                 push @strong, $l_map->{$u}->{$_};
1071                                 last;
1072                         }
1073                 }
1074         }
1075         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1076                                         \s(?:[a-f\d\-]+)$/xsm);
1077         unless (defined $rev) {
1078                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1079                                         \@(?:[a-f\d\-]+)/xsm);
1080                 return unless defined $rev;
1081         }
1082         foreach my $m (@strong) {
1083                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1084                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1085         }
1088 sub graft_merge_msg {
1089         my ($grafts, $l_map, $u, $p, @re) = @_;
1091         my $x = $l_map->{$u}->{$p};
1092         my $rl = rev_list_raw("refs/remotes/$x");
1093         while (my $c = next_rev_list_entry($rl)) {
1094                 foreach my $re (@re) {
1095                         my (@br) = ($c->{m} =~ /$re/g);
1096                         next unless @br;
1097                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1098                 }
1099         }
1102 sub verify_ref {
1103         my ($ref) = @_;
1104         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1105                                { STDERR => 0 }); };
1108 sub repo_path_split {
1109         my $full_url = shift;
1110         $full_url =~ s#/+$##;
1112         foreach (@repo_path_split_cache) {
1113                 if ($full_url =~ s#$_##) {
1114                         my $u = $1;
1115                         $full_url =~ s#^/+##;
1116                         return ($u, $full_url);
1117                 }
1118         }
1119         my $tmp = Git::SVN::Ra->new($full_url);
1120         return ($tmp->{repos_root}, $tmp->{svn_path});
1123 sub setup_git_svn {
1124         defined $SVN_URL or croak "SVN repository location required\n";
1125         unless (-d $GIT_DIR) {
1126                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1127         }
1128         mkpath([$GIT_SVN_DIR]);
1129         mkpath(["$GIT_SVN_DIR/info"]);
1130         open my $fh, '>>',$REVDB or croak $!;
1131         close $fh;
1132         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1136 sub get_tree_from_treeish {
1137         my ($treeish) = @_;
1138         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1139         my $type = command_oneline(qw/cat-file -t/, $treeish);
1140         my $expected;
1141         while ($type eq 'tag') {
1142                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1143         }
1144         if ($type eq 'commit') {
1145                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1146                                                     $treeish))[0];
1147                 ($expected) = ($expected =~ /^tree ($sha1)$/);
1148                 die "Unable to get tree from $treeish\n" unless $expected;
1149         } elsif ($type eq 'tree') {
1150                 $expected = $treeish;
1151         } else {
1152                 die "$treeish is a $type, expected tree, tag or commit\n";
1153         }
1154         return $expected;
1157 sub get_diff {
1158         my ($from, $treeish) = @_;
1159         print "diff-tree $from $treeish\n";
1160         my @diff_tree = qw(diff-tree -z -r);
1161         if ($_cp_similarity) {
1162                 push @diff_tree, "-C$_cp_similarity";
1163         } else {
1164                 push @diff_tree, '-C';
1165         }
1166         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1167         push @diff_tree, "-l$_l" if defined $_l;
1168         push @diff_tree, $from, $treeish;
1169         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1170         local $/ = "\0";
1171         my $state = 'meta';
1172         my @mods;
1173         while (<$diff_fh>) {
1174                 chomp $_; # this gets rid of the trailing "\0"
1175                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1176                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1177                         push @mods, {   mode_a => $1, mode_b => $2,
1178                                         sha1_b => $3, chg => $4 };
1179                         if ($4 =~ /^(?:C|R)$/) {
1180                                 $state = 'file_a';
1181                         } else {
1182                                 $state = 'file_b';
1183                         }
1184                 } elsif ($state eq 'file_a') {
1185                         my $x = $mods[$#mods] or croak "Empty array\n";
1186                         if ($x->{chg} !~ /^(?:C|R)$/) {
1187                                 croak "Error parsing $_, $x->{chg}\n";
1188                         }
1189                         $x->{file_a} = $_;
1190                         $state = 'file_b';
1191                 } elsif ($state eq 'file_b') {
1192                         my $x = $mods[$#mods] or croak "Empty array\n";
1193                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1194                                 croak "Error parsing $_, $x->{chg}\n";
1195                         }
1196                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1197                                 croak "Error parsing $_, $x->{chg}\n";
1198                         }
1199                         $x->{file_b} = $_;
1200                         $state = 'meta';
1201                 } else {
1202                         croak "Error parsing $_\n";
1203                 }
1204         }
1205         command_close_pipe($diff_fh, $ctx);
1206         return \@mods;
1209 sub libsvn_checkout_tree {
1210         my ($from, $treeish, $ed) = @_;
1211         my $mods = get_diff($from, $treeish);
1212         return $mods unless (scalar @$mods);
1213         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1214         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1215                 my $f = $m->{chg};
1216                 if (defined $o{$f}) {
1217                         $ed->$f($m, $_q);
1218                 } else {
1219                         croak "Invalid change type: $f\n";
1220                 }
1221         }
1222         $ed->rmdirs($_q) if $_rmdir;
1223         return $mods;
1226 sub get_commit_message {
1227         my ($commit, $commit_msg) = (@_);
1228         my %log_msg = ( msg => '' );
1229         open my $msg, '>', $commit_msg or croak $!;
1231         my $type = command_oneline(qw/cat-file -t/, $commit);
1232         if ($type eq 'commit' || $type eq 'tag') {
1233                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1234                                                          $type, $commit);
1235                 my $in_msg = 0;
1236                 while (<$msg_fh>) {
1237                         if (!$in_msg) {
1238                                 $in_msg = 1 if (/^\s*$/);
1239                         } elsif (/^git-svn-id: /) {
1240                                 # skip this, we regenerate the correct one
1241                                 # on re-fetch anyways
1242                         } else {
1243                                 print $msg $_ or croak $!;
1244                         }
1245                 }
1246                 command_close_pipe($msg_fh, $ctx);
1247         }
1248         close $msg or croak $!;
1250         if ($_edit || ($type eq 'tree')) {
1251                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1252                 system($editor, $commit_msg);
1253         }
1255         # file_to_s removes all trailing newlines, so just use chomp() here:
1256         open $msg, '<', $commit_msg or croak $!;
1257         { local $/; chomp($log_msg{msg} = <$msg>); }
1258         close $msg or croak $!;
1260         return \%log_msg;
1263 sub set_svn_commit_env {
1264         if (defined $LC_ALL) {
1265                 $ENV{LC_ALL} = $LC_ALL;
1266         } else {
1267                 delete $ENV{LC_ALL};
1268         }
1271 sub rev_list_raw {
1272         my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1273         return { fh => $fh, ctx => $c, t => { } };
1276 sub next_rev_list_entry {
1277         my $rl = shift;
1278         my $fh = $rl->{fh};
1279         my $x = $rl->{t};
1280         while (<$fh>) {
1281                 if (/^commit ($sha1)$/o) {
1282                         if ($x->{c}) {
1283                                 $rl->{t} = { c => $1 };
1284                                 return $x;
1285                         } else {
1286                                 $x->{c} = $1;
1287                         }
1288                 } elsif (/^parent ($sha1)$/o) {
1289                         $x->{p}->{$1} = 1;
1290                 } elsif (s/^    //) {
1291                         $x->{m} ||= '';
1292                         $x->{m} .= $_;
1293                 }
1294         }
1295         command_close_pipe($fh, $rl->{ctx});
1296         return ($x != $rl->{t}) ? $x : undef;
1299 sub s_to_file {
1300         my ($str, $file, $mode) = @_;
1301         open my $fd,'>',$file or croak $!;
1302         print $fd $str,"\n" or croak $!;
1303         close $fd or croak $!;
1304         chmod ($mode &~ umask, $file) if (defined $mode);
1307 sub file_to_s {
1308         my $file = shift;
1309         open my $fd,'<',$file or croak "$!: file: $file\n";
1310         local $/;
1311         my $ret = <$fd>;
1312         close $fd or croak $!;
1313         $ret =~ s/\s*$//s;
1314         return $ret;
1317 sub assert_revision_unknown {
1318         my $r = shift;
1319         if (my $c = revdb_get($REVDB, $r)) {
1320                 croak "$r = $c already exists! Why are we refetching it?";
1321         }
1324 sub git_commit {
1325         my ($log_msg, @parents) = @_;
1326         assert_revision_unknown($log_msg->{revision});
1327         map_tree_joins() if (@_branch_from && !%tree_map);
1329         my (@tmp_parents, @exec_parents, %seen_parent);
1330         if (my $lparents = $log_msg->{parents}) {
1331                 @tmp_parents = @$lparents
1332         }
1333         # commit parents can be conditionally bound to a particular
1334         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1335         foreach my $p (@parents) {
1336                 next unless defined $p;
1337                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1338                         if ($1 == $log_msg->{revision}) {
1339                                 push @tmp_parents, $2;
1340                         }
1341                 } else {
1342                         push @tmp_parents, $p if $p =~ /$sha1_short/o;
1343                 }
1344         }
1345         my $tree = $log_msg->{tree};
1346         if (!defined $tree) {
1347                 my $index = set_index($GIT_SVN_INDEX);
1348                 $tree = command_oneline('write-tree');
1349                 croak $? if $?;
1350                 restore_index($index);
1351         }
1352         # just in case we clobber the existing ref, we still want that ref
1353         # as our parent:
1354         if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1355                 chomp $cur;
1356                 push @tmp_parents, $cur;
1357         }
1359         if (exists $tree_map{$tree}) {
1360                 foreach my $p (@{$tree_map{$tree}}) {
1361                         my $skip;
1362                         foreach (@tmp_parents) {
1363                                 # see if a common parent is found
1364                                 my $mb = eval { command('merge-base', $_, $p) };
1365                                 next if ($@ || $?);
1366                                 $skip = 1;
1367                                 last;
1368                         }
1369                         next if $skip;
1370                         my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1371                         next if (($SVN->uuid eq $uuid_p) &&
1372                                                 ($log_msg->{revision} > $r_p));
1373                         next if (defined $url_p && defined $SVN_URL &&
1374                                                 ($SVN->uuid eq $uuid_p) &&
1375                                                 ($url_p eq $SVN_URL));
1376                         push @tmp_parents, $p;
1377                 }
1378         }
1379         foreach (@tmp_parents) {
1380                 next if $seen_parent{$_};
1381                 $seen_parent{$_} = 1;
1382                 push @exec_parents, $_;
1383                 # MAXPARENT is defined to 16 in commit-tree.c:
1384                 last if @exec_parents > 16;
1385         }
1387         set_commit_env($log_msg);
1388         my @exec = ('git-commit-tree', $tree);
1389         push @exec, '-p', $_  foreach @exec_parents;
1390         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1391                                                                 or croak $!;
1392         print $msg_fh $log_msg->{msg} or croak $!;
1393         unless ($_no_metadata) {
1394                 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1395                                         $SVN->uuid,"\n" or croak $!;
1396         }
1397         $msg_fh->flush == 0 or croak $!;
1398         close $msg_fh or croak $!;
1399         chomp(my $commit = do { local $/; <$out_fh> });
1400         close $out_fh or croak $!;
1401         waitpid $pid, 0;
1402         croak $? if $?;
1403         if ($commit !~ /^$sha1$/o) {
1404                 die "Failed to commit, invalid sha1: $commit\n";
1405         }
1406         command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1407         revdb_set($REVDB, $log_msg->{revision}, $commit);
1409         # this output is read via pipe, do not change:
1410         print "r$log_msg->{revision} = $commit\n";
1411         return $commit;
1414 sub check_repack {
1415         if ($_repack && (--$_repack_nr == 0)) {
1416                 $_repack_nr = $_repack;
1417                 # repack doesn't use any arguments with spaces in them, does it?
1418                 command_noisy('repack', split(/\s+/, $_repack_flags));
1419         }
1422 sub set_commit_env {
1423         my ($log_msg) = @_;
1424         my $author = $log_msg->{author};
1425         if (!defined $author || length $author == 0) {
1426                 $author = '(no author)';
1427         }
1428         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1429                                 : ($author,$author . '@' . $SVN->uuid);
1430         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1431         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1432         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1435 sub check_upgrade_needed {
1436         if (!-r $REVDB) {
1437                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1438                 open my $fh, '>>',$REVDB or croak $!;
1439                 close $fh;
1440         }
1441         return unless eval {
1442                 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1443                         {STDERR => 0});
1444         };
1445         my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1446         if ($@ || !$head) {
1447                 print STDERR "Please run: $0 rebuild --upgrade\n";
1448                 exit 1;
1449         }
1452 # fills %tree_map with a reverse mapping of trees to commits.  Useful
1453 # for finding parents to commit on.
1454 sub map_tree_joins {
1455         my %seen;
1456         foreach my $br (@_branch_from) {
1457                 my $pipe = command_output_pipe(qw/rev-list
1458                                             --topo-order --pretty=raw/, $br);
1459                 while (<$pipe>) {
1460                         if (/^commit ($sha1)$/o) {
1461                                 my $commit = $1;
1463                                 # if we've seen a commit,
1464                                 # we've seen its parents
1465                                 last if $seen{$commit};
1466                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1467                                 unless (defined $tree) {
1468                                         die "Failed to parse commit $commit\n";
1469                                 }
1470                                 push @{$tree_map{$tree}}, $commit;
1471                                 $seen{$commit} = 1;
1472                         }
1473                 }
1474                 close $pipe;
1475         }
1478 sub load_all_refs {
1479         if (@_branch_from) {
1480                 print STDERR '--branch|-b parameters are ignored when ',
1481                         "--branch-all-refs|-B is passed\n";
1482         }
1484         # don't worry about rev-list on non-commit objects/tags,
1485         # it shouldn't blow up if a ref is a blob or tree...
1486         @_branch_from = command(qw/rev-parse --symbolic --all/);
1489 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1490 sub load_authors {
1491         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1492         while (<$authors>) {
1493                 chomp;
1494                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1495                 my ($user, $name, $email) = ($1, $2, $3);
1496                 $users{$user} = [$name, $email];
1497         }
1498         close $authors or croak $!;
1501 sub rload_authors {
1502         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1503         while (<$authors>) {
1504                 chomp;
1505                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1506                 my ($user, $name, $email) = ($1, $2, $3);
1507                 $rusers{"$name <$email>"} = $user;
1508         }
1509         close $authors or croak $!;
1512 sub git_svn_each {
1513         my $sub = shift;
1514         foreach (command(qw/rev-parse --symbolic --all/)) {
1515                 next unless s#^refs/remotes/##;
1516                 chomp $_;
1517                 next unless -f "$GIT_DIR/svn/$_/info/url";
1518                 &$sub($_);
1519         }
1522 sub migrate_revdb {
1523         git_svn_each(sub {
1524                 my $id = shift;
1525                 defined(my $pid = fork) or croak $!;
1526                 if (!$pid) {
1527                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1528                         init_vars();
1529                         exit 0 if -r $REVDB;
1530                         print "Upgrading svn => git mapping...\n";
1531                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1532                         open my $fh, '>>',$REVDB or croak $!;
1533                         close $fh;
1534                         rebuild();
1535                         print "Done upgrading. You may now delete the ",
1536                                 "deprecated $GIT_SVN_DIR/revs directory\n";
1537                         exit 0;
1538                 }
1539                 waitpid $pid, 0;
1540                 croak $? if $?;
1541         });
1544 sub migration_check {
1545         migrate_revdb() unless (-e $REVDB);
1546         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1547         print "Upgrading repository...\n";
1548         unless (-d "$GIT_DIR/svn") {
1549                 mkdir "$GIT_DIR/svn" or croak $!;
1550         }
1551         print "Data from a previous version of git-svn exists, but\n\t",
1552                                 "$GIT_SVN_DIR\n\t(required for this version ",
1553                                 "($VERSION) of git-svn) does not.\n";
1555         foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1556                 next unless $x =~ s#^refs/remotes/##;
1557                 chomp $x;
1558                 next unless -f "$GIT_DIR/$x/info/url";
1559                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1560                 next unless $u;
1561                 my $dn = dirname("$GIT_DIR/svn/$x");
1562                 mkpath([$dn]) unless -d $dn;
1563                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1564         }
1565         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1566         print "Done upgrading.\n";
1569 sub find_rev_before {
1570         my ($r, $id, $eq_ok) = @_;
1571         my $f = "$GIT_DIR/svn/$id/.rev_db";
1572         return (undef,undef) unless -r $f;
1573         --$r unless $eq_ok;
1574         while ($r > 0) {
1575                 if (my $c = revdb_get($f, $r)) {
1576                         return ($r, $c);
1577                 }
1578                 --$r;
1579         }
1580         return (undef, undef);
1583 sub init_vars {
1584         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1585         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1586         $REVDB = "$GIT_SVN_DIR/.rev_db";
1587         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1588         $SVN_URL = undef;
1589         %tree_map = ();
1592 # convert GetOpt::Long specs for use by git-config
1593 sub read_repo_config {
1594         return unless -d $GIT_DIR;
1595         my $opts = shift;
1596         foreach my $o (keys %$opts) {
1597                 my $v = $opts->{$o};
1598                 my ($key) = ($o =~ /^([a-z\-]+)/);
1599                 $key =~ s/-//g;
1600                 my $arg = 'git-config';
1601                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1602                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1603                 if (ref $v eq 'ARRAY') {
1604                         chomp(my @tmp = `$arg --get-all svn.$key`);
1605                         @$v = @tmp if @tmp;
1606                 } else {
1607                         chomp(my $tmp = `$arg --get svn.$key`);
1608                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1609                                 $$v = $tmp;
1610                         }
1611                 }
1612         }
1615 sub set_default_vals {
1616         if (defined $_repack) {
1617                 $_repack = 1000 if ($_repack <= 0);
1618                 $_repack_nr = $_repack;
1619                 $_repack_flags ||= '-d';
1620         }
1623 sub read_grafts {
1624         my $gr_file = shift;
1625         my ($grafts, $comments) = ({}, {});
1626         if (open my $fh, '<', $gr_file) {
1627                 my @tmp;
1628                 while (<$fh>) {
1629                         if (/^($sha1)\s+/) {
1630                                 my $c = $1;
1631                                 if (@tmp) {
1632                                         @{$comments->{$c}} = @tmp;
1633                                         @tmp = ();
1634                                 }
1635                                 foreach my $p (split /\s+/, $_) {
1636                                         $grafts->{$c}->{$p} = 1;
1637                                 }
1638                         } else {
1639                                 push @tmp, $_;
1640                         }
1641                 }
1642                 close $fh or croak $!;
1643                 @{$comments->{'END'}} = @tmp if @tmp;
1644         }
1645         return ($grafts, $comments);
1648 sub write_grafts {
1649         my ($grafts, $comments, $gr_file) = @_;
1651         open my $fh, '>', $gr_file or croak $!;
1652         foreach my $c (sort keys %$grafts) {
1653                 if ($comments->{$c}) {
1654                         print $fh $_ foreach @{$comments->{$c}};
1655                 }
1656                 my $p = $grafts->{$c};
1657                 my %x; # real parents
1658                 delete $p->{$c}; # commits are not self-reproducing...
1659                 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1660                 while (<$ch>) {
1661                         if (/^parent ($sha1)/) {
1662                                 $x{$1} = $p->{$1} = 1;
1663                         } else {
1664                                 last unless /^\S/;
1665                         }
1666                 }
1667                 close $ch; # breaking the pipe
1669                 # if real parents are the only ones in the grafts, drop it
1670                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1672                 my (@ip, @jp, $mb);
1673                 my %del = %x;
1674                 @ip = @jp = keys %$p;
1675                 foreach my $i (@ip) {
1676                         next if $del{$i} || $p->{$i} == 2;
1677                         foreach my $j (@jp) {
1678                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1679                                 $mb = eval { command('merge-base', $i, $j) };
1680                                 next unless $mb;
1681                                 chomp $mb;
1682                                 next if $x{$mb};
1683                                 if ($mb eq $j) {
1684                                         delete $p->{$i};
1685                                         $del{$i} = 1;
1686                                 } elsif ($mb eq $i) {
1687                                         delete $p->{$j};
1688                                         $del{$j} = 1;
1689                                 }
1690                         }
1691                 }
1693                 # if real parents are the only ones in the grafts, drop it
1694                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1696                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1697         }
1698         if ($comments->{'END'}) {
1699                 print $fh $_ foreach @{$comments->{'END'}};
1700         }
1701         close $fh or croak $!;
1704 sub read_url_paths_all {
1705         my ($l_map, $pfx, $p) = @_;
1706         my @dir;
1707         foreach (<$p/*>) {
1708                 if (-r "$_/info/url") {
1709                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1710                         my $id = $pfx . basename $_;
1711                         my $url = file_to_s("$_/info/url");
1712                         my ($u, $p) = repo_path_split($url);
1713                         $l_map->{$u}->{$p} = $id;
1714                 } elsif (-d $_) {
1715                         push @dir, $_;
1716                 }
1717         }
1718         foreach (@dir) {
1719                 my $x = $_;
1720                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1721                 read_url_paths_all($l_map, $x, $_);
1722         }
1725 # this one only gets ids that have been imported, not new ones
1726 sub read_url_paths {
1727         my $l_map = {};
1728         git_svn_each(sub { my $x = shift;
1729                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1730                         my ($u, $p) = repo_path_split($url);
1731                         $l_map->{$u}->{$p} = $x;
1732                         });
1733         return $l_map;
1736 sub extract_metadata {
1737         my $id = shift or return (undef, undef, undef);
1738         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1739                                                         \s([a-f\d\-]+)$/x);
1740         if (!defined $rev || !$uuid || !$url) {
1741                 # some of the original repositories I made had
1742                 # identifiers like this:
1743                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1744         }
1745         return ($url, $rev, $uuid);
1748 sub cmt_metadata {
1749         return extract_metadata((grep(/^git-svn-id: /,
1750                 command(qw/cat-file commit/, shift)))[-1]);
1753 sub get_commit_time {
1754         my $cmt = shift;
1755         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1756         while (<$fh>) {
1757                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1758                 my ($s, $tz) = ($1, $2);
1759                 if ($tz =~ s/^\+//) {
1760                         $s += tz_to_s_offset($tz);
1761                 } elsif ($tz =~ s/^\-//) {
1762                         $s -= tz_to_s_offset($tz);
1763                 }
1764                 close $fh;
1765                 return $s;
1766         }
1767         die "Can't get commit time for commit: $cmt\n";
1770 sub tz_to_s_offset {
1771         my ($tz) = @_;
1772         $tz =~ s/(\d\d)$//;
1773         return ($1 * 60) + ($tz * 3600);
1776 # adapted from pager.c
1777 sub config_pager {
1778         $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
1779         if (!defined $_pager) {
1780                 $_pager = 'less';
1781         } elsif (length $_pager == 0 || $_pager eq 'cat') {
1782                 $_pager = undef;
1783         }
1786 sub run_pager {
1787         return unless -t *STDOUT;
1788         pipe my $rfd, my $wfd or return;
1789         defined(my $pid = fork) or croak $!;
1790         if (!$pid) {
1791                 open STDOUT, '>&', $wfd or croak $!;
1792                 return;
1793         }
1794         open STDIN, '<&', $rfd or croak $!;
1795         $ENV{LESS} ||= 'FRSX';
1796         exec $_pager or croak "Can't run pager: $! ($_pager)\n";
1799 sub get_author_info {
1800         my ($dest, $author, $t, $tz) = @_;
1801         $author =~ s/(?:^\s*|\s*$)//g;
1802         $dest->{a_raw} = $author;
1803         my $_a;
1804         if ($_authors) {
1805                 $_a = $rusers{$author} || undef;
1806         }
1807         if (!$_a) {
1808                 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
1809         }
1810         $dest->{t} = $t;
1811         $dest->{tz} = $tz;
1812         $dest->{a} = $_a;
1813         # Date::Parse isn't in the standard Perl distro :(
1814         if ($tz =~ s/^\+//) {
1815                 $t += tz_to_s_offset($tz);
1816         } elsif ($tz =~ s/^\-//) {
1817                 $t -= tz_to_s_offset($tz);
1818         }
1819         $dest->{t_utc} = $t;
1822 sub process_commit {
1823         my ($c, $r_min, $r_max, $defer) = @_;
1824         if (defined $r_min && defined $r_max) {
1825                 if ($r_min == $c->{r} && $r_min == $r_max) {
1826                         show_commit($c);
1827                         return 0;
1828                 }
1829                 return 1 if $r_min == $r_max;
1830                 if ($r_min < $r_max) {
1831                         # we need to reverse the print order
1832                         return 0 if (defined $_limit && --$_limit < 0);
1833                         push @$defer, $c;
1834                         return 1;
1835                 }
1836                 if ($r_min != $r_max) {
1837                         return 1 if ($r_min < $c->{r});
1838                         return 1 if ($r_max > $c->{r});
1839                 }
1840         }
1841         return 0 if (defined $_limit && --$_limit < 0);
1842         show_commit($c);
1843         return 1;
1846 sub show_commit {
1847         my $c = shift;
1848         if ($_oneline) {
1849                 my $x = "\n";
1850                 if (my $l = $c->{l}) {
1851                         while ($l->[0] =~ /^\s*$/) { shift @$l }
1852                         $x = $l->[0];
1853                 }
1854                 $_l_fmt ||= 'A' . length($c->{r});
1855                 print 'r',pack($_l_fmt, $c->{r}),' | ';
1856                 print "$c->{c} | " if $_show_commit;
1857                 print $x;
1858         } else {
1859                 show_commit_normal($c);
1860         }
1863 sub show_commit_changed_paths {
1864         my ($c) = @_;
1865         return unless $c->{changed};
1866         print "Changed paths:\n", @{$c->{changed}};
1869 sub show_commit_normal {
1870         my ($c) = @_;
1871         print '-' x72, "\nr$c->{r} | ";
1872         print "$c->{c} | " if $_show_commit;
1873         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
1874                                  localtime($c->{t_utc})), ' | ';
1875         my $nr_line = 0;
1877         if (my $l = $c->{l}) {
1878                 while ($l->[$#$l] eq "\n" && $#$l > 0
1879                                           && $l->[($#$l - 1)] eq "\n") {
1880                         pop @$l;
1881                 }
1882                 $nr_line = scalar @$l;
1883                 if (!$nr_line) {
1884                         print "1 line\n\n\n";
1885                 } else {
1886                         if ($nr_line == 1) {
1887                                 $nr_line = '1 line';
1888                         } else {
1889                                 $nr_line .= ' lines';
1890                         }
1891                         print $nr_line, "\n";
1892                         show_commit_changed_paths($c);
1893                         print "\n";
1894                         print $_ foreach @$l;
1895                 }
1896         } else {
1897                 print "1 line\n";
1898                 show_commit_changed_paths($c);
1899                 print "\n";
1901         }
1902         foreach my $x (qw/raw diff/) {
1903                 if ($c->{$x}) {
1904                         print "\n";
1905                         print $_ foreach @{$c->{$x}}
1906                 }
1907         }
1910 package Git::SVN::Prompt;
1911 use strict;
1912 use warnings;
1913 require SVN::Core;
1914 use vars qw/$_no_auth_cache $_username/;
1916 sub simple {
1917         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1918         $may_save = undef if $_no_auth_cache;
1919         $default_username = $_username if defined $_username;
1920         if (defined $default_username && length $default_username) {
1921                 if (defined $realm && length $realm) {
1922                         print STDERR "Authentication realm: $realm\n";
1923                         STDERR->flush;
1924                 }
1925                 $cred->username($default_username);
1926         } else {
1927                 username($cred, $realm, $may_save, $pool);
1928         }
1929         $cred->password(_read_password("Password for '" .
1930                                        $cred->username . "': ", $realm));
1931         $cred->may_save($may_save);
1932         $SVN::_Core::SVN_NO_ERROR;
1935 sub ssl_server_trust {
1936         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1937         $may_save = undef if $_no_auth_cache;
1938         print STDERR "Error validating server certificate for '$realm':\n";
1939         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1940                 print STDERR " - The certificate is not issued by a trusted ",
1941                       "authority. Use the\n",
1942                       "   fingerprint to validate the certificate manually!\n";
1943         }
1944         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1945                 print STDERR " - The certificate hostname does not match.\n";
1946         }
1947         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1948                 print STDERR " - The certificate is not yet valid.\n";
1949         }
1950         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1951                 print STDERR " - The certificate has expired.\n";
1952         }
1953         if ($failures & $SVN::Auth::SSL::OTHER) {
1954                 print STDERR " - The certificate has an unknown error.\n";
1955         }
1956         printf STDERR
1957                 "Certificate information:\n".
1958                 " - Hostname: %s\n".
1959                 " - Valid: from %s until %s\n".
1960                 " - Issuer: %s\n".
1961                 " - Fingerprint: %s\n",
1962                 map $cert_info->$_, qw(hostname valid_from valid_until
1963                                        issuer_dname fingerprint);
1964         my $choice;
1965 prompt:
1966         print STDERR $may_save ?
1967               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1968               "(R)eject or accept (t)emporarily? ";
1969         STDERR->flush;
1970         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1971         if ($choice =~ /^t$/i) {
1972                 $cred->may_save(undef);
1973         } elsif ($choice =~ /^r$/i) {
1974                 return -1;
1975         } elsif ($may_save && $choice =~ /^p$/i) {
1976                 $cred->may_save($may_save);
1977         } else {
1978                 goto prompt;
1979         }
1980         $cred->accepted_failures($failures);
1981         $SVN::_Core::SVN_NO_ERROR;
1984 sub ssl_client_cert {
1985         my ($cred, $realm, $may_save, $pool) = @_;
1986         $may_save = undef if $_no_auth_cache;
1987         print STDERR "Client certificate filename: ";
1988         STDERR->flush;
1989         chomp(my $filename = <STDIN>);
1990         $cred->cert_file($filename);
1991         $cred->may_save($may_save);
1992         $SVN::_Core::SVN_NO_ERROR;
1995 sub ssl_client_cert_pw {
1996         my ($cred, $realm, $may_save, $pool) = @_;
1997         $may_save = undef if $_no_auth_cache;
1998         $cred->password(_read_password("Password: ", $realm));
1999         $cred->may_save($may_save);
2000         $SVN::_Core::SVN_NO_ERROR;
2003 sub username {
2004         my ($cred, $realm, $may_save, $pool) = @_;
2005         $may_save = undef if $_no_auth_cache;
2006         if (defined $realm && length $realm) {
2007                 print STDERR "Authentication realm: $realm\n";
2008         }
2009         my $username;
2010         if (defined $_username) {
2011                 $username = $_username;
2012         } else {
2013                 print STDERR "Username: ";
2014                 STDERR->flush;
2015                 chomp($username = <STDIN>);
2016         }
2017         $cred->username($username);
2018         $cred->may_save($may_save);
2019         $SVN::_Core::SVN_NO_ERROR;
2022 sub _read_password {
2023         my ($prompt, $realm) = @_;
2024         print STDERR $prompt;
2025         STDERR->flush;
2026         require Term::ReadKey;
2027         Term::ReadKey::ReadMode('noecho');
2028         my $password = '';
2029         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2030                 last if $key =~ /[\012\015]/; # \n\r
2031                 $password .= $key;
2032         }
2033         Term::ReadKey::ReadMode('restore');
2034         print STDERR "\n";
2035         STDERR->flush;
2036         $password;
2039 package main;
2041 sub uri_encode {
2042         my ($f) = @_;
2043         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2044         $f
2047 sub uri_decode {
2048         my ($f) = @_;
2049         $f =~ tr/+/ /;
2050         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2051         $f
2054 sub libsvn_log_entry {
2055         my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2056         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2057                                          (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2058                                 or die "Unable to parse date: $date\n";
2059         if (defined $author && length $author > 0 &&
2060             defined $_authors && ! defined $users{$author}) {
2061                 die "Author: $author not defined in $_authors file\n";
2062         }
2063         $msg = '' if ($rev == 0 && !defined $msg);
2065         open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2066         my $h;
2067         print $un "r$rev\n" or croak $!;
2068         $h = $untracked->{empty};
2069         foreach (sort keys %$h) {
2070                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2071                 print $un "  $act: ", uri_encode($_), "\n" or croak $!;
2072                 warn "W: $act: $_\n";
2073         }
2074         foreach my $t (qw/dir_prop file_prop/) {
2075                 $h = $untracked->{$t} or next;
2076                 foreach my $path (sort keys %$h) {
2077                         my $ppath = $path eq '' ? '.' : $path;
2078                         foreach my $prop (sort keys %{$h->{$path}}) {
2079                                 next if $SKIP{$prop};
2080                                 my $v = $h->{$path}->{$prop};
2081                                 if (defined $v) {
2082                                         print $un "  +$t: ",
2083                                                   uri_encode($ppath), ' ',
2084                                                   uri_encode($prop), ' ',
2085                                                   uri_encode($v), "\n"
2086                                                   or croak $!;
2087                                 } else {
2088                                         print $un "  -$t: ",
2089                                                   uri_encode($ppath), ' ',
2090                                                   uri_encode($prop), "\n"
2091                                                   or croak $!;
2092                                 }
2093                         }
2094                 }
2095         }
2096         foreach my $t (qw/absent_file absent_directory/) {
2097                 $h = $untracked->{$t} or next;
2098                 foreach my $parent (sort keys %$h) {
2099                         foreach my $path (sort @{$h->{$parent}}) {
2100                                 print $un "  $t: ",
2101                                       uri_encode("$parent/$path"), "\n"
2102                                       or croak $!;
2103                                 warn "W: $t: $parent/$path ",
2104                                      "Insufficient permissions?\n";
2105                         }
2106                 }
2107         }
2109         # revprops (make this optional? it's an extra network trip...)
2110         my $rp = $SVN->rev_proplist($rev);
2111         foreach (sort keys %$rp) {
2112                 next if /^svn:(?:author|date|log)$/;
2113                 print $un "  rev_prop: ", uri_encode($_), ' ',
2114                           uri_encode($rp->{$_}), "\n";
2115         }
2116         close $un or croak $!;
2118         { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2119           author => $author, msg => $msg."\n", parents => $parents || [],
2120           revprops => $rp }
2123 sub libsvn_fetch {
2124         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2125         my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2126         my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2127         unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2128                 die "SVN connection failed somewhere...\n";
2129         }
2130         libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2133 sub svn_grab_base_rev {
2134         my $c = eval { command_oneline([qw/rev-parse --verify/,
2135                                         "refs/remotes/$GIT_SVN^0"],
2136                                         { STDERR => 0 }) };
2137         if (defined $c && length $c) {
2138                 my ($url, $rev, $uuid) = cmt_metadata($c);
2139                 return ($rev, $c) if defined $rev;
2140         }
2141         if ($_no_metadata) {
2142                 my $offset = -41; # from tail
2143                 my $rl;
2144                 open my $fh, '<', $REVDB or
2145                         die "--no-metadata specified and $REVDB not readable\n";
2146                 seek $fh, $offset, 2;
2147                 $rl = readline $fh;
2148                 defined $rl or return (undef, undef);
2149                 chomp $rl;
2150                 while ($c ne $rl && tell $fh != 0) {
2151                         $offset -= 41;
2152                         seek $fh, $offset, 2;
2153                         $rl = readline $fh;
2154                         defined $rl or return (undef, undef);
2155                         chomp $rl;
2156                 }
2157                 my $rev = tell $fh;
2158                 croak $! if ($rev < -1);
2159                 $rev =  ($rev - 41) / 41;
2160                 close $fh or croak $!;
2161                 return ($rev, $c);
2162         }
2163         return (undef, undef);
2166 sub libsvn_parse_revision {
2167         my $base = shift;
2168         my $head = $SVN->get_latest_revnum();
2169         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2170                 return ($base + 1, $head) if (defined $base);
2171                 return (0, $head);
2172         }
2173         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2174         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2175         if ($_revision =~ /^BASE:(\d+)$/) {
2176                 return ($base + 1, $1) if (defined $base);
2177                 return (0, $head);
2178         }
2179         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2180         die "revision argument: $_revision not understood by git-svn\n",
2181                 "Try using the command-line svn client instead\n";
2184 sub libsvn_traverse_ignore {
2185         my ($fh, $path, $r) = @_;
2186         $path =~ s#^/+##g;
2187         my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2188         my $p = $path;
2189         $p =~ s#^\Q$SVN->{svn_path}\E/##;
2190         print $fh length $p ? "\n# $p\n" : "\n# /\n";
2191         if (my $s = $props->{'svn:ignore'}) {
2192                 $s =~ s/[\r\n]+/\n/g;
2193                 chomp $s;
2194                 if (length $p == 0) {
2195                         $s =~ s#\n#\n/$p#g;
2196                         print $fh "/$s\n";
2197                 } else {
2198                         $s =~ s#\n#\n/$p/#g;
2199                         print $fh "/$p/$s\n";
2200                 }
2201         }
2202         foreach (sort keys %$dirent) {
2203                 next if $dirent->{$_}->kind != $SVN::Node::dir;
2204                 libsvn_traverse_ignore($fh, "$path/$_", $r);
2205         }
2208 sub revisions_eq {
2209         my ($path, $r0, $r1) = @_;
2210         return 1 if $r0 == $r1;
2211         my $nr = 0;
2212         # should be OK to use Pool here (r1 - r0) should be small
2213         $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2214         return 0 if ($nr > 1);
2215         return 1;
2218 sub libsvn_find_parent_branch {
2219         my ($paths, $rev, $author, $date, $msg) = @_;
2220         my $svn_path = '/'.$SVN->{svn_path};
2222         # look for a parent from another branch:
2223         my $i = $paths->{$svn_path} or return;
2224         my $branch_from = $i->copyfrom_path or return;
2225         my $r = $i->copyfrom_rev;
2226         print STDERR  "Found possible branch point: ",
2227                                 "$branch_from => $svn_path, $r\n";
2228         $branch_from =~ s#^/##;
2229         my $l_map = {};
2230         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2231         my $url = $SVN->{repos_root};
2232         defined $l_map->{$url} or return;
2233         my $id = $l_map->{$url}->{$branch_from};
2234         if (!defined $id && $_follow_parent) {
2235                 print STDERR "Following parent: $branch_from\@$r\n";
2236                 # auto create a new branch and follow it
2237                 $id = basename($branch_from);
2238                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2239                 while (-r "$GIT_DIR/svn/$id") {
2240                         # just grow a tail if we're not unique enough :x
2241                         $id .= '-';
2242                 }
2243         }
2244         return unless defined $id;
2246         my ($r0, $parent) = find_rev_before($r,$id,1);
2247         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2248                 defined(my $pid = fork) or croak $!;
2249                 if (!$pid) {
2250                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2251                         init_vars();
2252                         $SVN_URL = "$url/$branch_from";
2253                         $SVN = undef;
2254                         setup_git_svn();
2255                         # we can't assume SVN_URL exists at r+1:
2256                         $_revision = "0:$r";
2257                         fetch_lib();
2258                         exit 0;
2259                 }
2260                 waitpid $pid, 0;
2261                 croak $? if $?;
2262                 ($r0, $parent) = find_rev_before($r,$id,1);
2263         }
2264         return unless (defined $r0 && defined $parent);
2265         if (revisions_eq($branch_from, $r0, $r)) {
2266                 unlink $GIT_SVN_INDEX;
2267                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2268                 command_noisy('read-tree', $parent);
2269                 unless ($SVN->can_do_switch) {
2270                         return _libsvn_new_tree($paths, $rev, $author, $date,
2271                                                 $msg, [$parent]);
2272                 }
2273                 # do_switch works with svn/trunk >= r22312, but that is not
2274                 # included with SVN 1.4.2 (the latest version at the moment),
2275                 # so we can't rely on it.
2276                 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2277                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2278                 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2279                                    die "SVN connection failed somewhere...\n";
2280                 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2281         }
2282         print STDERR "Nope, branch point not imported or unknown\n";
2283         return undef;
2286 sub libsvn_new_tree {
2287         if (my $log_entry = libsvn_find_parent_branch(@_)) {
2288                 return $log_entry;
2289         }
2290         my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2291         _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2294 sub _libsvn_new_tree {
2295         my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2296         my $ed = SVN::Git::Fetcher->new({q => $_q});
2297         unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2298                 die "SVN connection failed somewhere...\n";
2299         }
2300         libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2303 sub find_graft_path_commit {
2304         my ($tree_paths, $p1, $r1) = @_;
2305         foreach my $x (keys %$tree_paths) {
2306                 next unless ($p1 =~ /^\Q$x\E/);
2307                 my $i = $tree_paths->{$x};
2308                 my ($r0, $parent) = find_rev_before($r1,$i,1);
2309                 return $parent if (defined $r0 && $r0 == $r1);
2310                 print STDERR "r$r1 of $i not imported\n";
2311                 next;
2312         }
2313         return undef;
2316 sub find_graft_path_parents {
2317         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2318         foreach my $x (keys %$tree_paths) {
2319                 next unless ($p0 =~ /^\Q$x\E/);
2320                 my $i = $tree_paths->{$x};
2321                 my ($r, $parent) = find_rev_before($r0, $i, 1);
2322                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2323                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2324                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2325                         next if ($url_a && $url_b && $url_a eq $url_b &&
2326                                                         $uuid_b eq $uuid_a);
2327                         $grafts->{$c}->{$parent} = 1;
2328                 }
2329         }
2332 sub libsvn_graft_file_copies {
2333         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2334         foreach (keys %$paths) {
2335                 my $i = $paths->{$_};
2336                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2337                                         $i->copyfrom_rev);
2338                 next unless (defined $p0 && defined $r0);
2340                 my $p1 = $_;
2341                 $p1 =~ s#^/##;
2342                 $p0 =~ s#^/##;
2343                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2344                 next unless $c;
2345                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2346         }
2349 sub set_index {
2350         my $old = $ENV{GIT_INDEX_FILE};
2351         $ENV{GIT_INDEX_FILE} = shift;
2352         return $old;
2355 sub restore_index {
2356         my ($old) = @_;
2357         if (defined $old) {
2358                 $ENV{GIT_INDEX_FILE} = $old;
2359         } else {
2360                 delete $ENV{GIT_INDEX_FILE};
2361         }
2364 sub libsvn_commit_cb {
2365         my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2366         if ($_optimize_commits && $rev == ($r_last + 1)) {
2367                 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2368                 $log->{tree} = get_tree_from_treeish($c);
2369                 my $cmt = git_commit($log, $cmt_last, $c);
2370                 my @diff = command('diff-tree', $cmt, $c);
2371                 if (@diff) {
2372                         print STDERR "Trees differ: $cmt $c\n",
2373                                         join('',@diff),"\n";
2374                         exit 1;
2375                 }
2376         } else {
2377                 fetch("$rev=$c");
2378         }
2381 sub libsvn_ls_fullurl {
2382         my $fullurl = shift;
2383         my $ra = Git::SVN::Ra->new($fullurl);
2384         my @ret;
2385         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
2386         my ($dirent, undef, undef) = $ra->get_dir('', $r);
2387         foreach my $d (sort keys %$dirent) {
2388                 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2389                         push @ret, "$d/"; # add '/' for compat with cli svn
2390                 }
2391         }
2392         return @ret;
2395 sub libsvn_skip_unknown_revs {
2396         my $err = shift;
2397         my $errno = $err->apr_err();
2398         # Maybe the branch we're tracking didn't
2399         # exist when the repo started, so it's
2400         # not an error if it doesn't, just continue
2401         #
2402         # Wonderfully consistent library, eh?
2403         # 160013 - svn:// and file://
2404         # 175002 - http(s)://
2405         # 175007 - http(s):// (this repo required authorization, too...)
2406         #   More codes may be discovered later...
2407         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2408                 return;
2409         }
2410         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2411 };
2413 # Tie::File seems to be prone to offset errors if revisions get sparse,
2414 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2415 # one of my favorite modules is out :<  Next up would be one of the DBM
2416 # modules, but I'm not sure which is most portable...  So I'll just
2417 # go with something that's plain-text, but still capable of
2418 # being randomly accessed.  So here's my ultra-simple fixed-width
2419 # database.  All records are 40 characters + "\n", so it's easy to seek
2420 # to a revision: (41 * rev) is the byte offset.
2421 # A record of 40 0s denotes an empty revision.
2422 # And yes, it's still pretty fast (faster than Tie::File).
2423 sub revdb_set {
2424         my ($file, $rev, $commit) = @_;
2425         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2426         open my $fh, '+<', $file or croak $!;
2427         my $offset = $rev * 41;
2428         # assume that append is the common case:
2429         seek $fh, 0, 2 or croak $!;
2430         my $pos = tell $fh;
2431         if ($pos < $offset) {
2432                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2433         }
2434         seek $fh, $offset, 0 or croak $!;
2435         print $fh $commit,"\n";
2436         close $fh or croak $!;
2439 sub revdb_get {
2440         my ($file, $rev) = @_;
2441         my $ret;
2442         my $offset = $rev * 41;
2443         open my $fh, '<', $file or croak $!;
2444         seek $fh, $offset, 0;
2445         if (tell $fh == $offset) {
2446                 $ret = readline $fh;
2447                 if (defined $ret) {
2448                         chomp $ret;
2449                         $ret = undef if ($ret =~ /^0{40}$/);
2450                 }
2451         }
2452         close $fh or croak $!;
2453         return $ret;
2456 sub copy_remote_ref {
2457         my $origin = $_cp_remote ? $_cp_remote : 'origin';
2458         my $ref = "refs/remotes/$GIT_SVN";
2459         if (command('ls-remote', $origin, $ref)) {
2460                 command_noisy('fetch', $origin, "$ref:$ref");
2461         } elsif ($_cp_remote && !$_upgrade) {
2462                 die "Unable to find remote reference: ",
2463                                 "refs/remotes/$GIT_SVN on $origin\n";
2464         }
2468         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2469                                 $SVN::Node::dir.$SVN::Node::unknown.
2470                                 $SVN::Node::none.$SVN::Node::file.
2471                                 $SVN::Node::dir.$SVN::Node::unknown.
2472                                 $SVN::Auth::SSL::CNMISMATCH.
2473                                 $SVN::Auth::SSL::NOTYETVALID.
2474                                 $SVN::Auth::SSL::EXPIRED.
2475                                 $SVN::Auth::SSL::UNKNOWNCA.
2476                                 $SVN::Auth::SSL::OTHER;
2479 package SVN::Git::Fetcher;
2480 use vars qw/@ISA/;
2481 use strict;
2482 use warnings;
2483 use Carp qw/croak/;
2484 use IO::File qw//;
2486 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2487 sub new {
2488         my ($class, $git_svn) = @_;
2489         my $self = SVN::Delta::Editor->new;
2490         bless $self, $class;
2491         $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2492         $self->{q} = $git_svn->{q};
2493         $self->{empty} = {};
2494         $self->{dir_prop} = {};
2495         $self->{file_prop} = {};
2496         $self->{absent_dir} = {};
2497         $self->{absent_file} = {};
2498         ($self->{gui}, $self->{ctx}) = command_input_pipe(
2499                                              qw/update-index -z --index-info/);
2500         require Digest::MD5;
2501         $self;
2504 sub open_root {
2505         { path => '' };
2508 sub open_directory {
2509         my ($self, $path, $pb, $rev) = @_;
2510         { path => $path };
2513 sub delete_entry {
2514         my ($self, $path, $rev, $pb) = @_;
2515         my $gui = $self->{gui};
2517         # remove entire directories.
2518         if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2519                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2520                                                      -r --name-only -z/,
2521                                                      $self->{c}, '--', $path);
2522                 local $/ = "\0";
2523                 while (<$ls>) {
2524                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2525                         print "\tD\t$_\n" unless $self->{q};
2526                 }
2527                 print "\tD\t$path/\n" unless $self->{q};
2528                 command_close_pipe($ls, $ctx);
2529                 $self->{empty}->{$path} = 0
2530         } else {
2531                 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
2532                 print "\tD\t$path\n" unless $self->{q};
2533         }
2534         undef;
2537 sub open_file {
2538         my ($self, $path, $pb, $rev) = @_;
2539         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
2540                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2541         unless (defined $mode && defined $blob) {
2542                 die "$path was not found in commit $self->{c} (r$rev)\n";
2543         }
2544         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2545           pool => SVN::Pool->new, action => 'M' };
2548 sub add_file {
2549         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2550         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2551         delete $self->{empty}->{$dir};
2552         { path => $path, mode_a => 100644, mode_b => 100644,
2553           pool => SVN::Pool->new, action => 'A' };
2556 sub add_directory {
2557         my ($self, $path, $cp_path, $cp_rev) = @_;
2558         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2559         delete $self->{empty}->{$dir};
2560         $self->{empty}->{$path} = 1;
2561         { path => $path };
2564 sub change_dir_prop {
2565         my ($self, $db, $prop, $value) = @_;
2566         $self->{dir_prop}->{$db->{path}} ||= {};
2567         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2568         undef;
2571 sub absent_directory {
2572         my ($self, $path, $pb) = @_;
2573         $self->{absent_dir}->{$pb->{path}} ||= [];
2574         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2575         undef;
2578 sub absent_file {
2579         my ($self, $path, $pb) = @_;
2580         $self->{absent_file}->{$pb->{path}} ||= [];
2581         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2582         undef;
2585 sub change_file_prop {
2586         my ($self, $fb, $prop, $value) = @_;
2587         if ($prop eq 'svn:executable') {
2588                 if ($fb->{mode_b} != 120000) {
2589                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2590                 }
2591         } elsif ($prop eq 'svn:special') {
2592                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2593         } else {
2594                 $self->{file_prop}->{$fb->{path}} ||= {};
2595                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2596         }
2597         undef;
2600 sub apply_textdelta {
2601         my ($self, $fb, $exp) = @_;
2602         my $fh = IO::File->new_tmpfile;
2603         $fh->autoflush(1);
2604         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2605         # (but $base does not,) so dup() it for reading in close_file
2606         open my $dup, '<&', $fh or croak $!;
2607         my $base = IO::File->new_tmpfile;
2608         $base->autoflush(1);
2609         if ($fb->{blob}) {
2610                 defined (my $pid = fork) or croak $!;
2611                 if (!$pid) {
2612                         open STDOUT, '>&', $base or croak $!;
2613                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2614                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2615                 }
2616                 waitpid $pid, 0;
2617                 croak $? if $?;
2619                 if (defined $exp) {
2620                         seek $base, 0, 0 or croak $!;
2621                         my $md5 = Digest::MD5->new;
2622                         $md5->addfile($base);
2623                         my $got = $md5->hexdigest;
2624                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2625                             "expected: $exp\n",
2626                             "     got: $got\n" if ($got ne $exp);
2627                 }
2628         }
2629         seek $base, 0, 0 or croak $!;
2630         $fb->{fh} = $dup;
2631         $fb->{base} = $base;
2632         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2635 sub close_file {
2636         my ($self, $fb, $exp) = @_;
2637         my $hash;
2638         my $path = $fb->{path};
2639         if (my $fh = $fb->{fh}) {
2640                 seek($fh, 0, 0) or croak $!;
2641                 my $md5 = Digest::MD5->new;
2642                 $md5->addfile($fh);
2643                 my $got = $md5->hexdigest;
2644                 die "Checksum mismatch: $path\n",
2645                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2646                 seek($fh, 0, 0) or croak $!;
2647                 if ($fb->{mode_b} == 120000) {
2648                         read($fh, my $buf, 5) == 5 or croak $!;
2649                         $buf eq 'link ' or die "$path has mode 120000",
2650                                                "but is not a link\n";
2651                 }
2652                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2653                 if (!$pid) {
2654                         open STDIN, '<&', $fh or croak $!;
2655                         exec qw/git-hash-object -w --stdin/ or croak $!;
2656                 }
2657                 chomp($hash = do { local $/; <$out> });
2658                 close $out or croak $!;
2659                 close $fh or croak $!;
2660                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2661                 close $fb->{base} or croak $!;
2662         } else {
2663                 $hash = $fb->{blob} or die "no blob information\n";
2664         }
2665         $fb->{pool}->clear;
2666         my $gui = $self->{gui};
2667         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
2668         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
2669         undef;
2672 sub abort_edit {
2673         my $self = shift;
2674         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
2675         $self->SUPER::abort_edit(@_);
2678 sub close_edit {
2679         my $self = shift;
2680         command_close_pipe($self->{gui}, $self->{ctx});
2681         $self->{git_commit_ok} = 1;
2682         $self->SUPER::close_edit(@_);
2685 package SVN::Git::Editor;
2686 use vars qw/@ISA/;
2687 use strict;
2688 use warnings;
2689 use Carp qw/croak/;
2690 use IO::File;
2692 sub new {
2693         my $class = shift;
2694         my $git_svn = shift;
2695         my $self = SVN::Delta::Editor->new(@_);
2696         bless $self, $class;
2697         foreach (qw/svn_path c r ra /) {
2698                 die "$_ required!\n" unless (defined $git_svn->{$_});
2699                 $self->{$_} = $git_svn->{$_};
2700         }
2701         $self->{pool} = SVN::Pool->new;
2702         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2703         $self->{rm} = { };
2704         require Digest::MD5;
2705         return $self;
2708 sub split_path {
2709         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2712 sub repo_path {
2713         (defined $_[1] && length $_[1]) ? $_[1] : ''
2716 sub url_path {
2717         my ($self, $path) = @_;
2718         $self->{ra}->{url} . '/' . $self->repo_path($path);
2721 sub rmdirs {
2722         my ($self, $q) = @_;
2723         my $rm = $self->{rm};
2724         delete $rm->{''}; # we never delete the url we're tracking
2725         return unless %$rm;
2727         foreach (keys %$rm) {
2728                 my @d = split m#/#, $_;
2729                 my $c = shift @d;
2730                 $rm->{$c} = 1;
2731                 while (@d) {
2732                         $c .= '/' . shift @d;
2733                         $rm->{$c} = 1;
2734                 }
2735         }
2736         delete $rm->{$self->{svn_path}};
2737         delete $rm->{''}; # we never delete the url we're tracking
2738         return unless %$rm;
2740         my ($fh, $ctx) = command_output_pipe(
2741                                    qw/ls-tree --name-only -r -z/, $self->{c});
2742         local $/ = "\0";
2743         while (<$fh>) {
2744                 chomp;
2745                 my @dn = split m#/#, $_;
2746                 while (pop @dn) {
2747                         delete $rm->{join '/', @dn};
2748                 }
2749                 unless (%$rm) {
2750                         close $fh;
2751                         return;
2752                 }
2753         }
2754         command_close_pipe($fh, $ctx);
2756         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2757         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2758                 $self->close_directory($bat->{$d}, $p);
2759                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2760                 print "\tD+\t$d/\n" unless $q;
2761                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2762                 delete $bat->{$d};
2763         }
2766 sub open_or_add_dir {
2767         my ($self, $full_path, $baton) = @_;
2768         my $t = $self->{ra}->check_path($full_path, $self->{r});
2769         if ($t == $SVN::Node::none) {
2770                 return $self->add_directory($full_path, $baton,
2771                                                 undef, -1, $self->{pool});
2772         } elsif ($t == $SVN::Node::dir) {
2773                 return $self->open_directory($full_path, $baton,
2774                                                 $self->{r}, $self->{pool});
2775         }
2776         print STDERR "$full_path already exists in repository at ",
2777                 "r$self->{r} and it is not a directory (",
2778                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2779         exit 1;
2782 sub ensure_path {
2783         my ($self, $path) = @_;
2784         my $bat = $self->{bat};
2785         $path = $self->repo_path($path);
2786         return $bat->{''} unless (length $path);
2787         my @p = split m#/+#, $path;
2788         my $c = shift @p;
2789         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2790         while (@p) {
2791                 my $c0 = $c;
2792                 $c .= '/' . shift @p;
2793                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2794         }
2795         return $bat->{$c};
2798 sub A {
2799         my ($self, $m, $q) = @_;
2800         my ($dir, $file) = split_path($m->{file_b});
2801         my $pbat = $self->ensure_path($dir);
2802         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2803                                         undef, -1);
2804         print "\tA\t$m->{file_b}\n" unless $q;
2805         $self->chg_file($fbat, $m);
2806         $self->close_file($fbat,undef,$self->{pool});
2809 sub C {
2810         my ($self, $m, $q) = @_;
2811         my ($dir, $file) = split_path($m->{file_b});
2812         my $pbat = $self->ensure_path($dir);
2813         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2814                                 $self->url_path($m->{file_a}), $self->{r});
2815         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
2816         $self->chg_file($fbat, $m);
2817         $self->close_file($fbat,undef,$self->{pool});
2820 sub delete_entry {
2821         my ($self, $path, $pbat) = @_;
2822         my $rpath = $self->repo_path($path);
2823         my ($dir, $file) = split_path($rpath);
2824         $self->{rm}->{$dir} = 1;
2825         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2828 sub R {
2829         my ($self, $m, $q) = @_;
2830         my ($dir, $file) = split_path($m->{file_b});
2831         my $pbat = $self->ensure_path($dir);
2832         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2833                                 $self->url_path($m->{file_a}), $self->{r});
2834         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
2835         $self->chg_file($fbat, $m);
2836         $self->close_file($fbat,undef,$self->{pool});
2838         ($dir, $file) = split_path($m->{file_a});
2839         $pbat = $self->ensure_path($dir);
2840         $self->delete_entry($m->{file_a}, $pbat);
2843 sub M {
2844         my ($self, $m, $q) = @_;
2845         my ($dir, $file) = split_path($m->{file_b});
2846         my $pbat = $self->ensure_path($dir);
2847         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2848                                 $pbat,$self->{r},$self->{pool});
2849         print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
2850         $self->chg_file($fbat, $m);
2851         $self->close_file($fbat,undef,$self->{pool});
2854 sub T { shift->M(@_) }
2856 sub change_file_prop {
2857         my ($self, $fbat, $pname, $pval) = @_;
2858         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2861 sub chg_file {
2862         my ($self, $fbat, $m) = @_;
2863         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2864                 $self->change_file_prop($fbat,'svn:executable','*');
2865         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2866                 $self->change_file_prop($fbat,'svn:executable',undef);
2867         }
2868         my $fh = IO::File->new_tmpfile or croak $!;
2869         if ($m->{mode_b} =~ /^120/) {
2870                 print $fh 'link ' or croak $!;
2871                 $self->change_file_prop($fbat,'svn:special','*');
2872         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2873                 $self->change_file_prop($fbat,'svn:special',undef);
2874         }
2875         defined(my $pid = fork) or croak $!;
2876         if (!$pid) {
2877                 open STDOUT, '>&', $fh or croak $!;
2878                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2879         }
2880         waitpid $pid, 0;
2881         croak $? if $?;
2882         $fh->flush == 0 or croak $!;
2883         seek $fh, 0, 0 or croak $!;
2885         my $md5 = Digest::MD5->new;
2886         $md5->addfile($fh) or croak $!;
2887         seek $fh, 0, 0 or croak $!;
2889         my $exp = $md5->hexdigest;
2890         my $pool = SVN::Pool->new;
2891         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2892         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2893         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2894         $pool->clear;
2896         close $fh or croak $!;
2899 sub D {
2900         my ($self, $m, $q) = @_;
2901         my ($dir, $file) = split_path($m->{file_b});
2902         my $pbat = $self->ensure_path($dir);
2903         print "\tD\t$m->{file_b}\n" unless $q;
2904         $self->delete_entry($m->{file_b}, $pbat);
2907 sub close_edit {
2908         my ($self) = @_;
2909         my ($p,$bat) = ($self->{pool}, $self->{bat});
2910         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2911                 $self->close_directory($bat->{$_}, $p);
2912         }
2913         $self->SUPER::close_edit($p);
2914         $p->clear;
2917 sub abort_edit {
2918         my ($self) = @_;
2919         $self->SUPER::abort_edit($self->{pool});
2920         $self->{pool}->clear;
2923 package Git::SVN::Ra;
2924 use vars qw/@ISA $config_dir/;
2925 use strict;
2926 use warnings;
2927 my ($can_do_switch);
2929 BEGIN {
2930         # enforce temporary pool usage for some simple functions
2931         my $e;
2932         foreach (qw/get_latest_revnum rev_proplist get_file
2933                     check_path get_dir get_uuid get_repos_root/) {
2934                 $e .= "sub $_ {
2935                         my \$self = shift;
2936                         my \$pool = SVN::Pool->new;
2937                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2938                         \$pool->clear;
2939                         wantarray ? \@ret : \$ret[0]; }\n";
2940         }
2941         eval $e;
2944 sub new {
2945         my ($class, $url) = @_;
2946         SVN::_Core::svn_config_ensure($config_dir, undef);
2947         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2948             SVN::Client::get_simple_provider(),
2949             SVN::Client::get_ssl_server_trust_file_provider(),
2950             SVN::Client::get_simple_prompt_provider(
2951               \&Git::SVN::Prompt::simple, 2),
2952             SVN::Client::get_ssl_client_cert_prompt_provider(
2953               \&Git::SVN::Prompt::ssl_client_cert, 2),
2954             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2955               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2956             SVN::Client::get_username_provider(),
2957             SVN::Client::get_ssl_server_trust_prompt_provider(
2958               \&Git::SVN::Prompt::ssl_server_trust),
2959             SVN::Client::get_username_prompt_provider(
2960               \&Git::SVN::Prompt::username, 2),
2961           ]);
2962         my $config = SVN::Core::config_get_config($config_dir);
2963         my $self = SVN::Ra->new(url => $url, auth => $baton,
2964                               config => $config,
2965                               pool => SVN::Pool->new,
2966                               auth_provider_callbacks => $callbacks);
2967         $self->{svn_path} = $url;
2968         $self->{repos_root} = $self->get_repos_root;
2969         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2970         bless $self, $class;
2973 sub DESTROY {
2974         my $self = shift;
2975         $self->{pool}->clear if $self->{pool};
2976         $self->SUPER::DESTROY(@_);
2979 sub dup {
2980         my ($self) = @_;
2981         my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2982                                 map { $_ => $self->{$_} } qw/config url
2983                      auth auth_provider_callbacks repos_root svn_path/);
2984         bless $dup, ref $self;
2987 sub get_log {
2988         my ($self, @args) = @_;
2989         my $pool = SVN::Pool->new;
2990         $args[4]-- if $args[4] && ! $::_follow_parent;
2991         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2992         my $ret = $self->SUPER::get_log(@args, $pool);
2993         $pool->clear;
2994         $ret;
2997 sub get_commit_editor {
2998         my ($self, $msg, $cb, $pool) = @_;
2999         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3000         $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3003 sub uuid {
3004         my ($self) = @_;
3005         $self->{uuid} ||= $self->get_uuid;
3008 sub gs_do_update {
3009         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3010         my $pool = SVN::Pool->new;
3011         my $reporter = $self->do_update($rev_b, $path, $recurse,
3012                                         $editor, $pool);
3013         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3014         my $new = ($rev_a == $rev_b);
3015         $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3016         $reporter->finish_report($pool);
3017         $pool->clear;
3018         $editor->{git_commit_ok};
3021 sub gs_do_switch {
3022         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3023         my $pool = SVN::Pool->new;
3024         my $reporter = $self->do_switch($rev_b, $path, $recurse,
3025                                         $url_b, $editor, $pool);
3026         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3027         $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3028         $reporter->finish_report($pool);
3029         $pool->clear;
3030         $editor->{git_commit_ok};
3033 sub can_do_switch {
3034         my $self = shift;
3035         unless (defined $can_do_switch) {
3036                 my $pool = SVN::Pool->new;
3037                 my $rep = eval {
3038                         $self->do_switch(1, '', 0, $self->{url},
3039                                          SVN::Delta::Editor->new, $pool);
3040                 };
3041                 if ($@) {
3042                         $can_do_switch = 0;
3043                 } else {
3044                         $rep->abort_report($pool);
3045                         $can_do_switch = 1;
3046                 }
3047                 $pool->clear;
3048         }
3049         $can_do_switch;
3052 __END__
3054 Data structures:
3056 $log_msg hashref as returned by libsvn_log_entry()
3058         msg => 'whitespace-formatted log entry
3059 ',                                              # trailing newline is preserved
3060         revision => '8',                        # integer
3061         date => '2004-02-24T17:01:44.108345Z',  # commit date
3062         author => 'committer name'
3063 };
3065 @mods = array of diff-index line hashes, each element represents one line
3066         of diff-index output
3068 diff-index line ($m hash)
3070         mode_a => first column of diff-index output, no leading ':',
3071         mode_b => second column of diff-index output,
3072         sha1_b => sha1sum of the final blob,
3073         chg => change type [MCRADT],
3074         file_a => original file name of a file (iff chg is 'C' or 'R')
3075         file_b => new/current file name of a file (any chg)
3079 # retval of read_url_paths{,_all}();
3080 $l_map = {
3081         # repository root url
3082         'https://svn.musicpd.org' => {
3083                 # repository path               # GIT_SVN_ID
3084                 'mpd/trunk'             =>      'trunk',
3085                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3086         },
3089 Notes:
3090         I don't trust the each() function on unless I created %hash myself
3091         because the internal iterator may not have started at base.