2e3d35527e836bea2bb7a30fb6b39387ed3621a3
1#!/usr/bin/env perl
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
7 $SVN_URL
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB
10 $_follow_parent $sha1 $sha1_short $_revision
11 $_cp_remote $_upgrade $_rmdir $_q $_cp_similarity
12 $_find_copies_harder $_l $_authors %users/;
13$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
14$VERSION = '@@GIT_VERSION@@';
15
16$ENV{GIT_DIR} ||= '.git';
17$Git::SVN::default_repo_id = 'git-svn';
18$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
19
20my $LC_ALL = $ENV{LC_ALL};
21$Git::SVN::Log::TZ = $ENV{TZ};
22# make sure the svn binary gives consistent output between locales and TZs:
23$ENV{TZ} = 'UTC';
24$ENV{LC_ALL} = 'C';
25$| = 1; # unbuffer STDOUT
26
27sub fatal (@) { print STDERR @_; exit 1 }
28require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29require SVN::Ra;
30require SVN::Delta;
31if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
33}
34push @Git::SVN::Ra::ISA, 'SVN::Ra';
35push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37use Carp qw/croak/;
38use IO::File qw//;
39use File::Basename qw/dirname basename/;
40use File::Path qw/mkpath/;
41use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
42use IPC::Open3;
43use Git;
44
45BEGIN {
46 my $s;
47 foreach (qw/command command_oneline command_noisy command_output_pipe
48 command_input_pipe command_close_pipe/) {
49 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
50 "*Git::SVN::Migration::$_ = ".
51 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
52 }
53 eval $s;
54}
55
56my ($SVN);
57
58my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
59$sha1 = qr/[a-f\d]{40}/;
60$sha1_short = qr/[a-f\d]{4,40}/;
61my ($_stdin, $_help, $_edit,
62 $_repack, $_repack_nr, $_repack_flags,
63 $_message, $_file, $_no_metadata,
64 $_template, $_shared,
65 $_version, $_upgrade,
66 $_merge, $_strategy, $_dry_run,
67 $_prefix);
68
69my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
70 'config-dir=s' => \$Git::SVN::Ra::config_dir,
71 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
72my %fc_opts = ( 'follow-parent|follow' => \$_follow_parent,
73 'authors-file|A=s' => \$_authors,
74 'repack:i' => \$_repack,
75 'no-metadata' => \$_no_metadata,
76 'quiet|q' => \$_q,
77 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags,
78 %remote_opts );
79
80my ($_trunk, $_tags, $_branches);
81my %multi_opts = ( 'trunk|T=s' => \$_trunk,
82 'tags|t=s' => \$_tags,
83 'branches|b=s' => \$_branches );
84my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
85my %cmt_opts = ( 'edit|e' => \$_edit,
86 'rmdir' => \$_rmdir,
87 'find-copies-harder' => \$_find_copies_harder,
88 'l=i' => \$_l,
89 'copy-similarity|C=i'=> \$_cp_similarity
90);
91
92my %cmd = (
93 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
94 { 'revision|r=s' => \$_revision, %fc_opts } ],
95 init => [ \&cmd_init, "Initialize a repo for tracking" .
96 " (requires URL argument)",
97 \%init_opts ],
98 dcommit => [ \&cmd_dcommit,
99 'Commit several diffs to merge with upstream',
100 { 'merge|m|M' => \$_merge,
101 'strategy|s=s' => \$_strategy,
102 'dry-run|n' => \$_dry_run,
103 %cmt_opts, %fc_opts } ],
104 'set-tree' => [ \&cmd_set_tree,
105 "Set an SVN repository to a git tree-ish",
106 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
107 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
108 { 'revision|r=i' => \$_revision } ],
109 rebuild => [ \&cmd_rebuild, "Rebuild git-svn metadata (after git clone)",
110 { 'copy-remote|remote=s' => \$_cp_remote,
111 'upgrade' => \$_upgrade } ],
112 'multi-init' => [ \&cmd_multi_init,
113 'Initialize multiple trees (like git-svnimport)',
114 { %multi_opts, %init_opts, %remote_opts,
115 'revision|r=i' => \$_revision,
116 'prefix=s' => \$_prefix,
117 } ],
118 'multi-fetch' => [ \&cmd_multi_fetch,
119 'Fetch multiple trees (like git-svnimport)',
120 \%fc_opts ],
121 'migrate' => [ sub { },
122 # no-op, we automatically run this anyways,
123 'Migrate configuration/metadata/layout from
124 previous versions of git-svn',
125 \%remote_opts ],
126 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
127 { 'limit=i' => \$Git::SVN::Log::limit,
128 'revision|r=s' => \$_revision,
129 'verbose|v' => \$Git::SVN::Log::verbose,
130 'incremental' => \$Git::SVN::Log::incremental,
131 'oneline' => \$Git::SVN::Log::oneline,
132 'show-commit' => \$Git::SVN::Log::show_commit,
133 'non-recursive' => \$Git::SVN::Log::non_recursive,
134 'authors-file|A=s' => \$_authors,
135 'color' => \$Git::SVN::Log::color,
136 'pager=s' => \$Git::SVN::Log::pager,
137 } ],
138 'commit-diff' => [ \&cmd_commit_diff,
139 'Commit a diff between two trees',
140 { 'message|m=s' => \$_message,
141 'file|F=s' => \$_file,
142 'revision|r=s' => \$_revision,
143 %cmt_opts } ],
144);
145
146my $cmd;
147for (my $i = 0; $i < @ARGV; $i++) {
148 if (defined $cmd{$ARGV[$i]}) {
149 $cmd = $ARGV[$i];
150 splice @ARGV, $i, 1;
151 last;
152 }
153};
154
155my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
156
157read_repo_config(\%opts);
158my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
159 'version|V' => \$_version,
160 'minimize-connections' =>
161 \$Git::SVN::Migration::_minimize,
162 'id|i=s' => \$Git::SVN::default_ref_id);
163exit 1 if (!$rv && $cmd ne 'log');
164
165usage(0) if $_help;
166version() if $_version;
167usage(1) unless defined $cmd;
168load_authors() if $_authors;
169unless ($cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/) {
170 Git::SVN::Migration::migration_check();
171}
172eval {
173 Git::SVN::verify_remotes_sanity();
174 $cmd{$cmd}->[0]->(@ARGV);
175};
176fatal $@ if $@;
177exit 0;
178
179####################### primary functions ######################
180sub usage {
181 my $exit = shift || 0;
182 my $fd = $exit ? \*STDERR : \*STDOUT;
183 print $fd <<"";
184git-svn - bidirectional operations between a single Subversion tree and git
185Usage: $0 <command> [options] [arguments]\n
186
187 print $fd "Available commands:\n" unless $cmd;
188
189 foreach (sort keys %cmd) {
190 next if $cmd && $cmd ne $_;
191 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
192 foreach (keys %{$cmd{$_}->[2]}) {
193 # prints out arguments as they should be passed:
194 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
195 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
196 "--$_" : "-$_" }
197 split /\|/,$_)," $x\n";
198 }
199 }
200 print $fd <<"";
201\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
202arbitrary identifier if you're tracking multiple SVN branches/repositories in
203one git repository and want to keep them separate. See git-svn(1) for more
204information.
205
206 exit $exit;
207}
208
209sub version {
210 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
211 exit 0;
212}
213
214sub cmd_rebuild {
215 my $url = shift;
216 my $gs = $url ? Git::SVN->init($url)
217 : eval { Git::SVN->new };
218 $gs ||= Git::SVN->_new;
219 if (!verify_ref($gs->refname.'^0')) {
220 $gs->copy_remote_ref;
221 }
222
223 my ($rev_list, $ctx) = command_output_pipe("rev-list", $gs->refname);
224 my $latest;
225 my $svn_uuid;
226 while (<$rev_list>) {
227 chomp;
228 my $c = $_;
229 fatal "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
230 my ($url, $rev, $uuid) = cmt_metadata($c);
231
232 # ignore merges (from set-tree)
233 next if (!defined $rev || !$uuid);
234
235 # if we merged or otherwise started elsewhere, this is
236 # how we break out of it
237 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
238 ($gs->{url} && $url && ($url ne $gs->{url}))) {
239 next;
240 }
241
242 unless (defined $latest) {
243 if (!$gs->{url} && !$url) {
244 fatal "SVN repository location required\n";
245 }
246 $gs = Git::SVN->init($url);
247 $latest = $rev;
248 }
249 $gs->rev_db_set($rev, $c);
250 print "r$rev = $c\n";
251 }
252 command_close_pipe($rev_list, $ctx);
253}
254
255sub do_git_init_db {
256 unless (-d $ENV{GIT_DIR}) {
257 my @init_db = ('init');
258 push @init_db, "--template=$_template" if defined $_template;
259 push @init_db, "--shared" if defined $_shared;
260 command_noisy(@init_db);
261 }
262}
263
264sub cmd_init {
265 my $url = shift or die "SVN repository location required " .
266 "as a command-line argument\n";
267 if (my $repo_path = shift) {
268 unless (-d $repo_path) {
269 mkpath([$repo_path]);
270 }
271 chdir $repo_path or croak $!;
272 $ENV{GIT_DIR} = $repo_path . "/.git";
273 }
274 do_git_init_db();
275
276 Git::SVN->init($url);
277}
278
279sub cmd_fetch {
280 if (@_) {
281 die "Additional fetch arguments are no longer supported.\n",
282 "Use --follow-parent if you have moved/copied directories
283 instead.\n";
284 }
285 my $gs = Git::SVN->new;
286 $gs->fetch;
287 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
288 command_noisy(qw(update-ref refs/heads/master),
289 $gs->{last_commit});
290 }
291}
292
293sub cmd_set_tree {
294 my (@commits) = @_;
295 if ($_stdin || !@commits) {
296 print "Reading from stdin...\n";
297 @commits = ();
298 while (<STDIN>) {
299 if (/\b($sha1_short)\b/o) {
300 unshift @commits, $1;
301 }
302 }
303 }
304 my @revs;
305 foreach my $c (@commits) {
306 my @tmp = command('rev-parse',$c);
307 if (scalar @tmp == 1) {
308 push @revs, $tmp[0];
309 } elsif (scalar @tmp > 1) {
310 push @revs, reverse(command('rev-list',@tmp));
311 } else {
312 fatal "Failed to rev-parse $c\n";
313 }
314 }
315 my $gs = Git::SVN->new;
316 my ($r_last, $cmt_last) = $gs->last_rev_commit;
317 $gs->fetch;
318 if ($r_last != $gs->{last_rev}) {
319 fatal "There are new revisions that were fetched ",
320 "and need to be merged (or acknowledged) ",
321 "before committing.\nlast rev: $r_last\n",
322 " current: $gs->{last_rev}\n";
323 }
324 $gs->set_tree($_) foreach @revs;
325 print "Done committing ",scalar @revs," revisions to SVN\n";
326}
327
328sub cmd_dcommit {
329 my $head = shift;
330 my $gs = Git::SVN->new;
331 $head ||= 'HEAD';
332 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
333 my $last_rev;
334 foreach my $d (reverse @refs) {
335 if (!verify_ref("$d~1")) {
336 fatal "Commit $d\n",
337 "has no parent commit, and therefore ",
338 "nothing to diff against.\n",
339 "You should be working from a repository ",
340 "originally created by git-svn\n";
341 }
342 unless (defined $last_rev) {
343 (undef, $last_rev, undef) = cmt_metadata("$d~1");
344 unless (defined $last_rev) {
345 fatal "Unable to extract revision information ",
346 "from commit $d~1\n";
347 }
348 }
349 if ($_dry_run) {
350 print "diff-tree $d~1 $d\n";
351 } else {
352 my $log = get_commit_entry($d)->{log};
353 my $ra = $gs->ra;
354 my $pool = SVN::Pool->new;
355 my %ed_opts = ( r => $last_rev,
356 ra => $ra->dup,
357 svn_path => $ra->{svn_path} );
358 my $ed = SVN::Git::Editor->new(\%ed_opts,
359 $ra->get_commit_editor($log,
360 sub { print "Committed r$_[0]\n";
361 $last_rev = $_[0]; }),
362 $pool);
363 my $mods = $ed->apply_diff("$d~1", $d);
364 if (@$mods == 0) {
365 print "No changes\n$d~1 == $d\n";
366 }
367 }
368 }
369 return if $_dry_run;
370 $gs->fetch;
371 # we always want to rebase against the current HEAD, not any
372 # head that was passed to us
373 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
374 my @finish;
375 if (@diff) {
376 @finish = qw/rebase/;
377 push @finish, qw/--merge/ if $_merge;
378 push @finish, "--strategy=$_strategy" if $_strategy;
379 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
380 "using @finish:\n", "@diff";
381 } else {
382 print "No changes between current HEAD and ",
383 $gs->refname, "\nResetting to the latest ",
384 $gs->refname, "\n";
385 @finish = qw/reset --mixed/;
386 }
387 command_noisy(@finish, $gs->refname);
388}
389
390sub cmd_show_ignore {
391 my $gs = Git::SVN->new;
392 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
393 $gs->traverse_ignore(\*STDOUT, '', $r);
394}
395
396sub cmd_multi_init {
397 my $url = shift;
398 unless (defined $_trunk || defined $_branches || defined $_tags) {
399 usage(1);
400 }
401 do_git_init_db();
402 $_prefix = '' unless defined $_prefix;
403 $url =~ s#/+$## if defined $url;
404 if (defined $_trunk) {
405 my $trunk_ref = $_prefix . 'trunk';
406 # try both old-style and new-style lookups:
407 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
408 unless ($gs_trunk) {
409 my ($trunk_url, $trunk_path) =
410 complete_svn_url($url, $_trunk);
411 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
412 undef, $trunk_ref);
413 }
414 }
415 return unless defined $_branches || defined $_tags;
416 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
417 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
418 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
419}
420
421sub cmd_multi_fetch {
422 my @gs;
423 foreach (command(qw/config -l/)) {
424 next unless m!^svn-remote\.(.+)\.fetch=
425 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
426 my ($repo_id, $path, $ref_id) = ($1, $2, $3);
427 push @gs, Git::SVN->new($ref_id, $repo_id, $path);
428 }
429 foreach (@gs) {
430 $_->fetch;
431 }
432}
433
434# this command is special because it requires no metadata
435sub cmd_commit_diff {
436 my ($ta, $tb, $url) = @_;
437 my $usage = "Usage: $0 commit-diff -r<revision> ".
438 "<tree-ish> <tree-ish> [<URL>]\n";
439 fatal($usage) if (!defined $ta || !defined $tb);
440 if (!defined $url) {
441 my $gs = eval { Git::SVN->new };
442 if (!$gs) {
443 fatal("Needed URL or usable git-svn --id in ",
444 "the command-line\n", $usage);
445 }
446 $url = $gs->{url};
447 }
448 unless (defined $_revision) {
449 fatal("-r|--revision is a required argument\n", $usage);
450 }
451 if (defined $_message && defined $_file) {
452 fatal("Both --message/-m and --file/-F specified ",
453 "for the commit message.\n",
454 "I have no idea what you mean\n");
455 }
456 if (defined $_file) {
457 $_message = file_to_s($_file);
458 } else {
459 $_message ||= get_commit_entry($tb)->{log};
460 }
461 my $ra ||= Git::SVN::Ra->new($url);
462 my $r = $_revision;
463 if ($r eq 'HEAD') {
464 $r = $ra->get_latest_revnum;
465 } elsif ($r !~ /^\d+$/) {
466 die "revision argument: $r not understood by git-svn\n";
467 }
468 my $pool = SVN::Pool->new;
469 my %ed_opts = ( r => $r,
470 ra => $ra->dup,
471 svn_path => $ra->{svn_path} );
472 my $ed = SVN::Git::Editor->new(\%ed_opts,
473 $ra->get_commit_editor($_message,
474 sub { print "Committed r$_[0]\n" }),
475 $pool);
476 my $mods = $ed->apply_diff($ta, $tb);
477 if (@$mods == 0) {
478 print "No changes\n$ta == $tb\n";
479 }
480 $pool->clear;
481}
482
483########################### utility functions #########################
484
485sub complete_svn_url {
486 my ($url, $path) = @_;
487 $path =~ s#/+$##;
488 if ($path !~ m#^[a-z\+]+://#) {
489 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
490 fatal("E: '$path' is not a complete URL ",
491 "and a separate URL is not specified\n");
492 }
493 return ($url, $path);
494 }
495 return ($path, '');
496}
497
498sub complete_url_ls_init {
499 my ($ra, $repo_path, $switch, $pfx) = @_;
500 unless ($repo_path) {
501 print STDERR "W: $switch not specified\n";
502 return;
503 }
504 $repo_path =~ s#/+$##;
505 if ($repo_path =~ m#^[a-z\+]+://#) {
506 $ra = Git::SVN::Ra->new($repo_path);
507 $repo_path = '';
508 } else {
509 $repo_path =~ s#^/+##;
510 unless ($ra) {
511 fatal("E: '$repo_path' is not a complete URL ",
512 "and a separate URL is not specified\n");
513 }
514 }
515 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
516 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
517 my $url = $ra->{url};
518 foreach my $d (sort keys %$dirent) {
519 next if ($dirent->{$d}->kind != $SVN::Node::dir);
520 my $path = "$repo_path/$d";
521 my $ref = "$pfx$d";
522 my $gs = eval { Git::SVN->new($ref) };
523 # don't try to init already existing refs
524 unless ($gs) {
525 print "init $url/$path => $ref\n";
526 Git::SVN->init($url, $path, undef, $ref);
527 }
528 }
529}
530
531sub verify_ref {
532 my ($ref) = @_;
533 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
534 { STDERR => 0 }); };
535}
536
537sub get_tree_from_treeish {
538 my ($treeish) = @_;
539 # $treeish can be a symbolic ref, too:
540 my $type = command_oneline(qw/cat-file -t/, $treeish);
541 my $expected;
542 while ($type eq 'tag') {
543 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
544 }
545 if ($type eq 'commit') {
546 $expected = (grep /^tree /, command(qw/cat-file commit/,
547 $treeish))[0];
548 ($expected) = ($expected =~ /^tree ($sha1)$/o);
549 die "Unable to get tree from $treeish\n" unless $expected;
550 } elsif ($type eq 'tree') {
551 $expected = $treeish;
552 } else {
553 die "$treeish is a $type, expected tree, tag or commit\n";
554 }
555 return $expected;
556}
557
558sub get_commit_entry {
559 my ($treeish) = shift;
560 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
561 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
562 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
563 open my $log_fh, '>', $commit_editmsg or croak $!;
564
565 my $type = command_oneline(qw/cat-file -t/, $treeish);
566 if ($type eq 'commit' || $type eq 'tag') {
567 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
568 $type, $treeish);
569 my $in_msg = 0;
570 while (<$msg_fh>) {
571 if (!$in_msg) {
572 $in_msg = 1 if (/^\s*$/);
573 } elsif (/^git-svn-id: /) {
574 # skip this for now, we regenerate the
575 # correct one on re-fetch anyways
576 # TODO: set *:merge properties or like...
577 } else {
578 print $log_fh $_ or croak $!;
579 }
580 }
581 command_close_pipe($msg_fh, $ctx);
582 }
583 close $log_fh or croak $!;
584
585 if ($_edit || ($type eq 'tree')) {
586 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
587 # TODO: strip out spaces, comments, like git-commit.sh
588 system($editor, $commit_editmsg);
589 }
590 rename $commit_editmsg, $commit_msg or croak $!;
591 open $log_fh, '<', $commit_msg or croak $!;
592 { local $/; chomp($log_entry{log} = <$log_fh>); }
593 close $log_fh or croak $!;
594 unlink $commit_msg;
595 \%log_entry;
596}
597
598sub s_to_file {
599 my ($str, $file, $mode) = @_;
600 open my $fd,'>',$file or croak $!;
601 print $fd $str,"\n" or croak $!;
602 close $fd or croak $!;
603 chmod ($mode &~ umask, $file) if (defined $mode);
604}
605
606sub file_to_s {
607 my $file = shift;
608 open my $fd,'<',$file or croak "$!: file: $file\n";
609 local $/;
610 my $ret = <$fd>;
611 close $fd or croak $!;
612 $ret =~ s/\s*$//s;
613 return $ret;
614}
615
616# '<svn username> = real-name <email address>' mapping based on git-svnimport:
617sub load_authors {
618 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
619 my $log = $cmd eq 'log';
620 while (<$authors>) {
621 chomp;
622 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
623 my ($user, $name, $email) = ($1, $2, $3);
624 if ($log) {
625 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
626 } else {
627 $users{$user} = [$name, $email];
628 }
629 }
630 close $authors or croak $!;
631}
632
633# convert GetOpt::Long specs for use by git-config
634sub read_repo_config {
635 return unless -d $ENV{GIT_DIR};
636 my $opts = shift;
637 foreach my $o (keys %$opts) {
638 my $v = $opts->{$o};
639 my ($key) = ($o =~ /^([a-z\-]+)/);
640 $key =~ s/-//g;
641 my $arg = 'git-config';
642 $arg .= ' --int' if ($o =~ /[:=]i$/);
643 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
644 if (ref $v eq 'ARRAY') {
645 chomp(my @tmp = `$arg --get-all svn.$key`);
646 @$v = @tmp if @tmp;
647 } else {
648 chomp(my $tmp = `$arg --get svn.$key`);
649 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
650 $$v = $tmp;
651 }
652 }
653 }
654}
655
656sub extract_metadata {
657 my $id = shift or return (undef, undef, undef);
658 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
659 \s([a-f\d\-]+)$/x);
660 if (!defined $rev || !$uuid || !$url) {
661 # some of the original repositories I made had
662 # identifiers like this:
663 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
664 }
665 return ($url, $rev, $uuid);
666}
667
668sub cmt_metadata {
669 return extract_metadata((grep(/^git-svn-id: /,
670 command(qw/cat-file commit/, shift)))[-1]);
671}
672
673sub get_commit_time {
674 my $cmt = shift;
675 my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
676 while (<$fh>) {
677 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
678 my ($s, $tz) = ($1, $2);
679 if ($tz =~ s/^\+//) {
680 $s += tz_to_s_offset($tz);
681 } elsif ($tz =~ s/^\-//) {
682 $s -= tz_to_s_offset($tz);
683 }
684 close $fh;
685 return $s;
686 }
687 die "Can't get commit time for commit: $cmt\n";
688}
689
690sub tz_to_s_offset {
691 my ($tz) = @_;
692 $tz =~ s/(\d\d)$//;
693 return ($1 * 60) + ($tz * 3600);
694}
695
696package Git::SVN;
697use strict;
698use warnings;
699use vars qw/$default_repo_id $default_ref_id/;
700use Carp qw/croak/;
701use File::Path qw/mkpath/;
702use IPC::Open3;
703
704# properties that we do not log:
705my %SKIP_PROP;
706BEGIN {
707 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
708 svn:special svn:executable
709 svn:entry:committed-rev
710 svn:entry:last-author
711 svn:entry:uuid
712 svn:entry:committed-date/;
713}
714
715sub read_all_remotes {
716 my $r = {};
717 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
718 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
719 $r->{$1}->{fetch}->{$2} = $3;
720 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
721 $r->{$1}->{url} = $2;
722 }
723 }
724 $r;
725}
726
727sub verify_remotes_sanity {
728 my %seen;
729 foreach (command(qw/config -l/)) {
730 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
731 if ($seen{$1}) {
732 die "Remote ref refs/remote/$1 is tracked by",
733 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
734 "Please resolve this ambiguity in ",
735 "your git configuration file before ",
736 "continuing\n";
737 }
738 $seen{$1} = $_;
739 }
740 }
741}
742
743# we allow more chars than remotes2config.sh...
744sub sanitize_remote_name {
745 my ($name) = @_;
746 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
747 $name;
748}
749
750sub init {
751 my ($class, $url, $path, $repo_id, $ref_id) = @_;
752 my $self = _new($class, $repo_id, $ref_id, $path);
753 if (defined $url) {
754 $url =~ s!/+$!!; # strip trailing slash
755
756 # verify that we aren't overwriting anything:
757 my $orig_url = eval {
758 command_oneline('config', '--get',
759 "svn-remote.$repo_id.url")
760 };
761 if ($orig_url && ($orig_url ne $url)) {
762 die "svn-remote.$repo_id.url already set: ",
763 "$orig_url\nwanted to set to: $url\n";
764 }
765 my ($xrepo_id, $xpath) = find_ref($self->refname);
766 if (defined $xpath) {
767 die "svn-remote.$xrepo_id.fetch already set to track ",
768 "$xpath:refs/remotes/", $self->refname, "\n";
769 }
770 if (!$orig_url) {
771 command_noisy('config',
772 "svn-remote.$repo_id.url", $url);
773 }
774 command_noisy('config', '--add',
775 "svn-remote.$repo_id.fetch",
776 "$path:".$self->refname);
777 }
778 $self->{url} = $url;
779 $self;
780}
781
782sub find_ref {
783 my ($ref_id) = @_;
784 foreach (command(qw/config -l/)) {
785 next unless m!^svn-remote\.(.+)\.fetch=
786 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
787 my ($repo_id, $path, $ref) = ($1, $2, $3);
788 if ($ref eq $ref_id) {
789 $path = '' if ($path =~ m#^\./?#);
790 return ($repo_id, $path);
791 }
792 }
793 (undef, undef, undef);
794}
795
796sub new {
797 my ($class, $ref_id, $repo_id, $path) = @_;
798 if (defined $ref_id && !defined $repo_id && !defined $path) {
799 ($repo_id, $path) = find_ref($ref_id);
800 if (!defined $repo_id) {
801 die "Could not find a \"svn-remote.*.fetch\" key ",
802 "in the repository configuration matching: ",
803 "refs/remotes/$ref_id\n";
804 }
805 }
806 my $self = _new($class, $repo_id, $ref_id, $path);
807 if (!defined $self->{path} || !length $self->{path}) {
808 my $fetch = command_oneline('config', '--get',
809 "svn-remote.$repo_id.fetch",
810 ":refs/remotes/$ref_id\$") or
811 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
812 "\":refs/remotes/$ref_id\$\" in config\n";
813 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
814 }
815 $self->{url} = command_oneline('config', '--get',
816 "svn-remote.$repo_id.url") or
817 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
818 $self;
819}
820
821sub refname { "refs/remotes/$_[0]->{ref_id}" }
822
823sub ra {
824 my ($self) = shift;
825 $self->{ra} ||= Git::SVN::Ra->new($self->{url});
826}
827
828sub rel_path {
829 my ($self) = @_;
830 my $repos_root = $self->ra->{repos_root};
831 return $self->{path} if ($self->{url} eq $repos_root);
832 my $url = $self->{url} .
833 (length $self->{path} ? "/$self->{path}" : $self->{path});
834 $url =~ s!^\Q$repos_root\E/*!!g;
835 $url;
836}
837
838sub copy_remote_ref {
839 my ($self) = @_;
840 my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
841 my $ref = $self->refname;
842 if (command('ls-remote', $origin, $ref)) {
843 command_noisy('fetch', $origin, "$ref:$ref");
844 } elsif ($::_cp_remote && !$::_upgrade) {
845 die "Unable to find remote reference: $ref on $origin\n";
846 }
847}
848
849sub traverse_ignore {
850 my ($self, $fh, $path, $r) = @_;
851 $path =~ s#^/+##g;
852 my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
853 my $p = $path;
854 $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
855 print $fh length $p ? "\n# $p\n" : "\n# /\n";
856 if (my $s = $props->{'svn:ignore'}) {
857 $s =~ s/[\r\n]+/\n/g;
858 chomp $s;
859 if (length $p == 0) {
860 $s =~ s#\n#\n/$p#g;
861 print $fh "/$s\n";
862 } else {
863 $s =~ s#\n#\n/$p/#g;
864 print $fh "/$p/$s\n";
865 }
866 }
867 foreach (sort keys %$dirent) {
868 next if $dirent->{$_}->kind != $SVN::Node::dir;
869 $self->traverse_ignore($fh, "$path/$_", $r);
870 }
871}
872
873# returns the newest SVN revision number and newest commit SHA1
874sub last_rev_commit {
875 my ($self) = @_;
876 if (defined $self->{last_rev} && defined $self->{last_commit}) {
877 return ($self->{last_rev}, $self->{last_commit});
878 }
879 my $c = ::verify_ref($self->refname.'^0');
880 if ($c) {
881 my $rev = (::cmt_metadata($c))[1];
882 if (defined $rev) {
883 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
884 return ($rev, $c);
885 }
886 }
887 my $offset = -41; # from tail
888 my $rl;
889 open my $fh, '<', $self->{db_path} or
890 croak "$self->{db_path} not readable: $!\n";
891 seek $fh, $offset, 2;
892 $rl = readline $fh;
893 defined $rl or return (undef, undef);
894 chomp $rl;
895 while ($c ne $rl && tell $fh != 0) {
896 $offset -= 41;
897 seek $fh, $offset, 2;
898 $rl = readline $fh;
899 defined $rl or return (undef, undef);
900 chomp $rl;
901 }
902 my $rev = tell $fh;
903 croak $! if ($rev < 0);
904 $rev = ($rev - 41) / 41;
905 close $fh or croak $!;
906 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
907 return ($rev, $c);
908}
909
910sub parse_revision {
911 my ($self, $base) = @_;
912 my $head = $self->ra->get_latest_revnum;
913 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
914 return ($base + 1, $head) if (defined $base);
915 return (0, $head);
916 }
917 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
918 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
919 if ($::_revision =~ /^BASE:(\d+)$/) {
920 return ($base + 1, $1) if (defined $base);
921 return (0, $head);
922 }
923 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
924 die "revision argument: $::_revision not understood by git-svn\n",
925 "Try using the command-line svn client instead\n";
926}
927
928sub tmp_index_do {
929 my ($self, $sub) = @_;
930 my $old_index = $ENV{GIT_INDEX_FILE};
931 $ENV{GIT_INDEX_FILE} = $self->{index};
932 my @ret = &$sub;
933 if ($old_index) {
934 $ENV{GIT_INDEX_FILE} = $old_index;
935 } else {
936 delete $ENV{GIT_INDEX_FILE};
937 }
938 wantarray ? @ret : $ret[0];
939}
940
941sub assert_index_clean {
942 my ($self, $treeish) = @_;
943
944 $self->tmp_index_do(sub {
945 command_noisy('read-tree', $treeish) unless -e $self->{index};
946 my $x = command_oneline('write-tree');
947 my ($y) = (command(qw/cat-file commit/, $treeish) =~
948 /^tree ($::sha1)/mo);
949 if ($y ne $x) {
950 unlink $self->{index} or croak $!;
951 command_noisy('read-tree', $treeish);
952 }
953 $x = command_oneline('write-tree');
954 if ($y ne $x) {
955 ::fatal "trees ($treeish) $y != $x\n",
956 "Something is seriously wrong...\n";
957 }
958 });
959}
960
961sub get_commit_parents {
962 my ($self, $log_entry, @parents) = @_;
963 my (%seen, @ret, @tmp);
964 # commit parents can be conditionally bound to a particular
965 # svn revision via: "svn_revno=commit_sha1", filter them out here:
966 foreach my $p (@parents) {
967 next unless defined $p;
968 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
969 push @tmp, $2 if $1 == $log_entry->{revision};
970 } else {
971 push @tmp, $p if $p =~ /^$::sha1_short$/o;
972 }
973 }
974 if (my $cur = ::verify_ref($self->refname.'^0')) {
975 push @tmp, $cur;
976 }
977 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
978 while (my $p = shift @tmp) {
979 next if $seen{$p};
980 $seen{$p} = 1;
981 push @ret, $p;
982 # MAXPARENT is defined to 16 in commit-tree.c:
983 last if @ret >= 16;
984 }
985 if (@tmp) {
986 die "r$log_entry->{revision}: No room for parents:\n\t",
987 join("\n\t", @tmp), "\n";
988 }
989 @ret;
990}
991
992sub full_url {
993 my ($self) = @_;
994 $self->ra->{url} . (length $self->{path} ? '/' . $self->{path} : '');
995}
996
997sub do_git_commit {
998 my ($self, $log_entry, @parents) = @_;
999 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1000 croak "$log_entry->{revision} = $c already exists! ",
1001 "Why are we refetching it?\n";
1002 }
1003 my $author = $log_entry->{author};
1004 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1005 : ($author, "$author\@".$self->ra->uuid));
1006 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1007 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1008 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1009
1010 my $tree = $log_entry->{tree};
1011 if (!defined $tree) {
1012 $tree = $self->tmp_index_do(sub {
1013 command_oneline('write-tree') });
1014 }
1015 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1016
1017 my @exec = ('git-commit-tree', $tree);
1018 foreach ($self->get_commit_parents($log_entry, @parents)) {
1019 push @exec, '-p', $_;
1020 }
1021 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1022 or croak $!;
1023 print $msg_fh $log_entry->{log} or croak $!;
1024 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1025 $log_entry->{revision}, ' ',
1026 $self->ra->uuid, "\n" or croak $!;
1027 $msg_fh->flush == 0 or croak $!;
1028 close $msg_fh or croak $!;
1029 chomp(my $commit = do { local $/; <$out_fh> });
1030 close $out_fh or croak $!;
1031 waitpid $pid, 0;
1032 croak $? if $?;
1033 if ($commit !~ /^$::sha1$/o) {
1034 die "Failed to commit, invalid sha1: $commit\n";
1035 }
1036
1037 command_noisy('update-ref',$self->refname, $commit);
1038 $self->rev_db_set($log_entry->{revision}, $commit);
1039
1040 $self->{last_rev} = $log_entry->{revision};
1041 $self->{last_commit} = $commit;
1042 print "r$log_entry->{revision} = $commit\n";
1043 return $commit;
1044}
1045
1046sub revisions_eq {
1047 my ($self, $r0, $r1) = @_;
1048 return 1 if $r0 == $r1;
1049 my $nr = 0;
1050 $self->ra->get_log([$self->{path}], $r0, $r1,
1051 0, 0, 1, sub { $nr++ });
1052 return 0 if ($nr > 1);
1053 return 1;
1054}
1055
1056sub find_parent_branch {
1057 my ($self, $paths, $rev) = @_;
1058
1059 # look for a parent from another branch:
1060 my $i = $paths->{'/'.$self->rel_path} or return;
1061 my $branch_from = $i->copyfrom_path or return;
1062 my $r = $i->copyfrom_rev;
1063 my $repos_root = $self->ra->{repos_root};
1064 my $url = $self->ra->{url};
1065 my $new_url = $repos_root . $branch_from;
1066 print STDERR "Found possible branch point: ",
1067 "$new_url => ", $self->full_url, ", $r\n";
1068 $branch_from =~ s#^/##;
1069 my $remotes = read_all_remotes();
1070 my $gs;
1071 foreach my $repo_id (keys %$remotes) {
1072 my $u = $remotes->{$repo_id}->{url} or next;
1073 next if $url ne $u;
1074 my $fetch = $remotes->{$repo_id}->{fetch};
1075 foreach my $f (keys %$fetch) {
1076 next if $f ne $branch_from;
1077 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1078 last;
1079 }
1080 last if $gs;
1081 }
1082 unless ($gs) {
1083 my $ref_id = $branch_from;
1084 $ref_id .= "\@$r" if find_ref($ref_id);
1085 # just grow a tail if we're not unique enough :x
1086 $ref_id .= '-' while find_ref($ref_id);
1087 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1088 }
1089 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1090 if ($::_follow_parent && (!defined $r0 || !defined $parent)) {
1091 foreach (0 .. $r) {
1092 my $log_entry = eval { $gs->do_fetch(undef, $_) };
1093 $gs->do_git_commit($log_entry) if $log_entry;
1094 }
1095 ($r0, $parent) = $gs->last_rev_commit;
1096 }
1097 if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1098 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1099 $self->assert_index_clean($parent);
1100 my $ed;
1101 if ($self->ra->can_do_switch) {
1102 print STDERR "Following parent with do_switch\n";
1103 # do_switch works with svn/trunk >= r22312, but that
1104 # is not included with SVN 1.4.2 (the latest version
1105 # at the moment), so we can't rely on it
1106 $self->{last_commit} = $parent;
1107 $ed = SVN::Git::Fetcher->new($self);
1108 $gs->ra->gs_do_switch($r0, $rev, $gs->{path}, 1,
1109 $self->full_url, $ed)
1110 or die "SVN connection failed somewhere...\n";
1111 } else {
1112 print STDERR "Following parent with do_update\n";
1113 $ed = SVN::Git::Fetcher->new($self);
1114 $self->ra->gs_do_update($rev, $rev, $self->{path},
1115 1, $ed)
1116 or die "SVN connection failed somewhere...\n";
1117 }
1118 return $self->make_log_entry($rev, [$parent], $ed);
1119 }
1120 print STDERR "Branch parent not found...\n";
1121 return undef;
1122}
1123
1124sub do_fetch {
1125 my ($self, $paths, $rev) = @_;
1126 my $ed;
1127 my ($last_rev, @parents);
1128 if ($self->{last_commit}) {
1129 $ed = SVN::Git::Fetcher->new($self);
1130 $last_rev = $self->{last_rev};
1131 $ed->{c} = $self->{last_commit};
1132 @parents = ($self->{last_commit});
1133 } else {
1134 $last_rev = $rev;
1135 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1136 return $log_entry;
1137 }
1138 $ed = SVN::Git::Fetcher->new($self);
1139 }
1140 unless ($self->ra->gs_do_update($last_rev, $rev,
1141 $self->{path}, 1, $ed)) {
1142 die "SVN connection failed somewhere...\n";
1143 }
1144 $self->make_log_entry($rev, \@parents, $ed);
1145}
1146
1147sub write_untracked {
1148 my ($self, $rev, $fh, $untracked) = @_;
1149 my $h;
1150 print $fh "r$rev\n" or croak $!;
1151 $h = $untracked->{empty};
1152 foreach (sort keys %$h) {
1153 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1154 print $fh " $act: ", uri_encode($_), "\n" or croak $!;
1155 warn "W: $act: $_\n";
1156 }
1157 foreach my $t (qw/dir_prop file_prop/) {
1158 $h = $untracked->{$t} or next;
1159 foreach my $path (sort keys %$h) {
1160 my $ppath = $path eq '' ? '.' : $path;
1161 foreach my $prop (sort keys %{$h->{$path}}) {
1162 next if $SKIP_PROP{$prop};
1163 my $v = $h->{$path}->{$prop};
1164 if (defined $v) {
1165 print $fh " +$t: ",
1166 uri_encode($ppath), ' ',
1167 uri_encode($prop), ' ',
1168 uri_encode($v), "\n"
1169 or croak $!;
1170 } else {
1171 print $fh " -$t: ",
1172 uri_encode($ppath), ' ',
1173 uri_encode($prop), "\n"
1174 or croak $!;
1175 }
1176 }
1177 }
1178 }
1179 foreach my $t (qw/absent_file absent_directory/) {
1180 $h = $untracked->{$t} or next;
1181 foreach my $parent (sort keys %$h) {
1182 foreach my $path (sort @{$h->{$parent}}) {
1183 print $fh " $t: ",
1184 uri_encode("$parent/$path"), "\n"
1185 or croak $!;
1186 warn "W: $t: $parent/$path ",
1187 "Insufficient permissions?\n";
1188 }
1189 }
1190 }
1191}
1192
1193sub parse_svn_date {
1194 my $date = shift || return '+0000 1970-01-01 00:00:00';
1195 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1196 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1197 croak "Unable to parse date: $date\n";
1198 "+0000 $Y-$m-$d $H:$M:$S";
1199}
1200
1201sub check_author {
1202 my ($author) = @_;
1203 if (!defined $author || length $author == 0) {
1204 $author = '(no author)';
1205 }
1206 if (defined $::_authors && ! defined $::users{$author}) {
1207 die "Author: $author not defined in $::_authors file\n";
1208 }
1209 $author;
1210}
1211
1212sub make_log_entry {
1213 my ($self, $rev, $parents, $untracked) = @_;
1214 my $rp = $self->ra->rev_proplist($rev);
1215 my %log_entry = ( parents => $parents || [], revision => $rev,
1216 revprops => $rp, log => '');
1217 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1218 $self->write_untracked($rev, $un, $untracked);
1219 foreach (sort keys %$rp) {
1220 my $v = $rp->{$_};
1221 if (/^svn:(author|date|log)$/) {
1222 $log_entry{$1} = $v;
1223 } else {
1224 print $un " rev_prop: ", uri_encode($_), ' ',
1225 uri_encode($v), "\n";
1226 }
1227 }
1228 close $un or croak $!;
1229 $log_entry{date} = parse_svn_date($log_entry{date});
1230 $log_entry{author} = check_author($log_entry{author});
1231 $log_entry{log} .= "\n";
1232 \%log_entry;
1233}
1234
1235sub fetch {
1236 my ($self, @parents) = @_;
1237 my ($last_rev, $last_commit) = $self->last_rev_commit;
1238 my ($base, $head) = $self->parse_revision($last_rev);
1239 return if ($base > $head);
1240 if (defined $last_commit) {
1241 $self->assert_index_clean($last_commit);
1242 }
1243 my $inc = 1000;
1244 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1245 my $err_handler = $SVN::Error::handler;
1246 $SVN::Error::handler = \&skip_unknown_revs;
1247 while (1) {
1248 my @revs;
1249 $self->ra->get_log([$self->{path}], $min, $max, 0, 1, 1, sub {
1250 my ($paths, $rev, $author, $date, $log) = @_;
1251 push @revs, [ $paths, $rev ] });
1252 foreach (@revs) {
1253 my $log_entry = $self->do_fetch(@$_);
1254 $self->do_git_commit($log_entry, @parents);
1255 }
1256 last if $max >= $head;
1257 $min = $max + 1;
1258 $max += $inc;
1259 $max = $head if ($max > $head);
1260 }
1261 $SVN::Error::handler = $err_handler;
1262}
1263
1264sub set_tree_cb {
1265 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1266 # TODO: enable and test optimized commits:
1267 if (0 && $rev == ($self->{last_rev} + 1)) {
1268 $log_entry->{revision} = $rev;
1269 $log_entry->{author} = $author;
1270 $self->do_git_commit($log_entry, "$rev=$tree");
1271 } else {
1272 $self->fetch("$rev=$tree");
1273 }
1274}
1275
1276sub set_tree {
1277 my ($self, $tree) = (shift, shift);
1278 my $log_entry = ::get_commit_entry($tree);
1279 unless ($self->{last_rev}) {
1280 fatal("Must have an existing revision to commit\n");
1281 }
1282 my $pool = SVN::Pool->new;
1283 my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1284 ra => $self->ra->dup,
1285 svn_path => $self->ra->{svn_path}
1286 },
1287 $self->ra->get_commit_editor(
1288 $log_entry->{log}, sub {
1289 $self->set_tree_cb($log_entry,
1290 $tree, @_);
1291 }),
1292 $pool);
1293 my $mods = $ed->apply_diff($self->{last_commit}, $tree);
1294 if (@$mods == 0) {
1295 print "No changes\nr$self->{last_rev} = $tree\n";
1296 }
1297 $pool->clear;
1298}
1299
1300sub skip_unknown_revs {
1301 my ($err) = @_;
1302 my $errno = $err->apr_err();
1303 # Maybe the branch we're tracking didn't
1304 # exist when the repo started, so it's
1305 # not an error if it doesn't, just continue
1306 #
1307 # Wonderfully consistent library, eh?
1308 # 160013 - svn:// and file://
1309 # 175002 - http(s)://
1310 # 175007 - http(s):// (this repo required authorization, too...)
1311 # More codes may be discovered later...
1312 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1313 return;
1314 }
1315 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1316}
1317
1318# rev_db:
1319# Tie::File seems to be prone to offset errors if revisions get sparse,
1320# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1321# one of my favorite modules is out :< Next up would be one of the DBM
1322# modules, but I'm not sure which is most portable... So I'll just
1323# go with something that's plain-text, but still capable of
1324# being randomly accessed. So here's my ultra-simple fixed-width
1325# database. All records are 40 characters + "\n", so it's easy to seek
1326# to a revision: (41 * rev) is the byte offset.
1327# A record of 40 0s denotes an empty revision.
1328# And yes, it's still pretty fast (faster than Tie::File).
1329
1330sub rev_db_set {
1331 my ($self, $rev, $commit) = @_;
1332 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1333 open my $fh, '+<', $self->{db_path} or croak $!;
1334 my $offset = $rev * 41;
1335 # assume that append is the common case:
1336 seek $fh, 0, 2 or croak $!;
1337 my $pos = tell $fh;
1338 if ($pos < $offset) {
1339 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1340 or croak $!;
1341 }
1342 seek $fh, $offset, 0 or croak $!;
1343 print $fh $commit,"\n" or croak $!;
1344 close $fh or croak $!;
1345}
1346
1347sub rev_db_get {
1348 my ($self, $rev) = @_;
1349 my $ret;
1350 my $offset = $rev * 41;
1351 open my $fh, '<', $self->{db_path} or croak $!;
1352 if (seek $fh, $offset, 0) {
1353 $ret = readline $fh;
1354 if (defined $ret) {
1355 chomp $ret;
1356 $ret = undef if ($ret =~ /^0{40}$/);
1357 }
1358 }
1359 close $fh or croak $!;
1360 $ret;
1361}
1362
1363sub find_rev_before {
1364 my ($self, $rev, $eq_ok) = @_;
1365 --$rev unless $eq_ok;
1366 while ($rev > 0) {
1367 if (my $c = $self->rev_db_get($rev)) {
1368 return ($rev, $c);
1369 }
1370 --$rev;
1371 }
1372 return (undef, undef);
1373}
1374
1375sub _new {
1376 my ($class, $repo_id, $ref_id, $path) = @_;
1377 unless (defined $repo_id && length $repo_id) {
1378 $repo_id = $Git::SVN::default_repo_id;
1379 }
1380 unless (defined $ref_id && length $ref_id) {
1381 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1382 }
1383 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1384 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1385 $_[3] = $path = '' unless (defined $path);
1386 mkpath([$dir]);
1387 unless (-f "$dir/.rev_db") {
1388 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1389 close $fh or croak $!;
1390 }
1391 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1392 path => $path,
1393 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1394}
1395
1396sub uri_encode {
1397 my ($f) = @_;
1398 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1399 $f
1400}
1401
1402package Git::SVN::Prompt;
1403use strict;
1404use warnings;
1405require SVN::Core;
1406use vars qw/$_no_auth_cache $_username/;
1407
1408sub simple {
1409 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1410 $may_save = undef if $_no_auth_cache;
1411 $default_username = $_username if defined $_username;
1412 if (defined $default_username && length $default_username) {
1413 if (defined $realm && length $realm) {
1414 print STDERR "Authentication realm: $realm\n";
1415 STDERR->flush;
1416 }
1417 $cred->username($default_username);
1418 } else {
1419 username($cred, $realm, $may_save, $pool);
1420 }
1421 $cred->password(_read_password("Password for '" .
1422 $cred->username . "': ", $realm));
1423 $cred->may_save($may_save);
1424 $SVN::_Core::SVN_NO_ERROR;
1425}
1426
1427sub ssl_server_trust {
1428 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1429 $may_save = undef if $_no_auth_cache;
1430 print STDERR "Error validating server certificate for '$realm':\n";
1431 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1432 print STDERR " - The certificate is not issued by a trusted ",
1433 "authority. Use the\n",
1434 " fingerprint to validate the certificate manually!\n";
1435 }
1436 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1437 print STDERR " - The certificate hostname does not match.\n";
1438 }
1439 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1440 print STDERR " - The certificate is not yet valid.\n";
1441 }
1442 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1443 print STDERR " - The certificate has expired.\n";
1444 }
1445 if ($failures & $SVN::Auth::SSL::OTHER) {
1446 print STDERR " - The certificate has an unknown error.\n";
1447 }
1448 printf STDERR
1449 "Certificate information:\n".
1450 " - Hostname: %s\n".
1451 " - Valid: from %s until %s\n".
1452 " - Issuer: %s\n".
1453 " - Fingerprint: %s\n",
1454 map $cert_info->$_, qw(hostname valid_from valid_until
1455 issuer_dname fingerprint);
1456 my $choice;
1457prompt:
1458 print STDERR $may_save ?
1459 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1460 "(R)eject or accept (t)emporarily? ";
1461 STDERR->flush;
1462 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1463 if ($choice =~ /^t$/i) {
1464 $cred->may_save(undef);
1465 } elsif ($choice =~ /^r$/i) {
1466 return -1;
1467 } elsif ($may_save && $choice =~ /^p$/i) {
1468 $cred->may_save($may_save);
1469 } else {
1470 goto prompt;
1471 }
1472 $cred->accepted_failures($failures);
1473 $SVN::_Core::SVN_NO_ERROR;
1474}
1475
1476sub ssl_client_cert {
1477 my ($cred, $realm, $may_save, $pool) = @_;
1478 $may_save = undef if $_no_auth_cache;
1479 print STDERR "Client certificate filename: ";
1480 STDERR->flush;
1481 chomp(my $filename = <STDIN>);
1482 $cred->cert_file($filename);
1483 $cred->may_save($may_save);
1484 $SVN::_Core::SVN_NO_ERROR;
1485}
1486
1487sub ssl_client_cert_pw {
1488 my ($cred, $realm, $may_save, $pool) = @_;
1489 $may_save = undef if $_no_auth_cache;
1490 $cred->password(_read_password("Password: ", $realm));
1491 $cred->may_save($may_save);
1492 $SVN::_Core::SVN_NO_ERROR;
1493}
1494
1495sub username {
1496 my ($cred, $realm, $may_save, $pool) = @_;
1497 $may_save = undef if $_no_auth_cache;
1498 if (defined $realm && length $realm) {
1499 print STDERR "Authentication realm: $realm\n";
1500 }
1501 my $username;
1502 if (defined $_username) {
1503 $username = $_username;
1504 } else {
1505 print STDERR "Username: ";
1506 STDERR->flush;
1507 chomp($username = <STDIN>);
1508 }
1509 $cred->username($username);
1510 $cred->may_save($may_save);
1511 $SVN::_Core::SVN_NO_ERROR;
1512}
1513
1514sub _read_password {
1515 my ($prompt, $realm) = @_;
1516 print STDERR $prompt;
1517 STDERR->flush;
1518 require Term::ReadKey;
1519 Term::ReadKey::ReadMode('noecho');
1520 my $password = '';
1521 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1522 last if $key =~ /[\012\015]/; # \n\r
1523 $password .= $key;
1524 }
1525 Term::ReadKey::ReadMode('restore');
1526 print STDERR "\n";
1527 STDERR->flush;
1528 $password;
1529}
1530
1531package main;
1532
1533sub uri_encode {
1534 my ($f) = @_;
1535 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1536 $f
1537}
1538
1539sub uri_decode {
1540 my ($f) = @_;
1541 $f =~ tr/+/ /;
1542 $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1543 $f
1544}
1545
1546{
1547 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1548 $SVN::Node::dir.$SVN::Node::unknown.
1549 $SVN::Node::none.$SVN::Node::file.
1550 $SVN::Node::dir.$SVN::Node::unknown.
1551 $SVN::Auth::SSL::CNMISMATCH.
1552 $SVN::Auth::SSL::NOTYETVALID.
1553 $SVN::Auth::SSL::EXPIRED.
1554 $SVN::Auth::SSL::UNKNOWNCA.
1555 $SVN::Auth::SSL::OTHER;
1556}
1557
1558package SVN::Git::Fetcher;
1559use vars qw/@ISA/;
1560use strict;
1561use warnings;
1562use Carp qw/croak/;
1563use IO::File qw//;
1564
1565# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1566sub new {
1567 my ($class, $git_svn) = @_;
1568 my $self = SVN::Delta::Editor->new;
1569 bless $self, $class;
1570 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1571 $self->{empty} = {};
1572 $self->{dir_prop} = {};
1573 $self->{file_prop} = {};
1574 $self->{absent_dir} = {};
1575 $self->{absent_file} = {};
1576 ($self->{gui}, $self->{ctx}) = $git_svn->tmp_index_do(
1577 sub { command_input_pipe(qw/update-index -z --index-info/) } );
1578 require Digest::MD5;
1579 $self;
1580}
1581
1582sub set_path_strip {
1583 my ($self, $path) = @_;
1584 $self->{path_strip} = qr/^\Q$path\E\/?/;
1585}
1586
1587sub open_root {
1588 { path => '' };
1589}
1590
1591sub open_directory {
1592 my ($self, $path, $pb, $rev) = @_;
1593 { path => $path };
1594}
1595
1596sub git_path {
1597 my ($self, $path) = @_;
1598 $path =~ s!$self->{path_strip}!! if $self->{path_strip};
1599 $path;
1600}
1601
1602sub delete_entry {
1603 my ($self, $path, $rev, $pb) = @_;
1604 my $gui = $self->{gui};
1605
1606 my $gpath = $self->git_path($path);
1607 # remove entire directories.
1608 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1609 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1610 -r --name-only -z/,
1611 $self->{c}, '--', $gpath);
1612 local $/ = "\0";
1613 while (<$ls>) {
1614 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
1615 print "\tD\t$_\n" unless $self->{q};
1616 }
1617 print "\tD\t$gpath/\n" unless $self->{q};
1618 command_close_pipe($ls, $ctx);
1619 $self->{empty}->{$path} = 0
1620 } else {
1621 print $gui '0 ',0 x 40,"\t",$gpath,"\0" or croak $!;
1622 print "\tD\t$gpath\n" unless $self->{q};
1623 }
1624 undef;
1625}
1626
1627sub open_file {
1628 my ($self, $path, $pb, $rev) = @_;
1629 my $gpath = $self->git_path($path);
1630 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1631 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1632 unless (defined $mode && defined $blob) {
1633 die "$path was not found in commit $self->{c} (r$rev)\n";
1634 }
1635 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1636 pool => SVN::Pool->new, action => 'M' };
1637}
1638
1639sub add_file {
1640 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1641 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1642 delete $self->{empty}->{$dir};
1643 { path => $path, mode_a => 100644, mode_b => 100644,
1644 pool => SVN::Pool->new, action => 'A' };
1645}
1646
1647sub add_directory {
1648 my ($self, $path, $cp_path, $cp_rev) = @_;
1649 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1650 delete $self->{empty}->{$dir};
1651 $self->{empty}->{$path} = 1;
1652 { path => $path };
1653}
1654
1655sub change_dir_prop {
1656 my ($self, $db, $prop, $value) = @_;
1657 $self->{dir_prop}->{$db->{path}} ||= {};
1658 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1659 undef;
1660}
1661
1662sub absent_directory {
1663 my ($self, $path, $pb) = @_;
1664 $self->{absent_dir}->{$pb->{path}} ||= [];
1665 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1666 undef;
1667}
1668
1669sub absent_file {
1670 my ($self, $path, $pb) = @_;
1671 $self->{absent_file}->{$pb->{path}} ||= [];
1672 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1673 undef;
1674}
1675
1676sub change_file_prop {
1677 my ($self, $fb, $prop, $value) = @_;
1678 if ($prop eq 'svn:executable') {
1679 if ($fb->{mode_b} != 120000) {
1680 $fb->{mode_b} = defined $value ? 100755 : 100644;
1681 }
1682 } elsif ($prop eq 'svn:special') {
1683 $fb->{mode_b} = defined $value ? 120000 : 100644;
1684 } else {
1685 $self->{file_prop}->{$fb->{path}} ||= {};
1686 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1687 }
1688 undef;
1689}
1690
1691sub apply_textdelta {
1692 my ($self, $fb, $exp) = @_;
1693 my $fh = IO::File->new_tmpfile;
1694 $fh->autoflush(1);
1695 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1696 # (but $base does not,) so dup() it for reading in close_file
1697 open my $dup, '<&', $fh or croak $!;
1698 my $base = IO::File->new_tmpfile;
1699 $base->autoflush(1);
1700 if ($fb->{blob}) {
1701 defined (my $pid = fork) or croak $!;
1702 if (!$pid) {
1703 open STDOUT, '>&', $base or croak $!;
1704 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1705 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1706 }
1707 waitpid $pid, 0;
1708 croak $? if $?;
1709
1710 if (defined $exp) {
1711 seek $base, 0, 0 or croak $!;
1712 my $md5 = Digest::MD5->new;
1713 $md5->addfile($base);
1714 my $got = $md5->hexdigest;
1715 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1716 "expected: $exp\n",
1717 " got: $got\n" if ($got ne $exp);
1718 }
1719 }
1720 seek $base, 0, 0 or croak $!;
1721 $fb->{fh} = $dup;
1722 $fb->{base} = $base;
1723 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1724}
1725
1726sub close_file {
1727 my ($self, $fb, $exp) = @_;
1728 my $hash;
1729 my $path = $self->git_path($fb->{path});
1730 if (my $fh = $fb->{fh}) {
1731 seek($fh, 0, 0) or croak $!;
1732 my $md5 = Digest::MD5->new;
1733 $md5->addfile($fh);
1734 my $got = $md5->hexdigest;
1735 die "Checksum mismatch: $path\n",
1736 "expected: $exp\n got: $got\n" if ($got ne $exp);
1737 seek($fh, 0, 0) or croak $!;
1738 if ($fb->{mode_b} == 120000) {
1739 read($fh, my $buf, 5) == 5 or croak $!;
1740 $buf eq 'link ' or die "$path has mode 120000",
1741 "but is not a link\n";
1742 }
1743 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1744 if (!$pid) {
1745 open STDIN, '<&', $fh or croak $!;
1746 exec qw/git-hash-object -w --stdin/ or croak $!;
1747 }
1748 chomp($hash = do { local $/; <$out> });
1749 close $out or croak $!;
1750 close $fh or croak $!;
1751 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1752 close $fb->{base} or croak $!;
1753 } else {
1754 $hash = $fb->{blob} or die "no blob information\n";
1755 }
1756 $fb->{pool}->clear;
1757 my $gui = $self->{gui};
1758 print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
1759 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1760 undef;
1761}
1762
1763sub abort_edit {
1764 my $self = shift;
1765 eval { command_close_pipe($self->{gui}, $self->{ctx}) };
1766 $self->SUPER::abort_edit(@_);
1767}
1768
1769sub close_edit {
1770 my $self = shift;
1771 command_close_pipe($self->{gui}, $self->{ctx});
1772 $self->{git_commit_ok} = 1;
1773 $self->SUPER::close_edit(@_);
1774}
1775
1776package SVN::Git::Editor;
1777use vars qw/@ISA/;
1778use strict;
1779use warnings;
1780use Carp qw/croak/;
1781use IO::File;
1782
1783sub new {
1784 my $class = shift;
1785 my $git_svn = shift;
1786 my $self = SVN::Delta::Editor->new(@_);
1787 bless $self, $class;
1788 foreach (qw/svn_path r ra/) {
1789 die "$_ required!\n" unless (defined $git_svn->{$_});
1790 $self->{$_} = $git_svn->{$_};
1791 }
1792 $self->{pool} = SVN::Pool->new;
1793 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1794 $self->{rm} = { };
1795 require Digest::MD5;
1796 return $self;
1797}
1798
1799sub split_path {
1800 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1801}
1802
1803sub repo_path {
1804 (defined $_[1] && length $_[1]) ? $_[1] : ''
1805}
1806
1807sub url_path {
1808 my ($self, $path) = @_;
1809 $self->{ra}->{url} . '/' . $self->repo_path($path);
1810}
1811
1812sub rmdirs {
1813 my ($self, $tree_b) = @_;
1814 my $rm = $self->{rm};
1815 delete $rm->{''}; # we never delete the url we're tracking
1816 return unless %$rm;
1817
1818 foreach (keys %$rm) {
1819 my @d = split m#/#, $_;
1820 my $c = shift @d;
1821 $rm->{$c} = 1;
1822 while (@d) {
1823 $c .= '/' . shift @d;
1824 $rm->{$c} = 1;
1825 }
1826 }
1827 delete $rm->{$self->{svn_path}};
1828 delete $rm->{''}; # we never delete the url we're tracking
1829 return unless %$rm;
1830
1831 my ($fh, $ctx) = command_output_pipe(
1832 qw/ls-tree --name-only -r -z/, $tree_b);
1833 local $/ = "\0";
1834 while (<$fh>) {
1835 chomp;
1836 my @dn = split m#/#, $_;
1837 while (pop @dn) {
1838 delete $rm->{join '/', @dn};
1839 }
1840 unless (%$rm) {
1841 close $fh;
1842 return;
1843 }
1844 }
1845 command_close_pipe($fh, $ctx);
1846
1847 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1848 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1849 $self->close_directory($bat->{$d}, $p);
1850 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
1851 print "\tD+\t$d/\n" unless $::_q;
1852 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1853 delete $bat->{$d};
1854 }
1855}
1856
1857sub open_or_add_dir {
1858 my ($self, $full_path, $baton) = @_;
1859 my $t = $self->{ra}->check_path($full_path, $self->{r});
1860 if ($t == $SVN::Node::none) {
1861 return $self->add_directory($full_path, $baton,
1862 undef, -1, $self->{pool});
1863 } elsif ($t == $SVN::Node::dir) {
1864 return $self->open_directory($full_path, $baton,
1865 $self->{r}, $self->{pool});
1866 }
1867 print STDERR "$full_path already exists in repository at ",
1868 "r$self->{r} and it is not a directory (",
1869 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1870 exit 1;
1871}
1872
1873sub ensure_path {
1874 my ($self, $path) = @_;
1875 my $bat = $self->{bat};
1876 $path = $self->repo_path($path);
1877 return $bat->{''} unless (length $path);
1878 my @p = split m#/+#, $path;
1879 my $c = shift @p;
1880 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
1881 while (@p) {
1882 my $c0 = $c;
1883 $c .= '/' . shift @p;
1884 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
1885 }
1886 return $bat->{$c};
1887}
1888
1889sub A {
1890 my ($self, $m) = @_;
1891 my ($dir, $file) = split_path($m->{file_b});
1892 my $pbat = $self->ensure_path($dir);
1893 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1894 undef, -1);
1895 print "\tA\t$m->{file_b}\n" unless $::_q;
1896 $self->chg_file($fbat, $m);
1897 $self->close_file($fbat,undef,$self->{pool});
1898}
1899
1900sub C {
1901 my ($self, $m) = @_;
1902 my ($dir, $file) = split_path($m->{file_b});
1903 my $pbat = $self->ensure_path($dir);
1904 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1905 $self->url_path($m->{file_a}), $self->{r});
1906 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1907 $self->chg_file($fbat, $m);
1908 $self->close_file($fbat,undef,$self->{pool});
1909}
1910
1911sub delete_entry {
1912 my ($self, $path, $pbat) = @_;
1913 my $rpath = $self->repo_path($path);
1914 my ($dir, $file) = split_path($rpath);
1915 $self->{rm}->{$dir} = 1;
1916 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
1917}
1918
1919sub R {
1920 my ($self, $m) = @_;
1921 my ($dir, $file) = split_path($m->{file_b});
1922 my $pbat = $self->ensure_path($dir);
1923 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1924 $self->url_path($m->{file_a}), $self->{r});
1925 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1926 $self->chg_file($fbat, $m);
1927 $self->close_file($fbat,undef,$self->{pool});
1928
1929 ($dir, $file) = split_path($m->{file_a});
1930 $pbat = $self->ensure_path($dir);
1931 $self->delete_entry($m->{file_a}, $pbat);
1932}
1933
1934sub M {
1935 my ($self, $m) = @_;
1936 my ($dir, $file) = split_path($m->{file_b});
1937 my $pbat = $self->ensure_path($dir);
1938 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
1939 $pbat,$self->{r},$self->{pool});
1940 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
1941 $self->chg_file($fbat, $m);
1942 $self->close_file($fbat,undef,$self->{pool});
1943}
1944
1945sub T { shift->M(@_) }
1946
1947sub change_file_prop {
1948 my ($self, $fbat, $pname, $pval) = @_;
1949 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
1950}
1951
1952sub chg_file {
1953 my ($self, $fbat, $m) = @_;
1954 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
1955 $self->change_file_prop($fbat,'svn:executable','*');
1956 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1957 $self->change_file_prop($fbat,'svn:executable',undef);
1958 }
1959 my $fh = IO::File->new_tmpfile or croak $!;
1960 if ($m->{mode_b} =~ /^120/) {
1961 print $fh 'link ' or croak $!;
1962 $self->change_file_prop($fbat,'svn:special','*');
1963 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1964 $self->change_file_prop($fbat,'svn:special',undef);
1965 }
1966 defined(my $pid = fork) or croak $!;
1967 if (!$pid) {
1968 open STDOUT, '>&', $fh or croak $!;
1969 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
1970 }
1971 waitpid $pid, 0;
1972 croak $? if $?;
1973 $fh->flush == 0 or croak $!;
1974 seek $fh, 0, 0 or croak $!;
1975
1976 my $md5 = Digest::MD5->new;
1977 $md5->addfile($fh) or croak $!;
1978 seek $fh, 0, 0 or croak $!;
1979
1980 my $exp = $md5->hexdigest;
1981 my $pool = SVN::Pool->new;
1982 my $atd = $self->apply_textdelta($fbat, undef, $pool);
1983 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
1984 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
1985 $pool->clear;
1986
1987 close $fh or croak $!;
1988}
1989
1990sub D {
1991 my ($self, $m) = @_;
1992 my ($dir, $file) = split_path($m->{file_b});
1993 my $pbat = $self->ensure_path($dir);
1994 print "\tD\t$m->{file_b}\n" unless $::_q;
1995 $self->delete_entry($m->{file_b}, $pbat);
1996}
1997
1998sub close_edit {
1999 my ($self) = @_;
2000 my ($p,$bat) = ($self->{pool}, $self->{bat});
2001 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2002 $self->close_directory($bat->{$_}, $p);
2003 }
2004 $self->SUPER::close_edit($p);
2005 $p->clear;
2006}
2007
2008sub abort_edit {
2009 my ($self) = @_;
2010 $self->SUPER::abort_edit($self->{pool});
2011 $self->{pool}->clear;
2012}
2013
2014# this drives the editor
2015sub apply_diff {
2016 my ($self, $tree_a, $tree_b) = @_;
2017 my @diff_tree = qw(diff-tree -z -r);
2018 if ($::_cp_similarity) {
2019 push @diff_tree, "-C$::_cp_similarity";
2020 } else {
2021 push @diff_tree, '-C';
2022 }
2023 push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
2024 push @diff_tree, "-l$::_l" if defined $::_l;
2025 push @diff_tree, $tree_a, $tree_b;
2026 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2027 my $nl = $/;
2028 local $/ = "\0";
2029 my $state = 'meta';
2030 my @mods;
2031 while (<$diff_fh>) {
2032 chomp $_; # this gets rid of the trailing "\0"
2033 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2034 $::sha1\s($::sha1)\s
2035 ([MTCRAD])\d*$/xo) {
2036 push @mods, { mode_a => $1, mode_b => $2,
2037 sha1_b => $3, chg => $4 };
2038 if ($4 =~ /^(?:C|R)$/) {
2039 $state = 'file_a';
2040 } else {
2041 $state = 'file_b';
2042 }
2043 } elsif ($state eq 'file_a') {
2044 my $x = $mods[$#mods] or croak "Empty array\n";
2045 if ($x->{chg} !~ /^(?:C|R)$/) {
2046 croak "Error parsing $_, $x->{chg}\n";
2047 }
2048 $x->{file_a} = $_;
2049 $state = 'file_b';
2050 } elsif ($state eq 'file_b') {
2051 my $x = $mods[$#mods] or croak "Empty array\n";
2052 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2053 croak "Error parsing $_, $x->{chg}\n";
2054 }
2055 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2056 croak "Error parsing $_, $x->{chg}\n";
2057 }
2058 $x->{file_b} = $_;
2059 $state = 'meta';
2060 } else {
2061 croak "Error parsing $_\n";
2062 }
2063 }
2064 command_close_pipe($diff_fh, $ctx);
2065 $/ = $nl;
2066
2067 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2068 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @mods) {
2069 my $f = $m->{chg};
2070 if (defined $o{$f}) {
2071 $self->$f($m);
2072 } else {
2073 fatal("Invalid change type: $f\n");
2074 }
2075 }
2076 $self->rmdirs($tree_b) if $::_rmdir;
2077 if (@mods == 0) {
2078 $self->abort_edit;
2079 } else {
2080 $self->close_edit;
2081 }
2082 \@mods;
2083}
2084
2085package Git::SVN::Ra;
2086use vars qw/@ISA $config_dir/;
2087use strict;
2088use warnings;
2089my ($can_do_switch);
2090my %RA;
2091
2092BEGIN {
2093 # enforce temporary pool usage for some simple functions
2094 my $e;
2095 foreach (qw/get_latest_revnum rev_proplist get_file
2096 check_path get_dir get_uuid get_repos_root/) {
2097 $e .= "sub $_ {
2098 my \$self = shift;
2099 my \$pool = SVN::Pool->new;
2100 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2101 \$pool->clear;
2102 wantarray ? \@ret : \$ret[0]; }\n";
2103 }
2104 eval $e;
2105}
2106
2107sub new {
2108 my ($class, $url) = @_;
2109 $url =~ s!/+$!!;
2110 return $RA{$url} if $RA{$url};
2111
2112 SVN::_Core::svn_config_ensure($config_dir, undef);
2113 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2114 SVN::Client::get_simple_provider(),
2115 SVN::Client::get_ssl_server_trust_file_provider(),
2116 SVN::Client::get_simple_prompt_provider(
2117 \&Git::SVN::Prompt::simple, 2),
2118 SVN::Client::get_ssl_client_cert_prompt_provider(
2119 \&Git::SVN::Prompt::ssl_client_cert, 2),
2120 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2121 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2122 SVN::Client::get_username_provider(),
2123 SVN::Client::get_ssl_server_trust_prompt_provider(
2124 \&Git::SVN::Prompt::ssl_server_trust),
2125 SVN::Client::get_username_prompt_provider(
2126 \&Git::SVN::Prompt::username, 2),
2127 ]);
2128 my $config = SVN::Core::config_get_config($config_dir);
2129 my $self = SVN::Ra->new(url => $url, auth => $baton,
2130 config => $config,
2131 pool => SVN::Pool->new,
2132 auth_provider_callbacks => $callbacks);
2133 $self->{svn_path} = $url;
2134 $self->{repos_root} = $self->get_repos_root;
2135 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2136 $RA{$url} = bless $self, $class;
2137}
2138
2139sub DESTROY {
2140 # do not call the real DESTROY since we store ourselves in %RA
2141}
2142
2143sub dup {
2144 my ($self) = @_;
2145 my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2146 map { $_ => $self->{$_} } qw/config url
2147 auth auth_provider_callbacks repos_root svn_path/);
2148 bless $dup, ref $self;
2149}
2150
2151sub get_log {
2152 my ($self, @args) = @_;
2153 my $pool = SVN::Pool->new;
2154 $args[4]-- if $args[4] && ! $::_follow_parent;
2155 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2156 my $ret = $self->SUPER::get_log(@args, $pool);
2157 $pool->clear;
2158 $ret;
2159}
2160
2161sub get_commit_editor {
2162 my ($self, $log, $cb, $pool) = @_;
2163 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2164 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2165}
2166
2167sub uuid {
2168 my ($self) = @_;
2169 $self->{uuid} ||= $self->get_uuid;
2170}
2171
2172sub gs_do_update {
2173 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2174 my $pool = SVN::Pool->new;
2175 $editor->set_path_strip($path);
2176 my $reporter = $self->do_update($rev_b, $path, $recurse,
2177 $editor, $pool);
2178 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2179 my $new = ($rev_a == $rev_b);
2180 $reporter->set_path('', $rev_a, $new, @lock, $pool);
2181 $reporter->finish_report($pool);
2182 $pool->clear;
2183 $editor->{git_commit_ok};
2184}
2185
2186sub gs_do_switch {
2187 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2188 my $pool = SVN::Pool->new;
2189 $editor->set_path_strip($path);
2190 my $reporter = $self->do_switch($rev_b, $path, $recurse,
2191 $url_b, $editor, $pool);
2192 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2193 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2194 $reporter->finish_report($pool);
2195 $pool->clear;
2196 $editor->{git_commit_ok};
2197}
2198
2199sub can_do_switch {
2200 my $self = shift;
2201 unless (defined $can_do_switch) {
2202 my $pool = SVN::Pool->new;
2203 my $rep = eval {
2204 $self->do_switch(1, '', 0, $self->{url},
2205 SVN::Delta::Editor->new, $pool);
2206 };
2207 if ($@) {
2208 $can_do_switch = 0;
2209 } else {
2210 $rep->abort_report($pool);
2211 $can_do_switch = 1;
2212 }
2213 $pool->clear;
2214 }
2215 $can_do_switch;
2216}
2217
2218package Git::SVN::Log;
2219use strict;
2220use warnings;
2221use POSIX qw/strftime/;
2222use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2223 %rusers $show_commit $incremental/;
2224my $l_fmt;
2225
2226sub cmt_showable {
2227 my ($c) = @_;
2228 return 1 if defined $c->{r};
2229 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2230 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2231 my @log = command(qw/cat-file commit/, $c->{c});
2232 shift @log while ($log[0] ne "\n");
2233 shift @log;
2234 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2235
2236 (undef, $c->{r}, undef) = ::extract_metadata(
2237 (grep(/^git-svn-id: /, @log))[-1]);
2238 }
2239 return defined $c->{r};
2240}
2241
2242sub log_use_color {
2243 return 1 if $color;
2244 my ($dc, $dcvar);
2245 $dcvar = 'color.diff';
2246 $dc = `git-config --get $dcvar`;
2247 if ($dc eq '') {
2248 # nothing at all; fallback to "diff.color"
2249 $dcvar = 'diff.color';
2250 $dc = `git-config --get $dcvar`;
2251 }
2252 chomp($dc);
2253 if ($dc eq 'auto') {
2254 my $pc;
2255 $pc = `git-config --get color.pager`;
2256 if ($pc eq '') {
2257 # does not have it -- fallback to pager.color
2258 $pc = `git-config --bool --get pager.color`;
2259 }
2260 else {
2261 $pc = `git-config --bool --get color.pager`;
2262 if ($?) {
2263 $pc = 'false';
2264 }
2265 }
2266 chomp($pc);
2267 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2268 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2269 }
2270 return 0;
2271 }
2272 return 0 if $dc eq 'never';
2273 return 1 if $dc eq 'always';
2274 chomp($dc = `git-config --bool --get $dcvar`);
2275 return ($dc eq 'true');
2276}
2277
2278sub git_svn_log_cmd {
2279 my ($r_min, $r_max) = @_;
2280 my $gs = Git::SVN->_new;
2281 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2282 $gs->refname);
2283 push @cmd, '-r' unless $non_recursive;
2284 push @cmd, qw/--raw --name-status/ if $verbose;
2285 push @cmd, '--color' if log_use_color();
2286 return @cmd unless defined $r_max;
2287 if ($r_max == $r_min) {
2288 push @cmd, '--max-count=1';
2289 if (my $c = $gs->rev_db_get($r_max)) {
2290 push @cmd, $c;
2291 }
2292 } else {
2293 my ($c_min, $c_max);
2294 $c_max = $gs->rev_db_get($r_max);
2295 $c_min = $gs->rev_db_get($r_min);
2296 if (defined $c_min && defined $c_max) {
2297 if ($r_max > $r_max) {
2298 push @cmd, "$c_min..$c_max";
2299 } else {
2300 push @cmd, "$c_max..$c_min";
2301 }
2302 } elsif ($r_max > $r_min) {
2303 push @cmd, $c_max;
2304 } else {
2305 push @cmd, $c_min;
2306 }
2307 }
2308 return @cmd;
2309}
2310
2311# adapted from pager.c
2312sub config_pager {
2313 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2314 if (!defined $pager) {
2315 $pager = 'less';
2316 } elsif (length $pager == 0 || $pager eq 'cat') {
2317 $pager = undef;
2318 }
2319}
2320
2321sub run_pager {
2322 return unless -t *STDOUT;
2323 pipe my $rfd, my $wfd or return;
2324 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2325 if (!$pid) {
2326 open STDOUT, '>&', $wfd or
2327 ::fatal "Can't redirect to stdout: $!\n";
2328 return;
2329 }
2330 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2331 $ENV{LESS} ||= 'FRSX';
2332 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2333}
2334
2335sub get_author_info {
2336 my ($dest, $author, $t, $tz) = @_;
2337 $author =~ s/(?:^\s*|\s*$)//g;
2338 $dest->{a_raw} = $author;
2339 my $au;
2340 if ($::_authors) {
2341 $au = $rusers{$author} || undef;
2342 }
2343 if (!$au) {
2344 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2345 }
2346 $dest->{t} = $t;
2347 $dest->{tz} = $tz;
2348 $dest->{a} = $au;
2349 # Date::Parse isn't in the standard Perl distro :(
2350 if ($tz =~ s/^\+//) {
2351 $t += ::tz_to_s_offset($tz);
2352 } elsif ($tz =~ s/^\-//) {
2353 $t -= ::tz_to_s_offset($tz);
2354 }
2355 $dest->{t_utc} = $t;
2356}
2357
2358sub process_commit {
2359 my ($c, $r_min, $r_max, $defer) = @_;
2360 if (defined $r_min && defined $r_max) {
2361 if ($r_min == $c->{r} && $r_min == $r_max) {
2362 show_commit($c);
2363 return 0;
2364 }
2365 return 1 if $r_min == $r_max;
2366 if ($r_min < $r_max) {
2367 # we need to reverse the print order
2368 return 0 if (defined $limit && --$limit < 0);
2369 push @$defer, $c;
2370 return 1;
2371 }
2372 if ($r_min != $r_max) {
2373 return 1 if ($r_min < $c->{r});
2374 return 1 if ($r_max > $c->{r});
2375 }
2376 }
2377 return 0 if (defined $limit && --$limit < 0);
2378 show_commit($c);
2379 return 1;
2380}
2381
2382sub show_commit {
2383 my $c = shift;
2384 if ($oneline) {
2385 my $x = "\n";
2386 if (my $l = $c->{l}) {
2387 while ($l->[0] =~ /^\s*$/) { shift @$l }
2388 $x = $l->[0];
2389 }
2390 $l_fmt ||= 'A' . length($c->{r});
2391 print 'r',pack($l_fmt, $c->{r}),' | ';
2392 print "$c->{c} | " if $show_commit;
2393 print $x;
2394 } else {
2395 show_commit_normal($c);
2396 }
2397}
2398
2399sub show_commit_changed_paths {
2400 my ($c) = @_;
2401 return unless $c->{changed};
2402 print "Changed paths:\n", @{$c->{changed}};
2403}
2404
2405sub show_commit_normal {
2406 my ($c) = @_;
2407 print '-' x72, "\nr$c->{r} | ";
2408 print "$c->{c} | " if $show_commit;
2409 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2410 localtime($c->{t_utc})), ' | ';
2411 my $nr_line = 0;
2412
2413 if (my $l = $c->{l}) {
2414 while ($l->[$#$l] eq "\n" && $#$l > 0
2415 && $l->[($#$l - 1)] eq "\n") {
2416 pop @$l;
2417 }
2418 $nr_line = scalar @$l;
2419 if (!$nr_line) {
2420 print "1 line\n\n\n";
2421 } else {
2422 if ($nr_line == 1) {
2423 $nr_line = '1 line';
2424 } else {
2425 $nr_line .= ' lines';
2426 }
2427 print $nr_line, "\n";
2428 show_commit_changed_paths($c);
2429 print "\n";
2430 print $_ foreach @$l;
2431 }
2432 } else {
2433 print "1 line\n";
2434 show_commit_changed_paths($c);
2435 print "\n";
2436
2437 }
2438 foreach my $x (qw/raw diff/) {
2439 if ($c->{$x}) {
2440 print "\n";
2441 print $_ foreach @{$c->{$x}}
2442 }
2443 }
2444}
2445
2446sub cmd_show_log {
2447 my (@args) = @_;
2448 my ($r_min, $r_max);
2449 my $r_last = -1; # prevent dupes
2450 if (defined $TZ) {
2451 $ENV{TZ} = $TZ;
2452 } else {
2453 delete $ENV{TZ};
2454 }
2455 if (defined $::_revision) {
2456 if ($::_revision =~ /^(\d+):(\d+)$/) {
2457 ($r_min, $r_max) = ($1, $2);
2458 } elsif ($::_revision =~ /^\d+$/) {
2459 $r_min = $r_max = $::_revision;
2460 } else {
2461 ::fatal "-r$::_revision is not supported, use ",
2462 "standard \'git log\' arguments instead\n";
2463 }
2464 }
2465
2466 config_pager();
2467 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2468 my $log = command_output_pipe(@args);
2469 run_pager();
2470 my (@k, $c, $d);
2471 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2472 while (<$log>) {
2473 if (/^${esc_color}commit ($::sha1_short)/o) {
2474 my $cmt = $1;
2475 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2476 $r_last = $c->{r};
2477 process_commit($c, $r_min, $r_max, \@k) or
2478 goto out;
2479 }
2480 $d = undef;
2481 $c = { c => $cmt };
2482 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2483 get_author_info($c, $1, $2, $3);
2484 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2485 # ignore
2486 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2487 push @{$c->{raw}}, $_;
2488 } elsif (/^${esc_color}[ACRMDT]\t/) {
2489 # we could add $SVN->{svn_path} here, but that requires
2490 # remote access at the moment (repo_path_split)...
2491 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2492 push @{$c->{changed}}, $_;
2493 } elsif (/^${esc_color}diff /o) {
2494 $d = 1;
2495 push @{$c->{diff}}, $_;
2496 } elsif ($d) {
2497 push @{$c->{diff}}, $_;
2498 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2499 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2500 } elsif (s/^${esc_color} //o) {
2501 push @{$c->{l}}, $_;
2502 }
2503 }
2504 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2505 $r_last = $c->{r};
2506 process_commit($c, $r_min, $r_max, \@k);
2507 }
2508 if (@k) {
2509 my $swap = $r_max;
2510 $r_max = $r_min;
2511 $r_min = $swap;
2512 process_commit($_, $r_min, $r_max) foreach reverse @k;
2513 }
2514out:
2515 close $log;
2516 print '-' x72,"\n" unless $incremental || $oneline;
2517}
2518
2519package Git::SVN::Migration;
2520# these version numbers do NOT correspond to actual version numbers
2521# of git nor git-svn. They are just relative.
2522#
2523# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2524#
2525# v1 layout: .git/$id/info/url, refs/remotes/$id
2526#
2527# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2528#
2529# v3 layout: .git/svn/$id, refs/remotes/$id
2530# - info/url may remain for backwards compatibility
2531# - this is what we migrate up to this layout automatically,
2532# - this will be used by git svn init on single branches
2533#
2534# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2535# - this is only created for newly multi-init-ed
2536# repositories. Similar in spirit to the
2537# --use-separate-remotes option in git-clone (now default)
2538# - we do not automatically migrate to this (following
2539# the example set by core git)
2540use strict;
2541use warnings;
2542use Carp qw/croak/;
2543use File::Path qw/mkpath/;
2544use File::Basename qw/dirname basename/;
2545use vars qw/$_minimize/;
2546
2547sub migrate_from_v0 {
2548 my $git_dir = $ENV{GIT_DIR};
2549 return undef unless -d $git_dir;
2550 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2551 my $migrated = 0;
2552 while (<$fh>) {
2553 chomp;
2554 my ($id, $orig_ref) = ($_, $_);
2555 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2556 next unless -f "$git_dir/$id/info/url";
2557 my $new_ref = "refs/remotes/$id";
2558 if (::verify_ref("$new_ref^0")) {
2559 print STDERR "W: $orig_ref is probably an old ",
2560 "branch used by an ancient version of ",
2561 "git-svn.\n",
2562 "However, $new_ref also exists.\n",
2563 "We will not be able ",
2564 "to use this branch until this ",
2565 "ambiguity is resolved.\n";
2566 next;
2567 }
2568 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2569 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2570 command_noisy('update-ref', $new_ref, $orig_ref);
2571 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2572 $migrated++;
2573 }
2574 command_close_pipe($fh, $ctx);
2575 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2576 $migrated;
2577}
2578
2579sub migrate_from_v1 {
2580 my $git_dir = $ENV{GIT_DIR};
2581 my $migrated = 0;
2582 return $migrated unless -d $git_dir;
2583 my $svn_dir = "$git_dir/svn";
2584
2585 # just in case somebody used 'svn' as their $id at some point...
2586 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2587
2588 print STDERR "Migrating from a git-svn v1 layout...\n";
2589 mkpath([$svn_dir]);
2590 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2591 "$svn_dir\n\t(required for this version ",
2592 "($::VERSION) of git-svn) does not. exist\n";
2593 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2594 while (<$fh>) {
2595 my $x = $_;
2596 next unless $x =~ s#^refs/remotes/##;
2597 chomp $x;
2598 next unless -f "$git_dir/$x/info/url";
2599 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2600 next unless $u;
2601 my $dn = dirname("$git_dir/svn/$x");
2602 mkpath([$dn]) unless -d $dn;
2603 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2604 mkpath(["$git_dir/svn/svn"]);
2605 print STDERR " - $git_dir/$x/info => ",
2606 "$git_dir/svn/$x/info\n";
2607 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2608 croak "$!: $x";
2609 # don't worry too much about these, they probably
2610 # don't exist with repos this old (save for index,
2611 # and we can easily regenerate that)
2612 foreach my $f (qw/unhandled.log index .rev_db/) {
2613 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2614 }
2615 } else {
2616 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2617 rename "$git_dir/$x", "$git_dir/svn/$x" or
2618 croak "$!: $x";
2619 }
2620 $migrated++;
2621 }
2622 command_close_pipe($fh, $ctx);
2623 print STDERR "Done migrating from a git-svn v1 layout\n";
2624 $migrated;
2625}
2626
2627sub read_old_urls {
2628 my ($l_map, $pfx, $path) = @_;
2629 my @dir;
2630 foreach (<$path/*>) {
2631 if (-r "$_/info/url") {
2632 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2633 my $ref_id = $pfx . basename $_;
2634 my $url = ::file_to_s("$_/info/url");
2635 $l_map->{$ref_id} = $url;
2636 } elsif (-d $_) {
2637 push @dir, $_;
2638 }
2639 }
2640 foreach (@dir) {
2641 my $x = $_;
2642 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2643 read_old_urls($l_map, $x, $_);
2644 }
2645}
2646
2647sub migrate_from_v2 {
2648 my @cfg = command(qw/config -l/);
2649 return if grep /^svn-remote\..+\.url=/, @cfg;
2650 my %l_map;
2651 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2652 my $migrated = 0;
2653
2654 foreach my $ref_id (sort keys %l_map) {
2655 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2656 $migrated++;
2657 }
2658 $migrated;
2659}
2660
2661sub minimize_connections {
2662 my $r = Git::SVN::read_all_remotes();
2663 my $new_urls = {};
2664 my $root_repos = {};
2665 foreach my $repo_id (keys %$r) {
2666 my $url = $r->{$repo_id}->{url} or next;
2667 my $fetch = $r->{$repo_id}->{fetch} or next;
2668 my $ra = Git::SVN::Ra->new($url);
2669
2670 # skip existing cases where we already connect to the root
2671 if (($ra->{url} eq $ra->{repos_root}) ||
2672 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2673 $repo_id)) {
2674 $root_repos->{$ra->{url}} = $repo_id;
2675 next;
2676 }
2677
2678 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2679 my $root_path = $ra->{url};
2680 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2681 foreach my $path (keys %$fetch) {
2682 my $ref_id = $fetch->{$path};
2683 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2684
2685 # make sure we can read when connecting to
2686 # a higher level of a repository
2687 my ($last_rev, undef) = $gs->last_rev_commit;
2688 if (!defined $last_rev) {
2689 $last_rev = eval {
2690 $root_ra->get_latest_revnum;
2691 };
2692 next if $@;
2693 }
2694 my $new = $root_path;
2695 $new .= length $path ? "/$path" : '';
2696 eval {
2697 $root_ra->get_log([$new], $last_rev, $last_rev,
2698 0, 0, 1, sub { });
2699 };
2700 next if $@;
2701 $new_urls->{$ra->{repos_root}}->{$new} =
2702 { ref_id => $ref_id,
2703 old_repo_id => $repo_id,
2704 old_path => $path };
2705 }
2706 }
2707
2708 my @emptied;
2709 foreach my $url (keys %$new_urls) {
2710 # see if we can re-use an existing [svn-remote "repo_id"]
2711 # instead of creating a(n ugly) new section:
2712 my $repo_id = $root_repos->{$url} ||
2713 Git::SVN::sanitize_remote_name($url);
2714
2715 my $fetch = $new_urls->{$url};
2716 foreach my $path (keys %$fetch) {
2717 my $x = $fetch->{$path};
2718 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2719 my $pfx = "svn-remote.$x->{old_repo_id}";
2720
2721 my $old_fetch = quotemeta("$x->{old_path}:".
2722 "refs/remotes/$x->{ref_id}");
2723 command_noisy(qw/config --unset/,
2724 "$pfx.fetch", '^'. $old_fetch . '$');
2725 delete $r->{$x->{old_repo_id}}->
2726 {fetch}->{$x->{old_path}};
2727 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2728 command_noisy(qw/config --unset/,
2729 "$pfx.url");
2730 push @emptied, $x->{old_repo_id}
2731 }
2732 }
2733 }
2734 if (@emptied) {
2735 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2736 "$ENV{GIT_DIR}/config";
2737 print STDERR <<EOF;
2738The following [svn-remote] sections in your config file ($file) are empty
2739and can be safely removed:
2740EOF
2741 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2742 }
2743}
2744
2745sub migration_check {
2746 migrate_from_v0();
2747 migrate_from_v1();
2748 migrate_from_v2();
2749 minimize_connections() if $_minimize;
2750}
2751
2752__END__
2753
2754Data structures:
2755
2756$log_entry hashref as returned by libsvn_log_entry()
2757{
2758 log => 'whitespace-formatted log entry
2759', # trailing newline is preserved
2760 revision => '8', # integer
2761 date => '2004-02-24T17:01:44.108345Z', # commit date
2762 author => 'committer name'
2763};
2764
2765@mods = array of diff-index line hashes, each element represents one line
2766 of diff-index output
2767
2768diff-index line ($m hash)
2769{
2770 mode_a => first column of diff-index output, no leading ':',
2771 mode_b => second column of diff-index output,
2772 sha1_b => sha1sum of the final blob,
2773 chg => change type [MCRADT],
2774 file_a => original file name of a file (iff chg is 'C' or 'R')
2775 file_b => new/current file name of a file (any chg)
2776}
2777;
2778
2779# retval of read_url_paths{,_all}();
2780$l_map = {
2781 # repository root url
2782 'https://svn.musicpd.org' => {
2783 # repository path # GIT_SVN_ID
2784 'mpd/trunk' => 'trunk',
2785 'mpd/tags/0.11.5' => 'tags/0.11.5',
2786 },
2787}
2788
2789Notes:
2790 I don't trust the each() function on unless I created %hash myself
2791 because the internal iterator may not have started at base.