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