git-svn: fix several fetch bugs related to repeated invocations
[git/dscho.git] / git-svn.perl
blob2afa2537b9c1af92700777f9426f59de82d0b31c
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $SVN_URL
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB
10 $_follow_parent $sha1 $sha1_short $_revision
11 $_cp_remote $_upgrade $_q
12 $_authors %users/;
13 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
14 $VERSION = '@@GIT_VERSION@@';
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';
20 my $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
27 sub fatal (@) { print STDERR @_; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use IO::File qw//;
39 use File::Basename qw/dirname basename/;
40 use File::Path qw/mkpath/;
41 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
42 use IPC::Open3;
43 use Git;
45 BEGIN {
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::$_; ";
53 eval $s;
56 my ($SVN);
58 my $_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}/;
61 my ($_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);
69 my %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 );
72 my %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 );
80 my ($_trunk, $_tags, $_branches);
81 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
82 'tags|t=s' => \$_tags,
83 'branches|b=s' => \$_branches );
84 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
85 my %cmt_opts = ( 'edit|e' => \$_edit,
86 'rmdir' => \$SVN::Git::Editor::_rmdir,
87 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
88 'l=i' => \$SVN::Git::Editor::_rename_limit,
89 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
92 my %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 'multi-init' => [ \&cmd_multi_init,
110 'Initialize multiple trees (like git-svnimport)',
111 { %multi_opts, %init_opts, %remote_opts,
112 'revision|r=i' => \$_revision,
113 'prefix=s' => \$_prefix,
114 } ],
115 'multi-fetch' => [ \&cmd_multi_fetch,
116 'Fetch multiple trees (like git-svnimport)',
117 \%fc_opts ],
118 'migrate' => [ sub { },
119 # no-op, we automatically run this anyways,
120 'Migrate configuration/metadata/layout from
121 previous versions of git-svn',
122 \%remote_opts ],
123 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
124 { 'limit=i' => \$Git::SVN::Log::limit,
125 'revision|r=s' => \$_revision,
126 'verbose|v' => \$Git::SVN::Log::verbose,
127 'incremental' => \$Git::SVN::Log::incremental,
128 'oneline' => \$Git::SVN::Log::oneline,
129 'show-commit' => \$Git::SVN::Log::show_commit,
130 'non-recursive' => \$Git::SVN::Log::non_recursive,
131 'authors-file|A=s' => \$_authors,
132 'color' => \$Git::SVN::Log::color,
133 'pager=s' => \$Git::SVN::Log::pager,
134 } ],
135 'commit-diff' => [ \&cmd_commit_diff,
136 'Commit a diff between two trees',
137 { 'message|m=s' => \$_message,
138 'file|F=s' => \$_file,
139 'revision|r=s' => \$_revision,
140 %cmt_opts } ],
143 my $cmd;
144 for (my $i = 0; $i < @ARGV; $i++) {
145 if (defined $cmd{$ARGV[$i]}) {
146 $cmd = $ARGV[$i];
147 splice @ARGV, $i, 1;
148 last;
152 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
154 read_repo_config(\%opts);
155 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
156 'version|V' => \$_version,
157 'minimize-connections' =>
158 \$Git::SVN::Migration::_minimize,
159 'id|i=s' => \$Git::SVN::default_ref_id);
160 exit 1 if (!$rv && $cmd ne 'log');
162 usage(0) if $_help;
163 version() if $_version;
164 usage(1) unless defined $cmd;
165 load_authors() if $_authors;
166 unless ($cmd =~ /^(?:init|multi-init|commit-diff)$/) {
167 Git::SVN::Migration::migration_check();
169 eval {
170 Git::SVN::verify_remotes_sanity();
171 $cmd{$cmd}->[0]->(@ARGV);
173 fatal $@ if $@;
174 exit 0;
176 ####################### primary functions ######################
177 sub usage {
178 my $exit = shift || 0;
179 my $fd = $exit ? \*STDERR : \*STDOUT;
180 print $fd <<"";
181 git-svn - bidirectional operations between a single Subversion tree and git
182 Usage: $0 <command> [options] [arguments]\n
184 print $fd "Available commands:\n" unless $cmd;
186 foreach (sort keys %cmd) {
187 next if $cmd && $cmd ne $_;
188 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
189 foreach (keys %{$cmd{$_}->[2]}) {
190 # prints out arguments as they should be passed:
191 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
192 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
193 "--$_" : "-$_" }
194 split /\|/,$_)," $x\n";
197 print $fd <<"";
198 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
199 arbitrary identifier if you're tracking multiple SVN branches/repositories in
200 one git repository and want to keep them separate. See git-svn(1) for more
201 information.
203 exit $exit;
206 sub version {
207 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
208 exit 0;
211 sub do_git_init_db {
212 unless (-d $ENV{GIT_DIR}) {
213 my @init_db = ('init');
214 push @init_db, "--template=$_template" if defined $_template;
215 push @init_db, "--shared" if defined $_shared;
216 command_noisy(@init_db);
220 sub cmd_init {
221 my $url = shift or die "SVN repository location required " .
222 "as a command-line argument\n";
223 if (my $repo_path = shift) {
224 unless (-d $repo_path) {
225 mkpath([$repo_path]);
227 chdir $repo_path or croak $!;
228 $ENV{GIT_DIR} = $repo_path . "/.git";
230 do_git_init_db();
232 Git::SVN->init($url);
235 sub cmd_fetch {
236 if (@_) {
237 die "Additional fetch arguments are no longer supported.\n",
238 "Use --follow-parent if you have moved/copied directories
239 instead.\n";
241 my $gs = Git::SVN->new;
242 $gs->fetch(parse_revision_argument());
243 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
244 command_noisy(qw(update-ref refs/heads/master),
245 $gs->{last_commit});
249 sub cmd_set_tree {
250 my (@commits) = @_;
251 if ($_stdin || !@commits) {
252 print "Reading from stdin...\n";
253 @commits = ();
254 while (<STDIN>) {
255 if (/\b($sha1_short)\b/o) {
256 unshift @commits, $1;
260 my @revs;
261 foreach my $c (@commits) {
262 my @tmp = command('rev-parse',$c);
263 if (scalar @tmp == 1) {
264 push @revs, $tmp[0];
265 } elsif (scalar @tmp > 1) {
266 push @revs, reverse(command('rev-list',@tmp));
267 } else {
268 fatal "Failed to rev-parse $c\n";
271 my $gs = Git::SVN->new;
272 my ($r_last, $cmt_last) = $gs->last_rev_commit;
273 $gs->fetch;
274 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
275 fatal "There are new revisions that were fetched ",
276 "and need to be merged (or acknowledged) ",
277 "before committing.\nlast rev: $r_last\n",
278 " current: $gs->{last_rev}\n";
280 $gs->set_tree($_) foreach @revs;
281 print "Done committing ",scalar @revs," revisions to SVN\n";
284 sub cmd_dcommit {
285 my $head = shift;
286 my $gs = Git::SVN->new;
287 $head ||= 'HEAD';
288 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
289 my $last_rev;
290 foreach my $d (reverse @refs) {
291 if (!verify_ref("$d~1")) {
292 fatal "Commit $d\n",
293 "has no parent commit, and therefore ",
294 "nothing to diff against.\n",
295 "You should be working from a repository ",
296 "originally created by git-svn\n";
298 unless (defined $last_rev) {
299 (undef, $last_rev, undef) = cmt_metadata("$d~1");
300 unless (defined $last_rev) {
301 fatal "Unable to extract revision information ",
302 "from commit $d~1\n";
305 if ($_dry_run) {
306 print "diff-tree $d~1 $d\n";
307 } else {
308 my %ed_opts = ( r => $last_rev,
309 log => get_commit_entry($d)->{log},
310 ra => $gs->ra,
311 tree_a => "$d~1",
312 tree_b => $d,
313 editor_cb => sub {
314 print "Committed r$_[0]\n";
315 $last_rev = $_[0]; },
316 svn_path => $gs->{path} );
317 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
318 print "No changes\n$d~1 == $d\n";
322 return if $_dry_run;
323 $gs->fetch;
324 # we always want to rebase against the current HEAD, not any
325 # head that was passed to us
326 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
327 my @finish;
328 if (@diff) {
329 @finish = qw/rebase/;
330 push @finish, qw/--merge/ if $_merge;
331 push @finish, "--strategy=$_strategy" if $_strategy;
332 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
333 "using @finish:\n", "@diff";
334 } else {
335 print "No changes between current HEAD and ",
336 $gs->refname, "\nResetting to the latest ",
337 $gs->refname, "\n";
338 @finish = qw/reset --mixed/;
340 command_noisy(@finish, $gs->refname);
343 sub cmd_show_ignore {
344 my $gs = Git::SVN->new;
345 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
346 $gs->traverse_ignore(\*STDOUT, '', $r);
349 sub cmd_multi_init {
350 my $url = shift;
351 unless (defined $_trunk || defined $_branches || defined $_tags) {
352 usage(1);
354 do_git_init_db();
355 $_prefix = '' unless defined $_prefix;
356 $url =~ s#/+$## if defined $url;
357 if (defined $_trunk) {
358 my $trunk_ref = $_prefix . 'trunk';
359 # try both old-style and new-style lookups:
360 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
361 unless ($gs_trunk) {
362 my ($trunk_url, $trunk_path) =
363 complete_svn_url($url, $_trunk);
364 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
365 undef, $trunk_ref);
368 return unless defined $_branches || defined $_tags;
369 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
370 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
371 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
374 sub cmd_multi_fetch {
375 my $remotes = Git::SVN::read_all_remotes();
376 foreach my $repo_id (sort keys %$remotes) {
377 my $url = $remotes->{$repo_id}->{url} or next;
378 my $fetch = $remotes->{$repo_id}->{fetch} or next;
379 Git::SVN::fetch_all($repo_id, $url, $fetch);
383 # this command is special because it requires no metadata
384 sub cmd_commit_diff {
385 my ($ta, $tb, $url) = @_;
386 my $usage = "Usage: $0 commit-diff -r<revision> ".
387 "<tree-ish> <tree-ish> [<URL>]\n";
388 fatal($usage) if (!defined $ta || !defined $tb);
389 my $svn_path;
390 if (!defined $url) {
391 my $gs = eval { Git::SVN->new };
392 if (!$gs) {
393 fatal("Needed URL or usable git-svn --id in ",
394 "the command-line\n", $usage);
396 $url = $gs->{url};
397 $svn_path = $gs->{path};
399 unless (defined $_revision) {
400 fatal("-r|--revision is a required argument\n", $usage);
402 if (defined $_message && defined $_file) {
403 fatal("Both --message/-m and --file/-F specified ",
404 "for the commit message.\n",
405 "I have no idea what you mean\n");
407 if (defined $_file) {
408 $_message = file_to_s($_file);
409 } else {
410 $_message ||= get_commit_entry($tb)->{log};
412 my $ra ||= Git::SVN::Ra->new($url);
413 $svn_path ||= $ra->{svn_path};
414 my $r = $_revision;
415 if ($r eq 'HEAD') {
416 $r = $ra->get_latest_revnum;
417 } elsif ($r !~ /^\d+$/) {
418 die "revision argument: $r not understood by git-svn\n";
420 my %ed_opts = ( r => $r,
421 log => $_message,
422 ra => $ra,
423 tree_a => $ta,
424 tree_b => $tb,
425 editor_cb => sub { print "Committed r$_[0]\n" },
426 svn_path => $svn_path );
427 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
428 print "No changes\n$ta == $tb\n";
432 ########################### utility functions #########################
434 sub parse_revision_argument {
435 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
436 return (undef, undef);
438 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
439 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
440 return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
441 return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
442 die "revision argument: $_revision not understood by git-svn\n",
443 "Try using the command-line svn client instead\n";
446 sub complete_svn_url {
447 my ($url, $path) = @_;
448 $path =~ s#/+$##;
449 if ($path !~ m#^[a-z\+]+://#) {
450 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
451 fatal("E: '$path' is not a complete URL ",
452 "and a separate URL is not specified\n");
454 return ($url, $path);
456 return ($path, '');
459 sub complete_url_ls_init {
460 my ($ra, $repo_path, $switch, $pfx) = @_;
461 unless ($repo_path) {
462 print STDERR "W: $switch not specified\n";
463 return;
465 $repo_path =~ s#/+$##;
466 if ($repo_path =~ m#^[a-z\+]+://#) {
467 $ra = Git::SVN::Ra->new($repo_path);
468 $repo_path = '';
469 } else {
470 $repo_path =~ s#^/+##;
471 unless ($ra) {
472 fatal("E: '$repo_path' is not a complete URL ",
473 "and a separate URL is not specified\n");
476 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
477 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
478 my $url = $ra->{url};
479 foreach my $d (sort keys %$dirent) {
480 next if ($dirent->{$d}->kind != $SVN::Node::dir);
481 my $path = "$repo_path/$d";
482 my $ref = "$pfx$d";
483 my $gs = eval { Git::SVN->new($ref) };
484 # don't try to init already existing refs
485 unless ($gs) {
486 print "init $url/$path => $ref\n";
487 Git::SVN->init($url, $path, undef, $ref);
492 sub verify_ref {
493 my ($ref) = @_;
494 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
495 { STDERR => 0 }); };
498 sub get_tree_from_treeish {
499 my ($treeish) = @_;
500 # $treeish can be a symbolic ref, too:
501 my $type = command_oneline(qw/cat-file -t/, $treeish);
502 my $expected;
503 while ($type eq 'tag') {
504 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
506 if ($type eq 'commit') {
507 $expected = (grep /^tree /, command(qw/cat-file commit/,
508 $treeish))[0];
509 ($expected) = ($expected =~ /^tree ($sha1)$/o);
510 die "Unable to get tree from $treeish\n" unless $expected;
511 } elsif ($type eq 'tree') {
512 $expected = $treeish;
513 } else {
514 die "$treeish is a $type, expected tree, tag or commit\n";
516 return $expected;
519 sub get_commit_entry {
520 my ($treeish) = shift;
521 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
522 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
523 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
524 open my $log_fh, '>', $commit_editmsg or croak $!;
526 my $type = command_oneline(qw/cat-file -t/, $treeish);
527 if ($type eq 'commit' || $type eq 'tag') {
528 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
529 $type, $treeish);
530 my $in_msg = 0;
531 while (<$msg_fh>) {
532 if (!$in_msg) {
533 $in_msg = 1 if (/^\s*$/);
534 } elsif (/^git-svn-id: /) {
535 # skip this for now, we regenerate the
536 # correct one on re-fetch anyways
537 # TODO: set *:merge properties or like...
538 } else {
539 print $log_fh $_ or croak $!;
542 command_close_pipe($msg_fh, $ctx);
544 close $log_fh or croak $!;
546 if ($_edit || ($type eq 'tree')) {
547 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
548 # TODO: strip out spaces, comments, like git-commit.sh
549 system($editor, $commit_editmsg);
551 rename $commit_editmsg, $commit_msg or croak $!;
552 open $log_fh, '<', $commit_msg or croak $!;
553 { local $/; chomp($log_entry{log} = <$log_fh>); }
554 close $log_fh or croak $!;
555 unlink $commit_msg;
556 \%log_entry;
559 sub s_to_file {
560 my ($str, $file, $mode) = @_;
561 open my $fd,'>',$file or croak $!;
562 print $fd $str,"\n" or croak $!;
563 close $fd or croak $!;
564 chmod ($mode &~ umask, $file) if (defined $mode);
567 sub file_to_s {
568 my $file = shift;
569 open my $fd,'<',$file or croak "$!: file: $file\n";
570 local $/;
571 my $ret = <$fd>;
572 close $fd or croak $!;
573 $ret =~ s/\s*$//s;
574 return $ret;
577 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
578 sub load_authors {
579 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
580 my $log = $cmd eq 'log';
581 while (<$authors>) {
582 chomp;
583 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
584 my ($user, $name, $email) = ($1, $2, $3);
585 if ($log) {
586 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
587 } else {
588 $users{$user} = [$name, $email];
591 close $authors or croak $!;
594 # convert GetOpt::Long specs for use by git-config
595 sub read_repo_config {
596 return unless -d $ENV{GIT_DIR};
597 my $opts = shift;
598 foreach my $o (keys %$opts) {
599 my $v = $opts->{$o};
600 my ($key) = ($o =~ /^([a-z\-]+)/);
601 $key =~ s/-//g;
602 my $arg = 'git-config';
603 $arg .= ' --int' if ($o =~ /[:=]i$/);
604 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
605 if (ref $v eq 'ARRAY') {
606 chomp(my @tmp = `$arg --get-all svn.$key`);
607 @$v = @tmp if @tmp;
608 } else {
609 chomp(my $tmp = `$arg --get svn.$key`);
610 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
611 $$v = $tmp;
617 sub extract_metadata {
618 my $id = shift or return (undef, undef, undef);
619 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
620 \s([a-f\d\-]+)$/x);
621 if (!defined $rev || !$uuid || !$url) {
622 # some of the original repositories I made had
623 # identifiers like this:
624 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
626 return ($url, $rev, $uuid);
629 sub cmt_metadata {
630 return extract_metadata((grep(/^git-svn-id: /,
631 command(qw/cat-file commit/, shift)))[-1]);
634 package Git::SVN;
635 use strict;
636 use warnings;
637 use vars qw/$default_repo_id $default_ref_id/;
638 use Carp qw/croak/;
639 use File::Path qw/mkpath/;
640 use IPC::Open3;
642 # properties that we do not log:
643 my %SKIP_PROP;
644 BEGIN {
645 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
646 svn:special svn:executable
647 svn:entry:committed-rev
648 svn:entry:last-author
649 svn:entry:uuid
650 svn:entry:committed-date/;
653 sub fetch_all {
654 my ($repo_id, $url, $fetch) = @_;
655 my @gs;
656 my $ra = Git::SVN::Ra->new($url);
657 my $head = $ra->get_latest_revnum;
658 my $base = $head;
659 my $new_remote;
660 foreach my $p (sort keys %$fetch) {
661 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
662 my $lr = $gs->last_rev;
663 if (defined $lr) {
664 $base = $lr if ($lr < $base);
665 } else {
666 $new_remote = 1;
668 push @gs, $gs;
670 $base = 0 if $new_remote;
671 return if (++$base > $head);
672 $ra->gs_fetch_loop_common($base, $head, @gs);
675 sub read_all_remotes {
676 my $r = {};
677 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
678 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
679 $r->{$1}->{fetch}->{$2} = $3;
680 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
681 $r->{$1}->{url} = $2;
687 sub verify_remotes_sanity {
688 return unless -d $ENV{GIT_DIR};
689 my %seen;
690 foreach (command(qw/config -l/)) {
691 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
692 if ($seen{$1}) {
693 die "Remote ref refs/remote/$1 is tracked by",
694 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
695 "Please resolve this ambiguity in ",
696 "your git configuration file before ",
697 "continuing\n";
699 $seen{$1} = $_;
704 # we allow more chars than remotes2config.sh...
705 sub sanitize_remote_name {
706 my ($name) = @_;
707 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
708 $name;
711 sub find_existing_remote {
712 my ($url, $remotes) = @_;
713 my $existing;
714 foreach my $repo_id (keys %$remotes) {
715 my $u = $remotes->{$repo_id}->{url} or next;
716 next if $u ne $url;
717 $existing = $repo_id;
718 last;
720 $existing;
723 sub init_remote_config {
724 my ($self, $url) = @_;
725 $url =~ s!/+$!!; # strip trailing slash
726 my $r = read_all_remotes();
727 my $existing = find_existing_remote($url, $r);
728 if ($existing) {
729 print STDERR "Using existing ",
730 "[svn-remote \"$existing\"]\n";
731 $self->{repo_id} = $existing;
732 } else {
733 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
734 $existing = find_existing_remote($min_url, $r);
735 if ($existing) {
736 print STDERR "Using existing ",
737 "[svn-remote \"$existing\"]\n";
738 $self->{repo_id} = $existing;
740 if ($min_url ne $url) {
741 print STDERR "Using higher level of URL: ",
742 "$url => $min_url\n";
743 my $old_path = $self->{path};
744 $self->{path} = $url;
745 $self->{path} =~ s!^\Q$min_url\E/*!!;
746 if (length $old_path) {
747 $self->{path} .= "/$old_path";
749 $url = $min_url;
752 my $orig_url;
753 if (!$existing) {
754 # verify that we aren't overwriting anything:
755 $orig_url = eval {
756 command_oneline('config', '--get',
757 "svn-remote.$self->{repo_id}.url")
759 if ($orig_url && ($orig_url ne $url)) {
760 die "svn-remote.$self->{repo_id}.url already set: ",
761 "$orig_url\nwanted to set to: $url\n";
764 my ($xrepo_id, $xpath) = find_ref($self->refname);
765 if (defined $xpath) {
766 die "svn-remote.$xrepo_id.fetch already set to track ",
767 "$xpath:refs/remotes/", $self->refname, "\n";
769 command_noisy('config',
770 "svn-remote.$self->{repo_id}.url", $url);
771 command_noisy('config', '--add',
772 "svn-remote.$self->{repo_id}.fetch",
773 "$self->{path}:".$self->refname);
774 $self->{url} = $url;
777 sub init {
778 my ($class, $url, $path, $repo_id, $ref_id) = @_;
779 my $self = _new($class, $repo_id, $ref_id, $path);
780 if (defined $url) {
781 $self->init_remote_config($url);
783 $self;
786 sub find_ref {
787 my ($ref_id) = @_;
788 foreach (command(qw/config -l/)) {
789 next unless m!^svn-remote\.(.+)\.fetch=
790 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
791 my ($repo_id, $path, $ref) = ($1, $2, $3);
792 if ($ref eq $ref_id) {
793 $path = '' if ($path =~ m#^\./?#);
794 return ($repo_id, $path);
797 (undef, undef, undef);
800 sub new {
801 my ($class, $ref_id, $repo_id, $path) = @_;
802 if (defined $ref_id && !defined $repo_id && !defined $path) {
803 ($repo_id, $path) = find_ref($ref_id);
804 if (!defined $repo_id) {
805 die "Could not find a \"svn-remote.*.fetch\" key ",
806 "in the repository configuration matching: ",
807 "refs/remotes/$ref_id\n";
810 my $self = _new($class, $repo_id, $ref_id, $path);
811 if (!defined $self->{path} || !length $self->{path}) {
812 my $fetch = command_oneline('config', '--get',
813 "svn-remote.$repo_id.fetch",
814 ":refs/remotes/$ref_id\$") or
815 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
816 "\":refs/remotes/$ref_id\$\" in config\n";
817 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
819 $self->{url} = command_oneline('config', '--get',
820 "svn-remote.$repo_id.url") or
821 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
822 if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
823 $self->rebuild;
825 $self;
828 sub refname { "refs/remotes/$_[0]->{ref_id}" }
830 sub ra {
831 my ($self) = shift;
832 Git::SVN::Ra->new($self->{url});
835 sub rel_path {
836 my ($self) = @_;
837 my $repos_root = $self->ra->{repos_root};
838 return $self->{path} if ($self->{url} eq $repos_root);
839 my $url = $self->{url} .
840 (length $self->{path} ? "/$self->{path}" : $self->{path});
841 $url =~ s!^\Q$repos_root\E/*!!g;
842 $url;
845 sub traverse_ignore {
846 my ($self, $fh, $path, $r) = @_;
847 $path =~ s#^/+##g;
848 my $ra = $self->ra;
849 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
850 my $p = $path;
851 $p =~ s#^\Q$ra->{svn_path}\E/##;
852 print $fh length $p ? "\n# $p\n" : "\n# /\n";
853 if (my $s = $props->{'svn:ignore'}) {
854 $s =~ s/[\r\n]+/\n/g;
855 chomp $s;
856 if (length $p == 0) {
857 $s =~ s#\n#\n/$p#g;
858 print $fh "/$s\n";
859 } else {
860 $s =~ s#\n#\n/$p/#g;
861 print $fh "/$p/$s\n";
864 foreach (sort keys %$dirent) {
865 next if $dirent->{$_}->kind != $SVN::Node::dir;
866 $self->traverse_ignore($fh, "$path/$_", $r);
870 sub last_rev { ($_[0]->last_rev_commit)[0] }
871 sub last_commit { ($_[0]->last_rev_commit)[1] }
873 # returns the newest SVN revision number and newest commit SHA1
874 sub last_rev_commit {
875 my ($self) = @_;
876 if (defined $self->{last_rev} && defined $self->{last_commit}) {
877 return ($self->{last_rev}, $self->{last_commit});
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);
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;
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);
910 sub get_fetch_range {
911 my ($self, $min, $max) = @_;
912 $max ||= $self->ra->get_latest_revnum;
913 $min ||= $self->last_rev || 0;
914 (++$min, $max);
917 sub tmp_index_do {
918 my ($self, $sub) = @_;
919 my $old_index = $ENV{GIT_INDEX_FILE};
920 $ENV{GIT_INDEX_FILE} = $self->{index};
921 my @ret = &$sub;
922 if ($old_index) {
923 $ENV{GIT_INDEX_FILE} = $old_index;
924 } else {
925 delete $ENV{GIT_INDEX_FILE};
927 wantarray ? @ret : $ret[0];
930 sub assert_index_clean {
931 my ($self, $treeish) = @_;
933 $self->tmp_index_do(sub {
934 command_noisy('read-tree', $treeish) unless -e $self->{index};
935 my $x = command_oneline('write-tree');
936 my ($y) = (command(qw/cat-file commit/, $treeish) =~
937 /^tree ($::sha1)/mo);
938 if ($y ne $x) {
939 unlink $self->{index} or croak $!;
940 command_noisy('read-tree', $treeish);
942 $x = command_oneline('write-tree');
943 if ($y ne $x) {
944 ::fatal "trees ($treeish) $y != $x\n",
945 "Something is seriously wrong...\n";
950 sub get_commit_parents {
951 my ($self, $log_entry) = @_;
952 my (%seen, @ret, @tmp);
953 # legacy support for 'set-tree'; this is only used by set_tree_cb:
954 if (my $ip = $self->{inject_parents}) {
955 if (my $commit = delete $ip->{$log_entry->{revision}}) {
956 push @tmp, $commit;
959 if (my $cur = ::verify_ref($self->refname.'^0')) {
960 push @tmp, $cur;
962 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
963 while (my $p = shift @tmp) {
964 next if $seen{$p};
965 $seen{$p} = 1;
966 push @ret, $p;
967 # MAXPARENT is defined to 16 in commit-tree.c:
968 last if @ret >= 16;
970 if (@tmp) {
971 die "r$log_entry->{revision}: No room for parents:\n\t",
972 join("\n\t", @tmp), "\n";
974 @ret;
977 sub full_url {
978 my ($self) = @_;
979 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
982 sub do_git_commit {
983 my ($self, $log_entry) = @_;
984 my $lr = $self->last_rev;
985 if (defined $lr && $lr >= $log_entry->{revision}) {
986 die "Last fetched revision of ", $self->refname,
987 " was r$lr, but we are about to fetch: ",
988 "r$log_entry->{revision}!\n";
990 if (my $c = $self->rev_db_get($log_entry->{revision})) {
991 croak "$log_entry->{revision} = $c already exists! ",
992 "Why are we refetching it?\n";
994 my $author = $log_entry->{author};
995 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
996 : ($author, "$author\@".$self->ra->uuid));
997 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
998 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
999 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1001 my $tree = $log_entry->{tree};
1002 if (!defined $tree) {
1003 $tree = $self->tmp_index_do(sub {
1004 command_oneline('write-tree') });
1006 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1008 my @exec = ('git-commit-tree', $tree);
1009 foreach ($self->get_commit_parents($log_entry)) {
1010 push @exec, '-p', $_;
1012 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1013 or croak $!;
1014 print $msg_fh $log_entry->{log} or croak $!;
1015 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1016 $log_entry->{revision}, ' ',
1017 $self->ra->uuid, "\n" or croak $!;
1018 $msg_fh->flush == 0 or croak $!;
1019 close $msg_fh or croak $!;
1020 chomp(my $commit = do { local $/; <$out_fh> });
1021 close $out_fh or croak $!;
1022 waitpid $pid, 0;
1023 croak $? if $?;
1024 if ($commit !~ /^$::sha1$/o) {
1025 die "Failed to commit, invalid sha1: $commit\n";
1028 command_noisy('update-ref',$self->refname, $commit);
1029 $self->rev_db_set($log_entry->{revision}, $commit);
1031 $self->{last_rev} = $log_entry->{revision};
1032 $self->{last_commit} = $commit;
1033 print "r$log_entry->{revision} = $commit ($self->{ref_id})\n";
1034 return $commit;
1037 sub revisions_eq {
1038 my ($self, $r0, $r1) = @_;
1039 return 1 if $r0 == $r1;
1040 my $nr = 0;
1041 $self->ra->get_log([$self->{path}], $r0, $r1,
1042 0, 0, 1, sub { $nr++ });
1043 return 0 if ($nr > 1);
1044 return 1;
1047 sub match_paths {
1048 my ($self, $paths) = @_;
1049 return 1 if $paths->{'/'};
1050 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\/?/;
1051 grep /$self->{path_regex}/, keys %$paths and return 1;
1052 my $c = '';
1053 foreach (split m#/#, $self->rel_path) {
1054 $c .= "/$_";
1055 return 1 if $paths->{$c};
1057 return 0;
1060 sub find_parent_branch {
1061 my ($self, $paths, $rev) = @_;
1062 return undef unless $::_follow_parent;
1063 unless (defined $paths) {
1064 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
1065 sub { $paths = dup_changed_paths($_[0]) });
1067 return undef unless defined $paths;
1069 # look for a parent from another branch:
1070 my @b_path_components = split m#/#, $self->rel_path;
1071 my @a_path_components;
1072 my $i;
1073 while (@b_path_components) {
1074 $i = $paths->{'/'.join('/', @b_path_components)};
1075 last if $i;
1076 unshift(@a_path_components, pop(@b_path_components));
1078 goto not_found unless defined $i;
1079 my $branch_from = $i->{copyfrom_path} or goto not_found;
1080 if (@a_path_components) {
1081 print STDERR "branch_from: $branch_from => ";
1082 $branch_from .= '/'.join('/', @a_path_components);
1083 print STDERR $branch_from, "\n";
1085 my $r = $i->{copyfrom_rev};
1086 my $repos_root = $self->ra->{repos_root};
1087 my $url = $self->ra->{url};
1088 my $new_url = $repos_root . $branch_from;
1089 print STDERR "Found possible branch point: ",
1090 "$new_url => ", $self->full_url, ", $r\n";
1091 $branch_from =~ s#^/##;
1092 my $remotes = read_all_remotes();
1093 my $gs;
1094 foreach my $repo_id (keys %$remotes) {
1095 my $u = $remotes->{$repo_id}->{url} or next;
1096 next if $url ne $u;
1097 my $fetch = $remotes->{$repo_id}->{fetch};
1098 foreach my $f (keys %$fetch) {
1099 next if $f ne $branch_from;
1100 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1101 last;
1103 last if $gs;
1105 unless ($gs) {
1106 my $ref_id = $self->{ref_id};
1107 $ref_id =~ s/\@\d+$//;
1108 $ref_id .= "\@$r";
1109 # just grow a tail if we're not unique enough :x
1110 $ref_id .= '-' while find_ref($ref_id);
1111 print STDERR "Initializing parent: $ref_id\n";
1112 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1114 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1115 if ($::_follow_parent && (!defined $r0 || !defined $parent)) {
1116 $gs->fetch(0, $r);
1117 ($r0, $parent) = $gs->last_rev_commit;
1119 if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1120 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1121 $self->assert_index_clean($parent);
1122 my $ed;
1123 if ($self->ra->can_do_switch) {
1124 print STDERR "Following parent with do_switch\n";
1125 # do_switch works with svn/trunk >= r22312, but that
1126 # is not included with SVN 1.4.3 (the latest version
1127 # at the moment), so we can't rely on it
1128 $self->{last_commit} = $parent;
1129 $ed = SVN::Git::Fetcher->new($self);
1130 $gs->ra->gs_do_switch($r0, $rev, $gs,
1131 $self->full_url, $ed)
1132 or die "SVN connection failed somewhere...\n";
1133 } else {
1134 print STDERR "Following parent with do_update\n";
1135 $ed = SVN::Git::Fetcher->new($self);
1136 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1137 or die "SVN connection failed somewhere...\n";
1139 print STDERR "Successfully followed parent\n";
1140 $ed->{new_fetch} = 1;
1141 return $self->make_log_entry($rev, [$parent], $ed);
1143 not_found:
1144 print STDERR "Branch parent for path: '/",
1145 $self->rel_path, "' @ r$rev not found:\n";
1146 return undef unless $paths;
1147 print STDERR "Changed paths:\n";
1148 foreach my $x (sort keys %$paths) {
1149 my $p = $paths->{$x};
1150 print STDERR "\t$p->{action}\t$x";
1151 if ($p->{copyfrom_path}) {
1152 print STDERR "(from $p->{copyfrom_path}: ",
1153 "$p->{copyfrom_rev})";
1155 print STDERR "\n";
1157 print STDERR '-'x72, "\n";
1158 return undef;
1161 sub do_fetch {
1162 my ($self, $paths, $rev) = @_;
1163 my $ed;
1164 my ($last_rev, @parents);
1165 if ($self->{last_commit}) {
1166 $ed = SVN::Git::Fetcher->new($self);
1167 $last_rev = $self->{last_rev};
1168 $ed->{c} = $self->{last_commit};
1169 @parents = ($self->{last_commit});
1170 } else {
1171 $last_rev = $rev;
1172 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1173 return $log_entry;
1175 $ed = SVN::Git::Fetcher->new($self);
1176 $ed->{new_fetch} = 1;
1178 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1179 die "SVN connection failed somewhere...\n";
1181 $self->make_log_entry($rev, \@parents, $ed);
1184 sub get_untracked {
1185 my ($self, $ed) = @_;
1186 my @out;
1187 my $h = $ed->{empty};
1188 foreach (sort keys %$h) {
1189 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1190 push @out, " $act: " . uri_encode($_);
1191 warn "W: $act: $_\n";
1193 foreach my $t (qw/dir_prop file_prop/) {
1194 $h = $ed->{$t} or next;
1195 foreach my $path (sort keys %$h) {
1196 my $ppath = $path eq '' ? '.' : $path;
1197 foreach my $prop (sort keys %{$h->{$path}}) {
1198 next if $SKIP_PROP{$prop};
1199 my $v = $h->{$path}->{$prop};
1200 my $t_ppath_prop = "$t: " .
1201 uri_encode($ppath) . ' ' .
1202 uri_encode($prop);
1203 if (defined $v) {
1204 push @out, " +$t_ppath_prop " .
1205 uri_encode($v);
1206 } else {
1207 push @out, " -$t_ppath_prop";
1212 foreach my $t (qw/absent_file absent_directory/) {
1213 $h = $ed->{$t} or next;
1214 foreach my $parent (sort keys %$h) {
1215 foreach my $path (sort @{$h->{$parent}}) {
1216 push @out, " $t: " .
1217 uri_encode("$parent/$path");
1218 warn "W: $t: $parent/$path ",
1219 "Insufficient permissions?\n";
1223 \@out;
1226 sub parse_svn_date {
1227 my $date = shift || return '+0000 1970-01-01 00:00:00';
1228 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1229 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1230 croak "Unable to parse date: $date\n";
1231 "+0000 $Y-$m-$d $H:$M:$S";
1234 sub check_author {
1235 my ($author) = @_;
1236 if (!defined $author || length $author == 0) {
1237 $author = '(no author)';
1239 if (defined $::_authors && ! defined $::users{$author}) {
1240 die "Author: $author not defined in $::_authors file\n";
1242 $author;
1245 sub make_log_entry {
1246 my ($self, $rev, $parents, $ed) = @_;
1247 my $untracked = $self->get_untracked($ed);
1249 return undef if (! $ed->{new_fetch} && ! $ed->{nr} && ! @$untracked);
1251 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1252 print $un "r$rev\n" or croak $!;
1253 print $un $_, "\n" foreach @$untracked;
1254 my %log_entry = ( parents => $parents || [], revision => $rev,
1255 log => '');
1256 my $rp = $self->ra->rev_proplist($rev);
1257 foreach (sort keys %$rp) {
1258 my $v = $rp->{$_};
1259 if (/^svn:(author|date|log)$/) {
1260 $log_entry{$1} = $v;
1261 } else {
1262 print $un " rev_prop: ", uri_encode($_), ' ',
1263 uri_encode($v), "\n";
1266 close $un or croak $!;
1268 $log_entry{date} = parse_svn_date($log_entry{date});
1269 $log_entry{author} = check_author($log_entry{author});
1270 $log_entry{log} .= "\n";
1271 \%log_entry;
1274 sub fetch {
1275 my ($self, $min_rev, $max_rev, @parents) = @_;
1276 my ($last_rev, $last_commit) = $self->last_rev_commit;
1277 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1278 return if ($base > $head);
1279 $self->ra->gs_fetch_loop_common($base, $head, $self);
1282 sub set_tree_cb {
1283 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1284 # TODO: enable and test optimized commits:
1285 if (0 && $rev == ($self->{last_rev} + 1)) {
1286 $log_entry->{revision} = $rev;
1287 $log_entry->{author} = $author;
1288 $self->do_git_commit($log_entry, "$rev=$tree");
1289 } else {
1290 $self->{inject_parents} = { $rev => $tree };
1291 $self->fetch(undef, undef);
1295 sub set_tree {
1296 my ($self, $tree) = (shift, shift);
1297 my $log_entry = ::get_commit_entry($tree);
1298 unless ($self->{last_rev}) {
1299 fatal("Must have an existing revision to commit\n");
1301 my %ed_opts = ( r => $self->{last_rev},
1302 log => $log_entry->{log},
1303 ra => $self->ra,
1304 tree_a => $self->{last_commit},
1305 tree_b => $tree,
1306 editor_cb => sub {
1307 $self->set_tree_cb($log_entry, $tree, @_) },
1308 svn_path => $self->{path} );
1309 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1310 print "No changes\nr$self->{last_rev} = $tree\n";
1314 sub rebuild {
1315 my ($self) = @_;
1316 print "Rebuilding $self->{db_path} ...\n";
1317 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1318 my $latest;
1319 my $full_url = $self->full_url;
1320 my $svn_uuid;
1321 while (<$rev_list>) {
1322 chomp;
1323 my $c = $_;
1324 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1325 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1327 # ignore merges (from set-tree)
1328 next if (!defined $rev || !$uuid);
1330 # if we merged or otherwise started elsewhere, this is
1331 # how we break out of it
1332 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1333 ($full_url && $url && ($url ne $full_url))) {
1334 next;
1336 $latest ||= $rev;
1337 $svn_uuid ||= $uuid;
1339 $self->rev_db_set($rev, $c);
1340 print "r$rev = $c\n";
1342 command_close_pipe($rev_list, $ctx);
1343 print "Done rebuilding $self->{db_path}\n";
1346 # rev_db:
1347 # Tie::File seems to be prone to offset errors if revisions get sparse,
1348 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1349 # one of my favorite modules is out :< Next up would be one of the DBM
1350 # modules, but I'm not sure which is most portable... So I'll just
1351 # go with something that's plain-text, but still capable of
1352 # being randomly accessed. So here's my ultra-simple fixed-width
1353 # database. All records are 40 characters + "\n", so it's easy to seek
1354 # to a revision: (41 * rev) is the byte offset.
1355 # A record of 40 0s denotes an empty revision.
1356 # And yes, it's still pretty fast (faster than Tie::File).
1358 sub rev_db_set {
1359 my ($self, $rev, $commit) = @_;
1360 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1361 open my $fh, '+<', $self->{db_path} or croak $!;
1362 my $offset = $rev * 41;
1363 # assume that append is the common case:
1364 seek $fh, 0, 2 or croak $!;
1365 my $pos = tell $fh;
1366 if ($pos < $offset) {
1367 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1368 or croak $!;
1370 seek $fh, $offset, 0 or croak $!;
1371 print $fh $commit,"\n" or croak $!;
1372 close $fh or croak $!;
1375 sub rev_db_get {
1376 my ($self, $rev) = @_;
1377 my $ret;
1378 my $offset = $rev * 41;
1379 open my $fh, '<', $self->{db_path} or croak $!;
1380 if (seek $fh, $offset, 0) {
1381 $ret = readline $fh;
1382 if (defined $ret) {
1383 chomp $ret;
1384 $ret = undef if ($ret =~ /^0{40}$/);
1387 close $fh or croak $!;
1388 $ret;
1391 sub find_rev_before {
1392 my ($self, $rev, $eq_ok) = @_;
1393 --$rev unless $eq_ok;
1394 while ($rev > 0) {
1395 if (my $c = $self->rev_db_get($rev)) {
1396 return ($rev, $c);
1398 --$rev;
1400 return (undef, undef);
1403 sub _new {
1404 my ($class, $repo_id, $ref_id, $path) = @_;
1405 unless (defined $repo_id && length $repo_id) {
1406 $repo_id = $Git::SVN::default_repo_id;
1408 unless (defined $ref_id && length $ref_id) {
1409 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1411 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1412 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1413 $_[3] = $path = '' unless (defined $path);
1414 mkpath([$dir]);
1415 unless (-f "$dir/.rev_db") {
1416 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1417 close $fh or croak $!;
1419 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1420 path => $path,
1421 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1424 sub uri_encode {
1425 my ($f) = @_;
1426 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1430 package Git::SVN::Prompt;
1431 use strict;
1432 use warnings;
1433 require SVN::Core;
1434 use vars qw/$_no_auth_cache $_username/;
1436 sub simple {
1437 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1438 $may_save = undef if $_no_auth_cache;
1439 $default_username = $_username if defined $_username;
1440 if (defined $default_username && length $default_username) {
1441 if (defined $realm && length $realm) {
1442 print STDERR "Authentication realm: $realm\n";
1443 STDERR->flush;
1445 $cred->username($default_username);
1446 } else {
1447 username($cred, $realm, $may_save, $pool);
1449 $cred->password(_read_password("Password for '" .
1450 $cred->username . "': ", $realm));
1451 $cred->may_save($may_save);
1452 $SVN::_Core::SVN_NO_ERROR;
1455 sub ssl_server_trust {
1456 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1457 $may_save = undef if $_no_auth_cache;
1458 print STDERR "Error validating server certificate for '$realm':\n";
1459 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1460 print STDERR " - The certificate is not issued by a trusted ",
1461 "authority. Use the\n",
1462 " fingerprint to validate the certificate manually!\n";
1464 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1465 print STDERR " - The certificate hostname does not match.\n";
1467 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1468 print STDERR " - The certificate is not yet valid.\n";
1470 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1471 print STDERR " - The certificate has expired.\n";
1473 if ($failures & $SVN::Auth::SSL::OTHER) {
1474 print STDERR " - The certificate has an unknown error.\n";
1476 printf STDERR
1477 "Certificate information:\n".
1478 " - Hostname: %s\n".
1479 " - Valid: from %s until %s\n".
1480 " - Issuer: %s\n".
1481 " - Fingerprint: %s\n",
1482 map $cert_info->$_, qw(hostname valid_from valid_until
1483 issuer_dname fingerprint);
1484 my $choice;
1485 prompt:
1486 print STDERR $may_save ?
1487 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1488 "(R)eject or accept (t)emporarily? ";
1489 STDERR->flush;
1490 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1491 if ($choice =~ /^t$/i) {
1492 $cred->may_save(undef);
1493 } elsif ($choice =~ /^r$/i) {
1494 return -1;
1495 } elsif ($may_save && $choice =~ /^p$/i) {
1496 $cred->may_save($may_save);
1497 } else {
1498 goto prompt;
1500 $cred->accepted_failures($failures);
1501 $SVN::_Core::SVN_NO_ERROR;
1504 sub ssl_client_cert {
1505 my ($cred, $realm, $may_save, $pool) = @_;
1506 $may_save = undef if $_no_auth_cache;
1507 print STDERR "Client certificate filename: ";
1508 STDERR->flush;
1509 chomp(my $filename = <STDIN>);
1510 $cred->cert_file($filename);
1511 $cred->may_save($may_save);
1512 $SVN::_Core::SVN_NO_ERROR;
1515 sub ssl_client_cert_pw {
1516 my ($cred, $realm, $may_save, $pool) = @_;
1517 $may_save = undef if $_no_auth_cache;
1518 $cred->password(_read_password("Password: ", $realm));
1519 $cred->may_save($may_save);
1520 $SVN::_Core::SVN_NO_ERROR;
1523 sub username {
1524 my ($cred, $realm, $may_save, $pool) = @_;
1525 $may_save = undef if $_no_auth_cache;
1526 if (defined $realm && length $realm) {
1527 print STDERR "Authentication realm: $realm\n";
1529 my $username;
1530 if (defined $_username) {
1531 $username = $_username;
1532 } else {
1533 print STDERR "Username: ";
1534 STDERR->flush;
1535 chomp($username = <STDIN>);
1537 $cred->username($username);
1538 $cred->may_save($may_save);
1539 $SVN::_Core::SVN_NO_ERROR;
1542 sub _read_password {
1543 my ($prompt, $realm) = @_;
1544 print STDERR $prompt;
1545 STDERR->flush;
1546 require Term::ReadKey;
1547 Term::ReadKey::ReadMode('noecho');
1548 my $password = '';
1549 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1550 last if $key =~ /[\012\015]/; # \n\r
1551 $password .= $key;
1553 Term::ReadKey::ReadMode('restore');
1554 print STDERR "\n";
1555 STDERR->flush;
1556 $password;
1559 package main;
1562 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1563 $SVN::Node::dir.$SVN::Node::unknown.
1564 $SVN::Node::none.$SVN::Node::file.
1565 $SVN::Node::dir.$SVN::Node::unknown.
1566 $SVN::Auth::SSL::CNMISMATCH.
1567 $SVN::Auth::SSL::NOTYETVALID.
1568 $SVN::Auth::SSL::EXPIRED.
1569 $SVN::Auth::SSL::UNKNOWNCA.
1570 $SVN::Auth::SSL::OTHER;
1573 package SVN::Git::Fetcher;
1574 use vars qw/@ISA/;
1575 use strict;
1576 use warnings;
1577 use Carp qw/croak/;
1578 use IO::File qw//;
1579 use Digest::MD5;
1581 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1582 sub new {
1583 my ($class, $git_svn) = @_;
1584 my $self = SVN::Delta::Editor->new;
1585 bless $self, $class;
1586 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1587 $self->{empty} = {};
1588 $self->{dir_prop} = {};
1589 $self->{file_prop} = {};
1590 $self->{absent_dir} = {};
1591 $self->{absent_file} = {};
1592 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1593 $self;
1596 sub set_path_strip {
1597 my ($self, $path) = @_;
1598 $self->{path_strip} = qr/^\Q$path\E\/?/;
1601 sub open_root {
1602 { path => '' };
1605 sub open_directory {
1606 my ($self, $path, $pb, $rev) = @_;
1607 { path => $path };
1610 sub git_path {
1611 my ($self, $path) = @_;
1612 if ($self->{path_strip}) {
1613 $path =~ s!$self->{path_strip}!! or
1614 die "Failed to strip path '$path' ($self->{path_strip})\n";
1616 $path;
1619 sub delete_entry {
1620 my ($self, $path, $rev, $pb) = @_;
1622 my $gpath = $self->git_path($path);
1623 return undef if ($gpath eq '');
1625 # remove entire directories.
1626 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1627 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1628 -r --name-only -z/,
1629 $self->{c}, '--', $gpath);
1630 local $/ = "\0";
1631 while (<$ls>) {
1632 chomp;
1633 $self->{gii}->remove($_);
1634 print "\tD\t$_\n" unless $self->{q};
1636 print "\tD\t$gpath/\n" unless $self->{q};
1637 command_close_pipe($ls, $ctx);
1638 $self->{empty}->{$path} = 0
1639 } else {
1640 $self->{gii}->remove($gpath);
1641 print "\tD\t$gpath\n" unless $self->{q};
1643 undef;
1646 sub open_file {
1647 my ($self, $path, $pb, $rev) = @_;
1648 my $gpath = $self->git_path($path);
1649 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1650 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1651 unless (defined $mode && defined $blob) {
1652 die "$path was not found in commit $self->{c} (r$rev)\n";
1654 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1655 pool => SVN::Pool->new, action => 'M' };
1658 sub add_file {
1659 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1660 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1661 delete $self->{empty}->{$dir};
1662 { path => $path, mode_a => 100644, mode_b => 100644,
1663 pool => SVN::Pool->new, action => 'A' };
1666 sub add_directory {
1667 my ($self, $path, $cp_path, $cp_rev) = @_;
1668 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1669 delete $self->{empty}->{$dir};
1670 $self->{empty}->{$path} = 1;
1671 { path => $path };
1674 sub change_dir_prop {
1675 my ($self, $db, $prop, $value) = @_;
1676 $self->{dir_prop}->{$db->{path}} ||= {};
1677 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1678 undef;
1681 sub absent_directory {
1682 my ($self, $path, $pb) = @_;
1683 $self->{absent_dir}->{$pb->{path}} ||= [];
1684 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1685 undef;
1688 sub absent_file {
1689 my ($self, $path, $pb) = @_;
1690 $self->{absent_file}->{$pb->{path}} ||= [];
1691 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1692 undef;
1695 sub change_file_prop {
1696 my ($self, $fb, $prop, $value) = @_;
1697 if ($prop eq 'svn:executable') {
1698 if ($fb->{mode_b} != 120000) {
1699 $fb->{mode_b} = defined $value ? 100755 : 100644;
1701 } elsif ($prop eq 'svn:special') {
1702 $fb->{mode_b} = defined $value ? 120000 : 100644;
1703 } else {
1704 $self->{file_prop}->{$fb->{path}} ||= {};
1705 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1707 undef;
1710 sub apply_textdelta {
1711 my ($self, $fb, $exp) = @_;
1712 my $fh = IO::File->new_tmpfile;
1713 $fh->autoflush(1);
1714 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1715 # (but $base does not,) so dup() it for reading in close_file
1716 open my $dup, '<&', $fh or croak $!;
1717 my $base = IO::File->new_tmpfile;
1718 $base->autoflush(1);
1719 if ($fb->{blob}) {
1720 defined (my $pid = fork) or croak $!;
1721 if (!$pid) {
1722 open STDOUT, '>&', $base or croak $!;
1723 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1724 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1726 waitpid $pid, 0;
1727 croak $? if $?;
1729 if (defined $exp) {
1730 seek $base, 0, 0 or croak $!;
1731 my $md5 = Digest::MD5->new;
1732 $md5->addfile($base);
1733 my $got = $md5->hexdigest;
1734 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1735 "expected: $exp\n",
1736 " got: $got\n" if ($got ne $exp);
1739 seek $base, 0, 0 or croak $!;
1740 $fb->{fh} = $dup;
1741 $fb->{base} = $base;
1742 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1745 sub close_file {
1746 my ($self, $fb, $exp) = @_;
1747 my $hash;
1748 my $path = $self->git_path($fb->{path});
1749 if (my $fh = $fb->{fh}) {
1750 seek($fh, 0, 0) or croak $!;
1751 my $md5 = Digest::MD5->new;
1752 $md5->addfile($fh);
1753 my $got = $md5->hexdigest;
1754 die "Checksum mismatch: $path\n",
1755 "expected: $exp\n got: $got\n" if ($got ne $exp);
1756 seek($fh, 0, 0) or croak $!;
1757 if ($fb->{mode_b} == 120000) {
1758 read($fh, my $buf, 5) == 5 or croak $!;
1759 $buf eq 'link ' or die "$path has mode 120000",
1760 "but is not a link\n";
1762 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1763 if (!$pid) {
1764 open STDIN, '<&', $fh or croak $!;
1765 exec qw/git-hash-object -w --stdin/ or croak $!;
1767 chomp($hash = do { local $/; <$out> });
1768 close $out or croak $!;
1769 close $fh or croak $!;
1770 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1771 close $fb->{base} or croak $!;
1772 } else {
1773 $hash = $fb->{blob} or die "no blob information\n";
1775 $fb->{pool}->clear;
1776 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1777 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1778 undef;
1781 sub abort_edit {
1782 my $self = shift;
1783 $self->{nr} = $self->{gii}->{nr};
1784 delete $self->{gii};
1785 $self->SUPER::abort_edit(@_);
1788 sub close_edit {
1789 my $self = shift;
1790 $self->{git_commit_ok} = 1;
1791 $self->{nr} = $self->{gii}->{nr};
1792 delete $self->{gii};
1793 $self->SUPER::close_edit(@_);
1796 package SVN::Git::Editor;
1797 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1798 use strict;
1799 use warnings;
1800 use Carp qw/croak/;
1801 use IO::File;
1802 use Digest::MD5;
1804 sub new {
1805 my ($class, $opts) = @_;
1806 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1807 die "$_ required!\n" unless (defined $opts->{$_});
1810 my $pool = SVN::Pool->new;
1811 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1812 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1813 $opts->{r}, $mods);
1815 # $opts->{ra} functions should not be used after this:
1816 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
1817 $opts->{editor_cb}, $pool);
1818 my $self = SVN::Delta::Editor->new(@ce, $pool);
1819 bless $self, $class;
1820 foreach (qw/svn_path r tree_a tree_b/) {
1821 $self->{$_} = $opts->{$_};
1823 $self->{url} = $opts->{ra}->{url};
1824 $self->{mods} = $mods;
1825 $self->{types} = $types;
1826 $self->{pool} = $pool;
1827 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1828 $self->{rm} = { };
1829 $self->{path_prefix} = length $self->{svn_path} ?
1830 "$self->{svn_path}/" : '';
1831 return $self;
1834 sub generate_diff {
1835 my ($tree_a, $tree_b) = @_;
1836 my @diff_tree = qw(diff-tree -z -r);
1837 if ($_cp_similarity) {
1838 push @diff_tree, "-C$_cp_similarity";
1839 } else {
1840 push @diff_tree, '-C';
1842 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1843 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1844 push @diff_tree, $tree_a, $tree_b;
1845 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1846 local $/ = "\0";
1847 my $state = 'meta';
1848 my @mods;
1849 while (<$diff_fh>) {
1850 chomp $_; # this gets rid of the trailing "\0"
1851 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1852 $::sha1\s($::sha1)\s
1853 ([MTCRAD])\d*$/xo) {
1854 push @mods, { mode_a => $1, mode_b => $2,
1855 sha1_b => $3, chg => $4 };
1856 if ($4 =~ /^(?:C|R)$/) {
1857 $state = 'file_a';
1858 } else {
1859 $state = 'file_b';
1861 } elsif ($state eq 'file_a') {
1862 my $x = $mods[$#mods] or croak "Empty array\n";
1863 if ($x->{chg} !~ /^(?:C|R)$/) {
1864 croak "Error parsing $_, $x->{chg}\n";
1866 $x->{file_a} = $_;
1867 $state = 'file_b';
1868 } elsif ($state eq 'file_b') {
1869 my $x = $mods[$#mods] or croak "Empty array\n";
1870 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1871 croak "Error parsing $_, $x->{chg}\n";
1873 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1874 croak "Error parsing $_, $x->{chg}\n";
1876 $x->{file_b} = $_;
1877 $state = 'meta';
1878 } else {
1879 croak "Error parsing $_\n";
1882 command_close_pipe($diff_fh, $ctx);
1883 \@mods;
1886 sub check_diff_paths {
1887 my ($ra, $pfx, $rev, $mods) = @_;
1888 my %types;
1889 $pfx .= '/' if length $pfx;
1891 sub type_diff_paths {
1892 my ($ra, $types, $path, $rev) = @_;
1893 my @p = split m#/+#, $path;
1894 my $c = shift @p;
1895 unless (defined $types->{$c}) {
1896 $types->{$c} = $ra->check_path($c, $rev);
1898 while (@p) {
1899 $c .= '/' . shift @p;
1900 next if defined $types->{$c};
1901 $types->{$c} = $ra->check_path($c, $rev);
1905 foreach my $m (@$mods) {
1906 foreach my $f (qw/file_a file_b/) {
1907 next unless defined $m->{$f};
1908 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
1909 if (length $pfx.$dir && ! defined $types{$dir}) {
1910 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
1914 \%types;
1917 sub split_path {
1918 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1921 sub repo_path {
1922 my ($self, $path) = @_;
1923 $self->{path_prefix}.(defined $path ? $path : '');
1926 sub url_path {
1927 my ($self, $path) = @_;
1928 $self->{url} . '/' . $self->repo_path($path);
1931 sub rmdirs {
1932 my ($self) = @_;
1933 my $rm = $self->{rm};
1934 delete $rm->{''}; # we never delete the url we're tracking
1935 return unless %$rm;
1937 foreach (keys %$rm) {
1938 my @d = split m#/#, $_;
1939 my $c = shift @d;
1940 $rm->{$c} = 1;
1941 while (@d) {
1942 $c .= '/' . shift @d;
1943 $rm->{$c} = 1;
1946 delete $rm->{$self->{svn_path}};
1947 delete $rm->{''}; # we never delete the url we're tracking
1948 return unless %$rm;
1950 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
1951 $self->{tree_b});
1952 local $/ = "\0";
1953 while (<$fh>) {
1954 chomp;
1955 my @dn = split m#/#, $_;
1956 while (pop @dn) {
1957 delete $rm->{join '/', @dn};
1959 unless (%$rm) {
1960 close $fh;
1961 return;
1964 command_close_pipe($fh, $ctx);
1966 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1967 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1968 $self->close_directory($bat->{$d}, $p);
1969 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
1970 print "\tD+\t$d/\n" unless $::_q;
1971 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1972 delete $bat->{$d};
1976 sub open_or_add_dir {
1977 my ($self, $full_path, $baton) = @_;
1978 my $t = $self->{types}->{$full_path};
1979 if (!defined $t) {
1980 die "$full_path not known in r$self->{r} or we have a bug!\n";
1982 if ($t == $SVN::Node::none) {
1983 return $self->add_directory($full_path, $baton,
1984 undef, -1, $self->{pool});
1985 } elsif ($t == $SVN::Node::dir) {
1986 return $self->open_directory($full_path, $baton,
1987 $self->{r}, $self->{pool});
1989 print STDERR "$full_path already exists in repository at ",
1990 "r$self->{r} and it is not a directory (",
1991 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1992 exit 1;
1995 sub ensure_path {
1996 my ($self, $path) = @_;
1997 my $bat = $self->{bat};
1998 my $repo_path = $self->repo_path($path);
1999 return $bat->{''} unless (length $repo_path);
2000 my @p = split m#/+#, $repo_path;
2001 my $c = shift @p;
2002 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2003 while (@p) {
2004 my $c0 = $c;
2005 $c .= '/' . shift @p;
2006 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2008 return $bat->{$c};
2011 sub A {
2012 my ($self, $m) = @_;
2013 my ($dir, $file) = split_path($m->{file_b});
2014 my $pbat = $self->ensure_path($dir);
2015 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2016 undef, -1);
2017 print "\tA\t$m->{file_b}\n" unless $::_q;
2018 $self->chg_file($fbat, $m);
2019 $self->close_file($fbat,undef,$self->{pool});
2022 sub C {
2023 my ($self, $m) = @_;
2024 my ($dir, $file) = split_path($m->{file_b});
2025 my $pbat = $self->ensure_path($dir);
2026 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2027 $self->url_path($m->{file_a}), $self->{r});
2028 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2029 $self->chg_file($fbat, $m);
2030 $self->close_file($fbat,undef,$self->{pool});
2033 sub delete_entry {
2034 my ($self, $path, $pbat) = @_;
2035 my $rpath = $self->repo_path($path);
2036 my ($dir, $file) = split_path($rpath);
2037 $self->{rm}->{$dir} = 1;
2038 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2041 sub R {
2042 my ($self, $m) = @_;
2043 my ($dir, $file) = split_path($m->{file_b});
2044 my $pbat = $self->ensure_path($dir);
2045 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2046 $self->url_path($m->{file_a}), $self->{r});
2047 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2048 $self->chg_file($fbat, $m);
2049 $self->close_file($fbat,undef,$self->{pool});
2051 ($dir, $file) = split_path($m->{file_a});
2052 $pbat = $self->ensure_path($dir);
2053 $self->delete_entry($m->{file_a}, $pbat);
2056 sub M {
2057 my ($self, $m) = @_;
2058 my ($dir, $file) = split_path($m->{file_b});
2059 my $pbat = $self->ensure_path($dir);
2060 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2061 $pbat,$self->{r},$self->{pool});
2062 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2063 $self->chg_file($fbat, $m);
2064 $self->close_file($fbat,undef,$self->{pool});
2067 sub T { shift->M(@_) }
2069 sub change_file_prop {
2070 my ($self, $fbat, $pname, $pval) = @_;
2071 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2074 sub chg_file {
2075 my ($self, $fbat, $m) = @_;
2076 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2077 $self->change_file_prop($fbat,'svn:executable','*');
2078 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2079 $self->change_file_prop($fbat,'svn:executable',undef);
2081 my $fh = IO::File->new_tmpfile or croak $!;
2082 if ($m->{mode_b} =~ /^120/) {
2083 print $fh 'link ' or croak $!;
2084 $self->change_file_prop($fbat,'svn:special','*');
2085 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2086 $self->change_file_prop($fbat,'svn:special',undef);
2088 defined(my $pid = fork) or croak $!;
2089 if (!$pid) {
2090 open STDOUT, '>&', $fh or croak $!;
2091 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2093 waitpid $pid, 0;
2094 croak $? if $?;
2095 $fh->flush == 0 or croak $!;
2096 seek $fh, 0, 0 or croak $!;
2098 my $md5 = Digest::MD5->new;
2099 $md5->addfile($fh) or croak $!;
2100 seek $fh, 0, 0 or croak $!;
2102 my $exp = $md5->hexdigest;
2103 my $pool = SVN::Pool->new;
2104 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2105 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2106 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2107 $pool->clear;
2109 close $fh or croak $!;
2112 sub D {
2113 my ($self, $m) = @_;
2114 my ($dir, $file) = split_path($m->{file_b});
2115 my $pbat = $self->ensure_path($dir);
2116 print "\tD\t$m->{file_b}\n" unless $::_q;
2117 $self->delete_entry($m->{file_b}, $pbat);
2120 sub close_edit {
2121 my ($self) = @_;
2122 my ($p,$bat) = ($self->{pool}, $self->{bat});
2123 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2124 $self->close_directory($bat->{$_}, $p);
2126 $self->SUPER::close_edit($p);
2127 $p->clear;
2130 sub abort_edit {
2131 my ($self) = @_;
2132 $self->SUPER::abort_edit($self->{pool});
2135 sub DESTROY {
2136 my $self = shift;
2137 $self->SUPER::DESTROY(@_);
2138 $self->{pool}->clear;
2141 # this drives the editor
2142 sub apply_diff {
2143 my ($self) = @_;
2144 my $mods = $self->{mods};
2145 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2146 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2147 my $f = $m->{chg};
2148 if (defined $o{$f}) {
2149 $self->$f($m);
2150 } else {
2151 fatal("Invalid change type: $f\n");
2154 $self->rmdirs if $_rmdir;
2155 if (@$mods == 0) {
2156 $self->abort_edit;
2157 } else {
2158 $self->close_edit;
2160 return scalar @$mods;
2163 package Git::SVN::Ra;
2164 use vars qw/@ISA $config_dir/;
2165 use strict;
2166 use warnings;
2167 my ($can_do_switch);
2168 my $RA;
2170 BEGIN {
2171 # enforce temporary pool usage for some simple functions
2172 my $e;
2173 foreach (qw/get_latest_revnum rev_proplist get_file
2174 check_path get_dir get_uuid get_repos_root/) {
2175 $e .= "sub $_ {
2176 my \$self = shift;
2177 my \$pool = SVN::Pool->new;
2178 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2179 \$pool->clear;
2180 wantarray ? \@ret : \$ret[0]; }\n";
2182 eval $e;
2185 sub new {
2186 my ($class, $url) = @_;
2187 $url =~ s!/+$!!;
2188 return $RA if ($RA && $RA->{url} eq $url);
2190 SVN::_Core::svn_config_ensure($config_dir, undef);
2191 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2192 SVN::Client::get_simple_provider(),
2193 SVN::Client::get_ssl_server_trust_file_provider(),
2194 SVN::Client::get_simple_prompt_provider(
2195 \&Git::SVN::Prompt::simple, 2),
2196 SVN::Client::get_ssl_client_cert_prompt_provider(
2197 \&Git::SVN::Prompt::ssl_client_cert, 2),
2198 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2199 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2200 SVN::Client::get_username_provider(),
2201 SVN::Client::get_ssl_server_trust_prompt_provider(
2202 \&Git::SVN::Prompt::ssl_server_trust),
2203 SVN::Client::get_username_prompt_provider(
2204 \&Git::SVN::Prompt::username, 2),
2206 my $config = SVN::Core::config_get_config($config_dir);
2207 my $self = SVN::Ra->new(url => $url, auth => $baton,
2208 config => $config,
2209 pool => SVN::Pool->new,
2210 auth_provider_callbacks => $callbacks);
2211 $self->{svn_path} = $url;
2212 $self->{repos_root} = $self->get_repos_root;
2213 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2214 $RA = bless $self, $class;
2217 sub DESTROY {
2218 # do not call the real DESTROY since we store ourselves in $RA
2221 sub get_log {
2222 my ($self, @args) = @_;
2223 my $pool = SVN::Pool->new;
2224 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2225 my $ret = $self->SUPER::get_log(@args, $pool);
2226 $pool->clear;
2227 $ret;
2230 sub get_commit_editor {
2231 my ($self, $log, $cb, $pool) = @_;
2232 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2233 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2236 sub uuid {
2237 my ($self) = @_;
2238 $self->{uuid} ||= $self->get_uuid;
2241 sub gs_do_update {
2242 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2243 my $new = ($rev_a == $rev_b);
2244 my $path = $gs->{path};
2246 my $ta = $self->check_path($path, $rev_a);
2247 my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2248 return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2249 if ($ta == $SVN::Node::none) {
2250 $rev_a = $rev_b;
2251 $new = 1;
2254 my $pool = SVN::Pool->new;
2255 $editor->set_path_strip($path);
2256 my (@pc) = split m#/#, $path;
2257 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2258 1, $editor, $pool);
2259 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2261 # Since we can't rely on svn_ra_reparent being available, we'll
2262 # just have to do some magic with set_path to make it so
2263 # we only want a partial path.
2264 my $sp = '';
2265 my $final = join('/', @pc);
2266 while (@pc) {
2267 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2268 $sp .= '/' if length $sp;
2269 $sp .= shift @pc;
2271 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2273 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2275 $reporter->finish_report($pool);
2276 $pool->clear;
2277 $editor->{git_commit_ok};
2280 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2281 # svn_ra_reparent didn't work before 1.4)
2282 sub gs_do_switch {
2283 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2284 my $path = $gs->{path};
2285 my $pool = SVN::Pool->new;
2287 my $full_url = $self->{url};
2288 my $old_url = $full_url;
2289 $full_url .= "/$path" if length $path;
2290 my ($ra, $reparented);
2291 if ($old_url ne $full_url) {
2292 if ($old_url !~ m#^svn(\+ssh)?://#) {
2293 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2294 $pool);
2295 $self->{url} = $full_url;
2296 $reparented = 1;
2297 } else {
2298 $ra = Git::SVN::Ra->new($full_url);
2301 $ra ||= $self;
2302 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2303 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2304 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2305 $reporter->finish_report($pool);
2307 if ($reparented) {
2308 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2309 $self->{url} = $old_url;
2312 $pool->clear;
2313 $editor->{git_commit_ok};
2316 sub gs_fetch_loop_common {
2317 my ($self, $base, $head, @gs) = @_;
2318 my $inc = 1000;
2319 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2320 my @paths = @gs == 1 ? ($gs[0]->{path}) : ('');
2321 foreach my $gs (@gs) {
2322 if (my $last_commit = $gs->last_commit) {
2323 $gs->assert_index_clean($last_commit);
2326 while (1) {
2327 my @revs;
2328 my $err;
2329 my $err_handler = $SVN::Error::handler;
2330 $SVN::Error::handler = sub {
2331 ($err) = @_;
2332 skip_unknown_revs($err);
2334 $self->get_log(\@paths, $min, $max, 0, 1, 1,
2335 sub { push @revs, [ dup_changed_paths($_[0]), $_[1] ]; });
2336 $SVN::Error::handler = $err_handler;
2338 if (! @revs && $err && $max >= $head) {
2339 print STDERR "Branch probably deleted:\n ",
2340 $err->expanded_message,
2341 "\nWill attempt to follow revisions ",
2342 "r$min .. r$max ",
2343 "committed before the deletion\n";
2344 @revs = map { [ undef, $_ ] } ($min .. $max);
2346 foreach (@revs) {
2347 my ($paths, $r) = @$_;
2348 foreach my $gs (@gs) {
2349 if ($paths) {
2350 $gs->match_paths($paths) or next;
2352 my $lr = $gs->last_rev;
2353 next if defined $lr && $lr >= $r;
2354 next if defined $gs->rev_db_get($r);
2355 if (my $log_entry = $gs->do_fetch($paths, $r)) {
2356 $gs->do_git_commit($log_entry);
2360 last if $max >= $head;
2361 $min = $max + 1;
2362 $max += $inc;
2363 $max = $head if ($max > $head);
2367 sub minimize_url {
2368 my ($self) = @_;
2369 return $self->{url} if ($self->{url} eq $self->{repos_root});
2370 my $url = $self->{repos_root};
2371 my @components = split(m!/!, $self->{svn_path});
2372 my $c = '';
2373 do {
2374 $url .= "/$c" if length $c;
2375 eval { (ref $self)->new($url)->get_latest_revnum };
2376 } while ($@ && ($c = shift @components));
2377 $url;
2380 sub can_do_switch {
2381 my $self = shift;
2382 unless (defined $can_do_switch) {
2383 my $pool = SVN::Pool->new;
2384 my $rep = eval {
2385 $self->do_switch(1, '', 0, $self->{url},
2386 SVN::Delta::Editor->new, $pool);
2388 if ($@) {
2389 $can_do_switch = 0;
2390 } else {
2391 $rep->abort_report($pool);
2392 $can_do_switch = 1;
2394 $pool->clear;
2396 $can_do_switch;
2399 sub skip_unknown_revs {
2400 my ($err) = @_;
2401 my $errno = $err->apr_err();
2402 # Maybe the branch we're tracking didn't
2403 # exist when the repo started, so it's
2404 # not an error if it doesn't, just continue
2406 # Wonderfully consistent library, eh?
2407 # 160013 - svn:// and file://
2408 # 175002 - http(s)://
2409 # 175007 - http(s):// (this repo required authorization, too...)
2410 # More codes may be discovered later...
2411 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2412 return;
2414 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2417 # svn_log_changed_path_t objects passed to get_log are likely to be
2418 # overwritten even if only the refs are copied to an external variable,
2419 # so we should dup the structures in their entirety. Using an externally
2420 # passed pool (instead of our temporary and quickly cleared pool in
2421 # Git::SVN::Ra) does not help matters at all...
2422 sub dup_changed_paths {
2423 my ($paths) = @_;
2424 return undef unless $paths;
2425 my %ret;
2426 foreach my $p (keys %$paths) {
2427 my $i = $paths->{$p};
2428 my %s = map { $_ => $i->$_ }
2429 qw/copyfrom_path copyfrom_rev action/;
2430 $ret{$p} = \%s;
2432 \%ret;
2435 package Git::SVN::Log;
2436 use strict;
2437 use warnings;
2438 use POSIX qw/strftime/;
2439 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2440 %rusers $show_commit $incremental/;
2441 my $l_fmt;
2443 sub cmt_showable {
2444 my ($c) = @_;
2445 return 1 if defined $c->{r};
2446 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2447 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2448 my @log = command(qw/cat-file commit/, $c->{c});
2449 shift @log while ($log[0] ne "\n");
2450 shift @log;
2451 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2453 (undef, $c->{r}, undef) = ::extract_metadata(
2454 (grep(/^git-svn-id: /, @log))[-1]);
2456 return defined $c->{r};
2459 sub log_use_color {
2460 return 1 if $color;
2461 my ($dc, $dcvar);
2462 $dcvar = 'color.diff';
2463 $dc = `git-config --get $dcvar`;
2464 if ($dc eq '') {
2465 # nothing at all; fallback to "diff.color"
2466 $dcvar = 'diff.color';
2467 $dc = `git-config --get $dcvar`;
2469 chomp($dc);
2470 if ($dc eq 'auto') {
2471 my $pc;
2472 $pc = `git-config --get color.pager`;
2473 if ($pc eq '') {
2474 # does not have it -- fallback to pager.color
2475 $pc = `git-config --bool --get pager.color`;
2477 else {
2478 $pc = `git-config --bool --get color.pager`;
2479 if ($?) {
2480 $pc = 'false';
2483 chomp($pc);
2484 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2485 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2487 return 0;
2489 return 0 if $dc eq 'never';
2490 return 1 if $dc eq 'always';
2491 chomp($dc = `git-config --bool --get $dcvar`);
2492 return ($dc eq 'true');
2495 sub git_svn_log_cmd {
2496 my ($r_min, $r_max) = @_;
2497 my $gs = Git::SVN->_new;
2498 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2499 $gs->refname);
2500 push @cmd, '-r' unless $non_recursive;
2501 push @cmd, qw/--raw --name-status/ if $verbose;
2502 push @cmd, '--color' if log_use_color();
2503 return @cmd unless defined $r_max;
2504 if ($r_max == $r_min) {
2505 push @cmd, '--max-count=1';
2506 if (my $c = $gs->rev_db_get($r_max)) {
2507 push @cmd, $c;
2509 } else {
2510 my ($c_min, $c_max);
2511 $c_max = $gs->rev_db_get($r_max);
2512 $c_min = $gs->rev_db_get($r_min);
2513 if (defined $c_min && defined $c_max) {
2514 if ($r_max > $r_max) {
2515 push @cmd, "$c_min..$c_max";
2516 } else {
2517 push @cmd, "$c_max..$c_min";
2519 } elsif ($r_max > $r_min) {
2520 push @cmd, $c_max;
2521 } else {
2522 push @cmd, $c_min;
2525 return @cmd;
2528 # adapted from pager.c
2529 sub config_pager {
2530 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2531 if (!defined $pager) {
2532 $pager = 'less';
2533 } elsif (length $pager == 0 || $pager eq 'cat') {
2534 $pager = undef;
2538 sub run_pager {
2539 return unless -t *STDOUT;
2540 pipe my $rfd, my $wfd or return;
2541 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2542 if (!$pid) {
2543 open STDOUT, '>&', $wfd or
2544 ::fatal "Can't redirect to stdout: $!\n";
2545 return;
2547 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2548 $ENV{LESS} ||= 'FRSX';
2549 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2552 sub tz_to_s_offset {
2553 my ($tz) = @_;
2554 $tz =~ s/(\d\d)$//;
2555 return ($1 * 60) + ($tz * 3600);
2558 sub get_author_info {
2559 my ($dest, $author, $t, $tz) = @_;
2560 $author =~ s/(?:^\s*|\s*$)//g;
2561 $dest->{a_raw} = $author;
2562 my $au;
2563 if ($::_authors) {
2564 $au = $rusers{$author} || undef;
2566 if (!$au) {
2567 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2569 $dest->{t} = $t;
2570 $dest->{tz} = $tz;
2571 $dest->{a} = $au;
2572 # Date::Parse isn't in the standard Perl distro :(
2573 if ($tz =~ s/^\+//) {
2574 $t += tz_to_s_offset($tz);
2575 } elsif ($tz =~ s/^\-//) {
2576 $t -= tz_to_s_offset($tz);
2578 $dest->{t_utc} = $t;
2581 sub process_commit {
2582 my ($c, $r_min, $r_max, $defer) = @_;
2583 if (defined $r_min && defined $r_max) {
2584 if ($r_min == $c->{r} && $r_min == $r_max) {
2585 show_commit($c);
2586 return 0;
2588 return 1 if $r_min == $r_max;
2589 if ($r_min < $r_max) {
2590 # we need to reverse the print order
2591 return 0 if (defined $limit && --$limit < 0);
2592 push @$defer, $c;
2593 return 1;
2595 if ($r_min != $r_max) {
2596 return 1 if ($r_min < $c->{r});
2597 return 1 if ($r_max > $c->{r});
2600 return 0 if (defined $limit && --$limit < 0);
2601 show_commit($c);
2602 return 1;
2605 sub show_commit {
2606 my $c = shift;
2607 if ($oneline) {
2608 my $x = "\n";
2609 if (my $l = $c->{l}) {
2610 while ($l->[0] =~ /^\s*$/) { shift @$l }
2611 $x = $l->[0];
2613 $l_fmt ||= 'A' . length($c->{r});
2614 print 'r',pack($l_fmt, $c->{r}),' | ';
2615 print "$c->{c} | " if $show_commit;
2616 print $x;
2617 } else {
2618 show_commit_normal($c);
2622 sub show_commit_changed_paths {
2623 my ($c) = @_;
2624 return unless $c->{changed};
2625 print "Changed paths:\n", @{$c->{changed}};
2628 sub show_commit_normal {
2629 my ($c) = @_;
2630 print '-' x72, "\nr$c->{r} | ";
2631 print "$c->{c} | " if $show_commit;
2632 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2633 localtime($c->{t_utc})), ' | ';
2634 my $nr_line = 0;
2636 if (my $l = $c->{l}) {
2637 while ($l->[$#$l] eq "\n" && $#$l > 0
2638 && $l->[($#$l - 1)] eq "\n") {
2639 pop @$l;
2641 $nr_line = scalar @$l;
2642 if (!$nr_line) {
2643 print "1 line\n\n\n";
2644 } else {
2645 if ($nr_line == 1) {
2646 $nr_line = '1 line';
2647 } else {
2648 $nr_line .= ' lines';
2650 print $nr_line, "\n";
2651 show_commit_changed_paths($c);
2652 print "\n";
2653 print $_ foreach @$l;
2655 } else {
2656 print "1 line\n";
2657 show_commit_changed_paths($c);
2658 print "\n";
2661 foreach my $x (qw/raw diff/) {
2662 if ($c->{$x}) {
2663 print "\n";
2664 print $_ foreach @{$c->{$x}}
2669 sub cmd_show_log {
2670 my (@args) = @_;
2671 my ($r_min, $r_max);
2672 my $r_last = -1; # prevent dupes
2673 if (defined $TZ) {
2674 $ENV{TZ} = $TZ;
2675 } else {
2676 delete $ENV{TZ};
2678 if (defined $::_revision) {
2679 if ($::_revision =~ /^(\d+):(\d+)$/) {
2680 ($r_min, $r_max) = ($1, $2);
2681 } elsif ($::_revision =~ /^\d+$/) {
2682 $r_min = $r_max = $::_revision;
2683 } else {
2684 ::fatal "-r$::_revision is not supported, use ",
2685 "standard \'git log\' arguments instead\n";
2689 config_pager();
2690 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2691 my $log = command_output_pipe(@args);
2692 run_pager();
2693 my (@k, $c, $d);
2694 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2695 while (<$log>) {
2696 if (/^${esc_color}commit ($::sha1_short)/o) {
2697 my $cmt = $1;
2698 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2699 $r_last = $c->{r};
2700 process_commit($c, $r_min, $r_max, \@k) or
2701 goto out;
2703 $d = undef;
2704 $c = { c => $cmt };
2705 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2706 get_author_info($c, $1, $2, $3);
2707 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2708 # ignore
2709 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2710 push @{$c->{raw}}, $_;
2711 } elsif (/^${esc_color}[ACRMDT]\t/) {
2712 # we could add $SVN->{svn_path} here, but that requires
2713 # remote access at the moment (repo_path_split)...
2714 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2715 push @{$c->{changed}}, $_;
2716 } elsif (/^${esc_color}diff /o) {
2717 $d = 1;
2718 push @{$c->{diff}}, $_;
2719 } elsif ($d) {
2720 push @{$c->{diff}}, $_;
2721 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2722 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2723 } elsif (s/^${esc_color} //o) {
2724 push @{$c->{l}}, $_;
2727 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2728 $r_last = $c->{r};
2729 process_commit($c, $r_min, $r_max, \@k);
2731 if (@k) {
2732 my $swap = $r_max;
2733 $r_max = $r_min;
2734 $r_min = $swap;
2735 process_commit($_, $r_min, $r_max) foreach reverse @k;
2737 out:
2738 close $log;
2739 print '-' x72,"\n" unless $incremental || $oneline;
2742 package Git::SVN::Migration;
2743 # these version numbers do NOT correspond to actual version numbers
2744 # of git nor git-svn. They are just relative.
2746 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2748 # v1 layout: .git/$id/info/url, refs/remotes/$id
2750 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2752 # v3 layout: .git/svn/$id, refs/remotes/$id
2753 # - info/url may remain for backwards compatibility
2754 # - this is what we migrate up to this layout automatically,
2755 # - this will be used by git svn init on single branches
2757 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2758 # - this is only created for newly multi-init-ed
2759 # repositories. Similar in spirit to the
2760 # --use-separate-remotes option in git-clone (now default)
2761 # - we do not automatically migrate to this (following
2762 # the example set by core git)
2763 use strict;
2764 use warnings;
2765 use Carp qw/croak/;
2766 use File::Path qw/mkpath/;
2767 use File::Basename qw/dirname basename/;
2768 use vars qw/$_minimize/;
2770 sub migrate_from_v0 {
2771 my $git_dir = $ENV{GIT_DIR};
2772 return undef unless -d $git_dir;
2773 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2774 my $migrated = 0;
2775 while (<$fh>) {
2776 chomp;
2777 my ($id, $orig_ref) = ($_, $_);
2778 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2779 next unless -f "$git_dir/$id/info/url";
2780 my $new_ref = "refs/remotes/$id";
2781 if (::verify_ref("$new_ref^0")) {
2782 print STDERR "W: $orig_ref is probably an old ",
2783 "branch used by an ancient version of ",
2784 "git-svn.\n",
2785 "However, $new_ref also exists.\n",
2786 "We will not be able ",
2787 "to use this branch until this ",
2788 "ambiguity is resolved.\n";
2789 next;
2791 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2792 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2793 command_noisy('update-ref', $new_ref, $orig_ref);
2794 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2795 $migrated++;
2797 command_close_pipe($fh, $ctx);
2798 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2799 $migrated;
2802 sub migrate_from_v1 {
2803 my $git_dir = $ENV{GIT_DIR};
2804 my $migrated = 0;
2805 return $migrated unless -d $git_dir;
2806 my $svn_dir = "$git_dir/svn";
2808 # just in case somebody used 'svn' as their $id at some point...
2809 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2811 print STDERR "Migrating from a git-svn v1 layout...\n";
2812 mkpath([$svn_dir]);
2813 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2814 "$svn_dir\n\t(required for this version ",
2815 "($::VERSION) of git-svn) does not. exist\n";
2816 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2817 while (<$fh>) {
2818 my $x = $_;
2819 next unless $x =~ s#^refs/remotes/##;
2820 chomp $x;
2821 next unless -f "$git_dir/$x/info/url";
2822 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2823 next unless $u;
2824 my $dn = dirname("$git_dir/svn/$x");
2825 mkpath([$dn]) unless -d $dn;
2826 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2827 mkpath(["$git_dir/svn/svn"]);
2828 print STDERR " - $git_dir/$x/info => ",
2829 "$git_dir/svn/$x/info\n";
2830 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2831 croak "$!: $x";
2832 # don't worry too much about these, they probably
2833 # don't exist with repos this old (save for index,
2834 # and we can easily regenerate that)
2835 foreach my $f (qw/unhandled.log index .rev_db/) {
2836 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2838 } else {
2839 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2840 rename "$git_dir/$x", "$git_dir/svn/$x" or
2841 croak "$!: $x";
2843 $migrated++;
2845 command_close_pipe($fh, $ctx);
2846 print STDERR "Done migrating from a git-svn v1 layout\n";
2847 $migrated;
2850 sub read_old_urls {
2851 my ($l_map, $pfx, $path) = @_;
2852 my @dir;
2853 foreach (<$path/*>) {
2854 if (-r "$_/info/url") {
2855 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2856 my $ref_id = $pfx . basename $_;
2857 my $url = ::file_to_s("$_/info/url");
2858 $l_map->{$ref_id} = $url;
2859 } elsif (-d $_) {
2860 push @dir, $_;
2863 foreach (@dir) {
2864 my $x = $_;
2865 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2866 read_old_urls($l_map, $x, $_);
2870 sub migrate_from_v2 {
2871 my @cfg = command(qw/config -l/);
2872 return if grep /^svn-remote\..+\.url=/, @cfg;
2873 my %l_map;
2874 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2875 my $migrated = 0;
2877 foreach my $ref_id (sort keys %l_map) {
2878 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2879 $migrated++;
2881 $migrated;
2884 sub minimize_connections {
2885 my $r = Git::SVN::read_all_remotes();
2886 my $new_urls = {};
2887 my $root_repos = {};
2888 foreach my $repo_id (keys %$r) {
2889 my $url = $r->{$repo_id}->{url} or next;
2890 my $fetch = $r->{$repo_id}->{fetch} or next;
2891 my $ra = Git::SVN::Ra->new($url);
2893 # skip existing cases where we already connect to the root
2894 if (($ra->{url} eq $ra->{repos_root}) ||
2895 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2896 $repo_id)) {
2897 $root_repos->{$ra->{url}} = $repo_id;
2898 next;
2901 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2902 my $root_path = $ra->{url};
2903 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2904 foreach my $path (keys %$fetch) {
2905 my $ref_id = $fetch->{$path};
2906 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2908 # make sure we can read when connecting to
2909 # a higher level of a repository
2910 my ($last_rev, undef) = $gs->last_rev_commit;
2911 if (!defined $last_rev) {
2912 $last_rev = eval {
2913 $root_ra->get_latest_revnum;
2915 next if $@;
2917 my $new = $root_path;
2918 $new .= length $path ? "/$path" : '';
2919 eval {
2920 $root_ra->get_log([$new], $last_rev, $last_rev,
2921 0, 0, 1, sub { });
2923 next if $@;
2924 $new_urls->{$ra->{repos_root}}->{$new} =
2925 { ref_id => $ref_id,
2926 old_repo_id => $repo_id,
2927 old_path => $path };
2931 my @emptied;
2932 foreach my $url (keys %$new_urls) {
2933 # see if we can re-use an existing [svn-remote "repo_id"]
2934 # instead of creating a(n ugly) new section:
2935 my $repo_id = $root_repos->{$url} ||
2936 Git::SVN::sanitize_remote_name($url);
2938 my $fetch = $new_urls->{$url};
2939 foreach my $path (keys %$fetch) {
2940 my $x = $fetch->{$path};
2941 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2942 my $pfx = "svn-remote.$x->{old_repo_id}";
2944 my $old_fetch = quotemeta("$x->{old_path}:".
2945 "refs/remotes/$x->{ref_id}");
2946 command_noisy(qw/config --unset/,
2947 "$pfx.fetch", '^'. $old_fetch . '$');
2948 delete $r->{$x->{old_repo_id}}->
2949 {fetch}->{$x->{old_path}};
2950 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2951 command_noisy(qw/config --unset/,
2952 "$pfx.url");
2953 push @emptied, $x->{old_repo_id}
2957 if (@emptied) {
2958 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2959 "$ENV{GIT_DIR}/config";
2960 print STDERR <<EOF;
2961 The following [svn-remote] sections in your config file ($file) are empty
2962 and can be safely removed:
2964 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2968 sub migration_check {
2969 migrate_from_v0();
2970 migrate_from_v1();
2971 migrate_from_v2();
2972 minimize_connections() if $_minimize;
2975 package Git::IndexInfo;
2976 use strict;
2977 use warnings;
2978 use Git qw/command_input_pipe command_close_pipe/;
2980 sub new {
2981 my ($class) = @_;
2982 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
2983 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
2986 sub remove {
2987 my ($self, $path) = @_;
2988 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
2989 return ++$self->{nr};
2991 undef;
2994 sub update {
2995 my ($self, $mode, $hash, $path) = @_;
2996 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
2997 return ++$self->{nr};
2999 undef;
3002 sub DESTROY {
3003 my ($self) = @_;
3004 command_close_pipe($self->{gui}, $self->{ctx});
3007 __END__
3009 Data structures:
3011 $log_entry hashref as returned by libsvn_log_entry()
3013 log => 'whitespace-formatted log entry
3014 ', # trailing newline is preserved
3015 revision => '8', # integer
3016 date => '2004-02-24T17:01:44.108345Z', # commit date
3017 author => 'committer name'
3021 # this is generated by generate_diff();
3022 @mods = array of diff-index line hashes, each element represents one line
3023 of diff-index output
3025 diff-index line ($m hash)
3027 mode_a => first column of diff-index output, no leading ':',
3028 mode_b => second column of diff-index output,
3029 sha1_b => sha1sum of the final blob,
3030 chg => change type [MCRADT],
3031 file_a => original file name of a file (iff chg is 'C' or 'R')
3032 file_b => new/current file name of a file (any chg)
3036 # retval of read_url_paths{,_all}();
3037 $l_map = {
3038 # repository root url
3039 'https://svn.musicpd.org' => {
3040 # repository path # GIT_SVN_ID
3041 'mpd/trunk' => 'trunk',
3042 'mpd/tags/0.11.5' => 'tags/0.11.5',
3046 Notes:
3047 I don't trust the each() function on unless I created %hash myself
3048 because the internal iterator may not have started at base.