git-svn: avoid redundant get_log calls between invocations
[git/dscho.git] / git-svn.perl
blobb1d91fa471b11ef6ab2f9c005bb1efac6ea53119
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 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 $ENV{GIT_DIR} ||= '.git';
13 $Git::SVN::default_repo_id = 'git-svn';
14 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Log::TZ = $ENV{TZ};
17 $ENV{TZ} = 'UTC';
18 $| = 1; # unbuffer STDOUT
20 sub fatal (@) { print STDERR @_; exit 1 }
21 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
22 require SVN::Ra;
23 require SVN::Delta;
24 if ($SVN::Core::VERSION lt '1.1.0') {
25 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
27 push @Git::SVN::Ra::ISA, 'SVN::Ra';
28 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
29 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
30 use Carp qw/croak/;
31 use IO::File qw//;
32 use File::Basename qw/dirname basename/;
33 use File::Path qw/mkpath/;
34 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
35 use IPC::Open3;
36 use Git;
38 BEGIN {
39 my $s;
40 foreach (qw/command command_oneline command_noisy command_output_pipe
41 command_input_pipe command_close_pipe/) {
42 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
43 "*Git::SVN::Migration::$_ = ".
44 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
46 eval $s;
49 my ($SVN);
51 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
52 $sha1 = qr/[a-f\d]{40}/;
53 $sha1_short = qr/[a-f\d]{4,40}/;
54 my ($_stdin, $_help, $_edit,
55 $_message, $_file,
56 $_template, $_shared,
57 $_version,
58 $_merge, $_strategy, $_dry_run,
59 $_prefix);
61 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
62 'config-dir=s' => \$Git::SVN::Ra::config_dir,
63 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
64 my %fc_opts = ( 'follow-parent|follow' => \$Git::SVN::_follow_parent,
65 'authors-file|A=s' => \$_authors,
66 'repack:i' => \$Git::SVN::_repack,
67 'no-metadata' => \$Git::SVN::_no_metadata,
68 'quiet|q' => \$_q,
69 'repack-flags|repack-args|repack-opts=s' =>
70 \$Git::SVN::_repack_flags,
71 %remote_opts );
73 my ($_trunk, $_tags, $_branches);
74 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
75 'tags|t=s' => \$_tags,
76 'branches|b=s' => \$_branches );
77 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
78 my %cmt_opts = ( 'edit|e' => \$_edit,
79 'rmdir' => \$SVN::Git::Editor::_rmdir,
80 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
81 'l=i' => \$SVN::Git::Editor::_rename_limit,
82 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
85 my %cmd = (
86 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
87 { 'revision|r=s' => \$_revision, %fc_opts } ],
88 init => [ \&cmd_init, "Initialize a repo for tracking" .
89 " (requires URL argument)",
90 \%init_opts ],
91 dcommit => [ \&cmd_dcommit,
92 'Commit several diffs to merge with upstream',
93 { 'merge|m|M' => \$_merge,
94 'strategy|s=s' => \$_strategy,
95 'dry-run|n' => \$_dry_run,
96 %cmt_opts, %fc_opts } ],
97 'set-tree' => [ \&cmd_set_tree,
98 "Set an SVN repository to a git tree-ish",
99 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
100 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
101 { 'revision|r=i' => \$_revision } ],
102 'multi-init' => [ \&cmd_multi_init,
103 'Initialize multiple trees (like git-svnimport)',
104 { %multi_opts, %init_opts, %remote_opts,
105 'revision|r=i' => \$_revision,
106 'prefix=s' => \$_prefix,
107 } ],
108 'multi-fetch' => [ \&cmd_multi_fetch,
109 'Fetch multiple trees (like git-svnimport)',
110 \%fc_opts ],
111 'migrate' => [ sub { },
112 # no-op, we automatically run this anyways,
113 'Migrate configuration/metadata/layout from
114 previous versions of git-svn',
115 \%remote_opts ],
116 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
117 { 'limit=i' => \$Git::SVN::Log::limit,
118 'revision|r=s' => \$_revision,
119 'verbose|v' => \$Git::SVN::Log::verbose,
120 'incremental' => \$Git::SVN::Log::incremental,
121 'oneline' => \$Git::SVN::Log::oneline,
122 'show-commit' => \$Git::SVN::Log::show_commit,
123 'non-recursive' => \$Git::SVN::Log::non_recursive,
124 'authors-file|A=s' => \$_authors,
125 'color' => \$Git::SVN::Log::color,
126 'pager=s' => \$Git::SVN::Log::pager,
127 } ],
128 'commit-diff' => [ \&cmd_commit_diff,
129 'Commit a diff between two trees',
130 { 'message|m=s' => \$_message,
131 'file|F=s' => \$_file,
132 'revision|r=s' => \$_revision,
133 %cmt_opts } ],
136 my $cmd;
137 for (my $i = 0; $i < @ARGV; $i++) {
138 if (defined $cmd{$ARGV[$i]}) {
139 $cmd = $ARGV[$i];
140 splice @ARGV, $i, 1;
141 last;
145 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
147 read_repo_config(\%opts);
148 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
149 'minimize-connections' => \$Git::SVN::Migration::_minimize,
150 'id|i=s' => \$Git::SVN::default_ref_id,
151 'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
152 exit 1 if (!$rv && $cmd ne 'log');
154 usage(0) if $_help;
155 version() if $_version;
156 usage(1) unless defined $cmd;
157 load_authors() if $_authors;
158 unless ($cmd =~ /^(?:init|multi-init|commit-diff)$/) {
159 Git::SVN::Migration::migration_check();
161 Git::SVN::init_vars();
162 eval {
163 Git::SVN::verify_remotes_sanity();
164 $cmd{$cmd}->[0]->(@ARGV);
166 fatal $@ if $@;
167 exit 0;
169 ####################### primary functions ######################
170 sub usage {
171 my $exit = shift || 0;
172 my $fd = $exit ? \*STDERR : \*STDOUT;
173 print $fd <<"";
174 git-svn - bidirectional operations between a single Subversion tree and git
175 Usage: $0 <command> [options] [arguments]\n
177 print $fd "Available commands:\n" unless $cmd;
179 foreach (sort keys %cmd) {
180 next if $cmd && $cmd ne $_;
181 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
182 foreach (keys %{$cmd{$_}->[2]}) {
183 # prints out arguments as they should be passed:
184 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
185 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
186 "--$_" : "-$_" }
187 split /\|/,$_)," $x\n";
190 print $fd <<"";
191 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
192 arbitrary identifier if you're tracking multiple SVN branches/repositories in
193 one git repository and want to keep them separate. See git-svn(1) for more
194 information.
196 exit $exit;
199 sub version {
200 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
201 exit 0;
204 sub do_git_init_db {
205 unless (-d $ENV{GIT_DIR}) {
206 my @init_db = ('init');
207 push @init_db, "--template=$_template" if defined $_template;
208 push @init_db, "--shared" if defined $_shared;
209 command_noisy(@init_db);
213 sub cmd_init {
214 my $url = shift or die "SVN repository location required " .
215 "as a command-line argument\n";
216 if (my $repo_path = shift) {
217 unless (-d $repo_path) {
218 mkpath([$repo_path]);
220 chdir $repo_path or croak $!;
221 $ENV{GIT_DIR} = $repo_path . "/.git";
223 do_git_init_db();
225 Git::SVN->init($url);
228 sub cmd_fetch {
229 if (@_) {
230 die "Additional fetch arguments are no longer supported.\n",
231 "Use --follow-parent if you have moved/copied directories
232 instead.\n";
234 my $gs = Git::SVN->new;
235 $gs->fetch(parse_revision_argument());
236 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
237 command_noisy(qw(update-ref refs/heads/master),
238 $gs->{last_commit});
242 sub cmd_set_tree {
243 my (@commits) = @_;
244 if ($_stdin || !@commits) {
245 print "Reading from stdin...\n";
246 @commits = ();
247 while (<STDIN>) {
248 if (/\b($sha1_short)\b/o) {
249 unshift @commits, $1;
253 my @revs;
254 foreach my $c (@commits) {
255 my @tmp = command('rev-parse',$c);
256 if (scalar @tmp == 1) {
257 push @revs, $tmp[0];
258 } elsif (scalar @tmp > 1) {
259 push @revs, reverse(command('rev-list',@tmp));
260 } else {
261 fatal "Failed to rev-parse $c\n";
264 my $gs = Git::SVN->new;
265 my ($r_last, $cmt_last) = $gs->last_rev_commit;
266 $gs->fetch;
267 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
268 fatal "There are new revisions that were fetched ",
269 "and need to be merged (or acknowledged) ",
270 "before committing.\nlast rev: $r_last\n",
271 " current: $gs->{last_rev}\n";
273 $gs->set_tree($_) foreach @revs;
274 print "Done committing ",scalar @revs," revisions to SVN\n";
277 sub cmd_dcommit {
278 my $head = shift;
279 my $gs = Git::SVN->new;
280 $head ||= 'HEAD';
281 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
282 my $last_rev;
283 foreach my $d (reverse @refs) {
284 if (!verify_ref("$d~1")) {
285 fatal "Commit $d\n",
286 "has no parent commit, and therefore ",
287 "nothing to diff against.\n",
288 "You should be working from a repository ",
289 "originally created by git-svn\n";
291 unless (defined $last_rev) {
292 (undef, $last_rev, undef) = cmt_metadata("$d~1");
293 unless (defined $last_rev) {
294 fatal "Unable to extract revision information ",
295 "from commit $d~1\n";
298 if ($_dry_run) {
299 print "diff-tree $d~1 $d\n";
300 } else {
301 my %ed_opts = ( r => $last_rev,
302 log => get_commit_entry($d)->{log},
303 ra => $gs->ra,
304 tree_a => "$d~1",
305 tree_b => $d,
306 editor_cb => sub {
307 print "Committed r$_[0]\n";
308 $last_rev = $_[0]; },
309 svn_path => $gs->{path} );
310 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
311 print "No changes\n$d~1 == $d\n";
315 return if $_dry_run;
316 $gs->fetch;
317 # we always want to rebase against the current HEAD, not any
318 # head that was passed to us
319 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
320 my @finish;
321 if (@diff) {
322 @finish = qw/rebase/;
323 push @finish, qw/--merge/ if $_merge;
324 push @finish, "--strategy=$_strategy" if $_strategy;
325 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
326 "using @finish:\n", "@diff";
327 } else {
328 print "No changes between current HEAD and ",
329 $gs->refname, "\nResetting to the latest ",
330 $gs->refname, "\n";
331 @finish = qw/reset --mixed/;
333 command_noisy(@finish, $gs->refname);
336 sub cmd_show_ignore {
337 my $gs = Git::SVN->new;
338 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
339 $gs->traverse_ignore(\*STDOUT, '', $r);
342 sub cmd_multi_init {
343 my $url = shift;
344 unless (defined $_trunk || defined $_branches || defined $_tags) {
345 usage(1);
347 do_git_init_db();
348 $_prefix = '' unless defined $_prefix;
349 $url =~ s#/+$## if defined $url;
350 if (defined $_trunk) {
351 my $trunk_ref = $_prefix . 'trunk';
352 # try both old-style and new-style lookups:
353 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
354 unless ($gs_trunk) {
355 my ($trunk_url, $trunk_path) =
356 complete_svn_url($url, $_trunk);
357 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
358 undef, $trunk_ref);
361 return unless defined $_branches || defined $_tags;
362 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
363 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
364 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
367 sub cmd_multi_fetch {
368 my $remotes = Git::SVN::read_all_remotes();
369 foreach my $repo_id (sort keys %$remotes) {
370 my $url = $remotes->{$repo_id}->{url} or next;
371 my $fetch = $remotes->{$repo_id}->{fetch} or next;
372 Git::SVN::fetch_all($repo_id, $url, $fetch);
376 # this command is special because it requires no metadata
377 sub cmd_commit_diff {
378 my ($ta, $tb, $url) = @_;
379 my $usage = "Usage: $0 commit-diff -r<revision> ".
380 "<tree-ish> <tree-ish> [<URL>]\n";
381 fatal($usage) if (!defined $ta || !defined $tb);
382 my $svn_path;
383 if (!defined $url) {
384 my $gs = eval { Git::SVN->new };
385 if (!$gs) {
386 fatal("Needed URL or usable git-svn --id in ",
387 "the command-line\n", $usage);
389 $url = $gs->{url};
390 $svn_path = $gs->{path};
392 unless (defined $_revision) {
393 fatal("-r|--revision is a required argument\n", $usage);
395 if (defined $_message && defined $_file) {
396 fatal("Both --message/-m and --file/-F specified ",
397 "for the commit message.\n",
398 "I have no idea what you mean\n");
400 if (defined $_file) {
401 $_message = file_to_s($_file);
402 } else {
403 $_message ||= get_commit_entry($tb)->{log};
405 my $ra ||= Git::SVN::Ra->new($url);
406 $svn_path ||= $ra->{svn_path};
407 my $r = $_revision;
408 if ($r eq 'HEAD') {
409 $r = $ra->get_latest_revnum;
410 } elsif ($r !~ /^\d+$/) {
411 die "revision argument: $r not understood by git-svn\n";
413 my %ed_opts = ( r => $r,
414 log => $_message,
415 ra => $ra,
416 tree_a => $ta,
417 tree_b => $tb,
418 editor_cb => sub { print "Committed r$_[0]\n" },
419 svn_path => $svn_path );
420 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
421 print "No changes\n$ta == $tb\n";
425 ########################### utility functions #########################
427 sub parse_revision_argument {
428 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
429 return (undef, undef);
431 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
432 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
433 return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
434 return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
435 die "revision argument: $_revision not understood by git-svn\n",
436 "Try using the command-line svn client instead\n";
439 sub complete_svn_url {
440 my ($url, $path) = @_;
441 $path =~ s#/+$##;
442 if ($path !~ m#^[a-z\+]+://#) {
443 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
444 fatal("E: '$path' is not a complete URL ",
445 "and a separate URL is not specified\n");
447 return ($url, $path);
449 return ($path, '');
452 sub complete_url_ls_init {
453 my ($ra, $repo_path, $switch, $pfx) = @_;
454 unless ($repo_path) {
455 print STDERR "W: $switch not specified\n";
456 return;
458 $repo_path =~ s#/+$##;
459 if ($repo_path =~ m#^[a-z\+]+://#) {
460 $ra = Git::SVN::Ra->new($repo_path);
461 $repo_path = '';
462 } else {
463 $repo_path =~ s#^/+##;
464 unless ($ra) {
465 fatal("E: '$repo_path' is not a complete URL ",
466 "and a separate URL is not specified\n");
469 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
470 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
471 my $url = $ra->{url};
472 foreach my $d (sort keys %$dirent) {
473 next if ($dirent->{$d}->kind != $SVN::Node::dir);
474 my $path = "$repo_path/$d";
475 my $ref = "$pfx$d";
476 my $gs = eval { Git::SVN->new($ref) };
477 # don't try to init already existing refs
478 unless ($gs) {
479 print "init $url/$path => $ref\n";
480 Git::SVN->init($url, $path, undef, $ref);
485 sub verify_ref {
486 my ($ref) = @_;
487 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
488 { STDERR => 0 }); };
491 sub get_tree_from_treeish {
492 my ($treeish) = @_;
493 # $treeish can be a symbolic ref, too:
494 my $type = command_oneline(qw/cat-file -t/, $treeish);
495 my $expected;
496 while ($type eq 'tag') {
497 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
499 if ($type eq 'commit') {
500 $expected = (grep /^tree /, command(qw/cat-file commit/,
501 $treeish))[0];
502 ($expected) = ($expected =~ /^tree ($sha1)$/o);
503 die "Unable to get tree from $treeish\n" unless $expected;
504 } elsif ($type eq 'tree') {
505 $expected = $treeish;
506 } else {
507 die "$treeish is a $type, expected tree, tag or commit\n";
509 return $expected;
512 sub get_commit_entry {
513 my ($treeish) = shift;
514 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
515 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
516 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
517 open my $log_fh, '>', $commit_editmsg or croak $!;
519 my $type = command_oneline(qw/cat-file -t/, $treeish);
520 if ($type eq 'commit' || $type eq 'tag') {
521 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
522 $type, $treeish);
523 my $in_msg = 0;
524 while (<$msg_fh>) {
525 if (!$in_msg) {
526 $in_msg = 1 if (/^\s*$/);
527 } elsif (/^git-svn-id: /) {
528 # skip this for now, we regenerate the
529 # correct one on re-fetch anyways
530 # TODO: set *:merge properties or like...
531 } else {
532 print $log_fh $_ or croak $!;
535 command_close_pipe($msg_fh, $ctx);
537 close $log_fh or croak $!;
539 if ($_edit || ($type eq 'tree')) {
540 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
541 # TODO: strip out spaces, comments, like git-commit.sh
542 system($editor, $commit_editmsg);
544 rename $commit_editmsg, $commit_msg or croak $!;
545 open $log_fh, '<', $commit_msg or croak $!;
546 { local $/; chomp($log_entry{log} = <$log_fh>); }
547 close $log_fh or croak $!;
548 unlink $commit_msg;
549 \%log_entry;
552 sub s_to_file {
553 my ($str, $file, $mode) = @_;
554 open my $fd,'>',$file or croak $!;
555 print $fd $str,"\n" or croak $!;
556 close $fd or croak $!;
557 chmod ($mode &~ umask, $file) if (defined $mode);
560 sub file_to_s {
561 my $file = shift;
562 open my $fd,'<',$file or croak "$!: file: $file\n";
563 local $/;
564 my $ret = <$fd>;
565 close $fd or croak $!;
566 $ret =~ s/\s*$//s;
567 return $ret;
570 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
571 sub load_authors {
572 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
573 my $log = $cmd eq 'log';
574 while (<$authors>) {
575 chomp;
576 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
577 my ($user, $name, $email) = ($1, $2, $3);
578 if ($log) {
579 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
580 } else {
581 $users{$user} = [$name, $email];
584 close $authors or croak $!;
587 # convert GetOpt::Long specs for use by git-config
588 sub read_repo_config {
589 return unless -d $ENV{GIT_DIR};
590 my $opts = shift;
591 foreach my $o (keys %$opts) {
592 my $v = $opts->{$o};
593 my ($key) = ($o =~ /^([a-z\-]+)/);
594 $key =~ s/-//g;
595 my $arg = 'git-config';
596 $arg .= ' --int' if ($o =~ /[:=]i$/);
597 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
598 if (ref $v eq 'ARRAY') {
599 chomp(my @tmp = `$arg --get-all svn.$key`);
600 @$v = @tmp if @tmp;
601 } else {
602 chomp(my $tmp = `$arg --get svn.$key`);
603 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
604 $$v = $tmp;
610 sub extract_metadata {
611 my $id = shift or return (undef, undef, undef);
612 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
613 \s([a-f\d\-]+)$/x);
614 if (!defined $rev || !$uuid || !$url) {
615 # some of the original repositories I made had
616 # identifiers like this:
617 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
619 return ($url, $rev, $uuid);
622 sub cmt_metadata {
623 return extract_metadata((grep(/^git-svn-id: /,
624 command(qw/cat-file commit/, shift)))[-1]);
627 package Git::SVN;
628 use strict;
629 use warnings;
630 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
631 $_repack $_repack_flags/;
632 use Carp qw/croak/;
633 use File::Path qw/mkpath/;
634 use File::Copy qw/copy/;
635 use IPC::Open3;
637 my $_repack_nr;
638 # properties that we do not log:
639 my %SKIP_PROP;
640 BEGIN {
641 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
642 svn:special svn:executable
643 svn:entry:committed-rev
644 svn:entry:last-author
645 svn:entry:uuid
646 svn:entry:committed-date/;
649 my %LOCKFILES;
650 END { unlink keys %LOCKFILES if %LOCKFILES }
652 sub fetch_all {
653 my ($repo_id, $url, $fetch) = @_;
654 my @gs;
655 my $ra = Git::SVN::Ra->new($url);
656 my $head = $ra->get_latest_revnum;
657 my $base = $head;
658 foreach my $p (sort keys %$fetch) {
659 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
660 my $lr = $gs->rev_db_max;
661 if (defined $lr) {
662 $base = $lr if ($lr < $base);
664 push @gs, $gs;
666 return if (++$base > $head);
667 $ra->gs_fetch_loop_common($base, $head, @gs);
670 sub read_all_remotes {
671 my $r = {};
672 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
673 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
674 $r->{$1}->{fetch}->{$2} = $3;
675 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
676 $r->{$1}->{url} = $2;
682 sub init_vars {
683 if (defined $_repack) {
684 $_repack = 1000 if ($_repack <= 0);
685 $_repack_nr = $_repack;
686 $_repack_flags ||= '-d';
690 sub verify_remotes_sanity {
691 return unless -d $ENV{GIT_DIR};
692 my %seen;
693 foreach (command(qw/config -l/)) {
694 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
695 if ($seen{$1}) {
696 die "Remote ref refs/remote/$1 is tracked by",
697 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
698 "Please resolve this ambiguity in ",
699 "your git configuration file before ",
700 "continuing\n";
702 $seen{$1} = $_;
707 # we allow more chars than remotes2config.sh...
708 sub sanitize_remote_name {
709 my ($name) = @_;
710 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
711 $name;
714 sub find_existing_remote {
715 my ($url, $remotes) = @_;
716 my $existing;
717 foreach my $repo_id (keys %$remotes) {
718 my $u = $remotes->{$repo_id}->{url} or next;
719 next if $u ne $url;
720 $existing = $repo_id;
721 last;
723 $existing;
726 sub init_remote_config {
727 my ($self, $url) = @_;
728 $url =~ s!/+$!!; # strip trailing slash
729 my $r = read_all_remotes();
730 my $existing = find_existing_remote($url, $r);
731 if ($existing) {
732 print STDERR "Using existing ",
733 "[svn-remote \"$existing\"]\n";
734 $self->{repo_id} = $existing;
735 } else {
736 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
737 $existing = find_existing_remote($min_url, $r);
738 if ($existing) {
739 print STDERR "Using existing ",
740 "[svn-remote \"$existing\"]\n";
741 $self->{repo_id} = $existing;
743 if ($min_url ne $url) {
744 print STDERR "Using higher level of URL: ",
745 "$url => $min_url\n";
746 my $old_path = $self->{path};
747 $self->{path} = $url;
748 $self->{path} =~ s!^\Q$min_url\E/*!!;
749 if (length $old_path) {
750 $self->{path} .= "/$old_path";
752 $url = $min_url;
755 my $orig_url;
756 if (!$existing) {
757 # verify that we aren't overwriting anything:
758 $orig_url = eval {
759 command_oneline('config', '--get',
760 "svn-remote.$self->{repo_id}.url")
762 if ($orig_url && ($orig_url ne $url)) {
763 die "svn-remote.$self->{repo_id}.url already set: ",
764 "$orig_url\nwanted to set to: $url\n";
767 my ($xrepo_id, $xpath) = find_ref($self->refname);
768 if (defined $xpath) {
769 die "svn-remote.$xrepo_id.fetch already set to track ",
770 "$xpath:refs/remotes/", $self->refname, "\n";
772 command_noisy('config',
773 "svn-remote.$self->{repo_id}.url", $url);
774 command_noisy('config', '--add',
775 "svn-remote.$self->{repo_id}.fetch",
776 "$self->{path}:".$self->refname);
777 $self->{url} = $url;
780 sub init {
781 my ($class, $url, $path, $repo_id, $ref_id) = @_;
782 my $self = _new($class, $repo_id, $ref_id, $path);
783 if (defined $url) {
784 $self->init_remote_config($url);
786 $self;
789 sub find_ref {
790 my ($ref_id) = @_;
791 foreach (command(qw/config -l/)) {
792 next unless m!^svn-remote\.(.+)\.fetch=
793 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
794 my ($repo_id, $path, $ref) = ($1, $2, $3);
795 if ($ref eq $ref_id) {
796 $path = '' if ($path =~ m#^\./?#);
797 return ($repo_id, $path);
800 (undef, undef, undef);
803 sub new {
804 my ($class, $ref_id, $repo_id, $path) = @_;
805 if (defined $ref_id && !defined $repo_id && !defined $path) {
806 ($repo_id, $path) = find_ref($ref_id);
807 if (!defined $repo_id) {
808 die "Could not find a \"svn-remote.*.fetch\" key ",
809 "in the repository configuration matching: ",
810 "refs/remotes/$ref_id\n";
813 my $self = _new($class, $repo_id, $ref_id, $path);
814 if (!defined $self->{path} || !length $self->{path}) {
815 my $fetch = command_oneline('config', '--get',
816 "svn-remote.$repo_id.fetch",
817 ":refs/remotes/$ref_id\$") or
818 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
819 "\":refs/remotes/$ref_id\$\" in config\n";
820 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
822 $self->{url} = command_oneline('config', '--get',
823 "svn-remote.$repo_id.url") or
824 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
825 if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
826 $self->rebuild;
828 $self;
831 sub refname { "refs/remotes/$_[0]->{ref_id}" }
833 sub ra {
834 my ($self) = shift;
835 Git::SVN::Ra->new($self->{url});
838 sub rel_path {
839 my ($self) = @_;
840 my $repos_root = $self->ra->{repos_root};
841 return $self->{path} if ($self->{url} eq $repos_root);
842 my $url = $self->{url} .
843 (length $self->{path} ? "/$self->{path}" : $self->{path});
844 $url =~ s!^\Q$repos_root\E/*!!g;
845 $url;
848 sub traverse_ignore {
849 my ($self, $fh, $path, $r) = @_;
850 $path =~ s#^/+##g;
851 my $ra = $self->ra;
852 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
853 my $p = $path;
854 $p =~ s#^\Q$ra->{svn_path}\E/##;
855 print $fh length $p ? "\n# $p\n" : "\n# /\n";
856 if (my $s = $props->{'svn:ignore'}) {
857 $s =~ s/[\r\n]+/\n/g;
858 chomp $s;
859 if (length $p == 0) {
860 $s =~ s#\n#\n/$p#g;
861 print $fh "/$s\n";
862 } else {
863 $s =~ s#\n#\n/$p/#g;
864 print $fh "/$p/$s\n";
867 foreach (sort keys %$dirent) {
868 next if $dirent->{$_}->kind != $SVN::Node::dir;
869 $self->traverse_ignore($fh, "$path/$_", $r);
873 sub last_rev { ($_[0]->last_rev_commit)[0] }
874 sub last_commit { ($_[0]->last_rev_commit)[1] }
876 # returns the newest SVN revision number and newest commit SHA1
877 sub last_rev_commit {
878 my ($self) = @_;
879 if (defined $self->{last_rev} && defined $self->{last_commit}) {
880 return ($self->{last_rev}, $self->{last_commit});
882 my $c = ::verify_ref($self->refname.'^0');
883 if ($c) {
884 my $rev = (::cmt_metadata($c))[1];
885 if (defined $rev) {
886 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
887 return ($rev, $c);
890 my $offset = -41; # from tail
891 my $rl;
892 open my $fh, '<', $self->{db_path} or
893 croak "$self->{db_path} not readable: $!\n";
894 seek $fh, $offset, 2;
895 $rl = readline $fh;
896 defined $rl or return (undef, undef);
897 chomp $rl;
898 while (('0' x40) eq $rl && tell $fh != 0) {
899 $offset -= 41;
900 seek $fh, $offset, 2;
901 $rl = readline $fh;
902 defined $rl or return (undef, undef);
903 chomp $rl;
905 if ($c) {
906 die "$self->{db_path} and ", $self->refname,
907 " inconsistent!:\n$c != $rl\n";
909 my $rev = tell $fh;
910 croak $! if ($rev < 0);
911 $rev = ($rev - 41) / 41;
912 close $fh or croak $!;
913 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
914 return ($rev, $c);
917 sub get_fetch_range {
918 my ($self, $min, $max) = @_;
919 $max ||= $self->ra->get_latest_revnum;
920 $min ||= $self->rev_db_max;
921 (++$min, $max);
924 sub tmp_index_do {
925 my ($self, $sub) = @_;
926 my $old_index = $ENV{GIT_INDEX_FILE};
927 $ENV{GIT_INDEX_FILE} = $self->{index};
928 my @ret = &$sub;
929 if ($old_index) {
930 $ENV{GIT_INDEX_FILE} = $old_index;
931 } else {
932 delete $ENV{GIT_INDEX_FILE};
934 wantarray ? @ret : $ret[0];
937 sub assert_index_clean {
938 my ($self, $treeish) = @_;
940 $self->tmp_index_do(sub {
941 command_noisy('read-tree', $treeish) unless -e $self->{index};
942 my $x = command_oneline('write-tree');
943 my ($y) = (command(qw/cat-file commit/, $treeish) =~
944 /^tree ($::sha1)/mo);
945 if ($y ne $x) {
946 unlink $self->{index} or croak $!;
947 command_noisy('read-tree', $treeish);
949 $x = command_oneline('write-tree');
950 if ($y ne $x) {
951 ::fatal "trees ($treeish) $y != $x\n",
952 "Something is seriously wrong...\n";
957 sub get_commit_parents {
958 my ($self, $log_entry) = @_;
959 my (%seen, @ret, @tmp);
960 # legacy support for 'set-tree'; this is only used by set_tree_cb:
961 if (my $ip = $self->{inject_parents}) {
962 if (my $commit = delete $ip->{$log_entry->{revision}}) {
963 push @tmp, $commit;
966 if (my $cur = ::verify_ref($self->refname.'^0')) {
967 push @tmp, $cur;
969 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
970 while (my $p = shift @tmp) {
971 next if $seen{$p};
972 $seen{$p} = 1;
973 push @ret, $p;
974 # MAXPARENT is defined to 16 in commit-tree.c:
975 last if @ret >= 16;
977 if (@tmp) {
978 die "r$log_entry->{revision}: No room for parents:\n\t",
979 join("\n\t", @tmp), "\n";
981 @ret;
984 sub full_url {
985 my ($self) = @_;
986 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
989 sub do_git_commit {
990 my ($self, $log_entry) = @_;
991 my $lr = $self->last_rev;
992 if (defined $lr && $lr >= $log_entry->{revision}) {
993 die "Last fetched revision of ", $self->refname,
994 " was r$lr, but we are about to fetch: ",
995 "r$log_entry->{revision}!\n";
997 if (my $c = $self->rev_db_get($log_entry->{revision})) {
998 croak "$log_entry->{revision} = $c already exists! ",
999 "Why are we refetching it?\n";
1001 my $author = $log_entry->{author};
1002 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1003 : ($author, "$author\@".$self->ra->uuid));
1004 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1005 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1006 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1008 my $tree = $log_entry->{tree};
1009 if (!defined $tree) {
1010 $tree = $self->tmp_index_do(sub {
1011 command_oneline('write-tree') });
1013 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1015 my @exec = ('git-commit-tree', $tree);
1016 foreach ($self->get_commit_parents($log_entry)) {
1017 push @exec, '-p', $_;
1019 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1020 or croak $!;
1021 print $msg_fh $log_entry->{log} or croak $!;
1022 unless ($_no_metadata) {
1023 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1024 $log_entry->{revision}, ' ',
1025 $self->ra->uuid, "\n" or croak $!;
1027 $msg_fh->flush == 0 or croak $!;
1028 close $msg_fh or croak $!;
1029 chomp(my $commit = do { local $/; <$out_fh> });
1030 close $out_fh or croak $!;
1031 waitpid $pid, 0;
1032 croak $? if $?;
1033 if ($commit !~ /^$::sha1$/o) {
1034 die "Failed to commit, invalid sha1: $commit\n";
1037 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1039 $self->{last_rev} = $log_entry->{revision};
1040 $self->{last_commit} = $commit;
1041 print "r$log_entry->{revision} = $commit ($self->{ref_id})\n";
1042 if (defined $_repack && (--$_repack_nr == 0)) {
1043 $_repack_nr = $_repack;
1044 # repack doesn't use any arguments with spaces in them, does it?
1045 print "Running git repack $_repack_flags ...\n";
1046 command_noisy('repack', split(/\s+/, $_repack_flags));
1047 print "Done repacking\n";
1049 return $commit;
1052 sub revisions_eq {
1053 my ($self, $r0, $r1) = @_;
1054 return 1 if $r0 == $r1;
1055 my $nr = 0;
1056 $self->ra->get_log([$self->{path}], $r0, $r1,
1057 0, 0, 1, sub { $nr++ });
1058 return 0 if ($nr > 1);
1059 return 1;
1062 sub find_parent_branch {
1063 my ($self, $paths, $rev) = @_;
1064 return undef unless $_follow_parent;
1065 unless (defined $paths) {
1066 my $err_handler = $SVN::Error::handler;
1067 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1068 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1069 $paths =
1070 Git::SVN::Ra::dup_changed_paths($_[0]) });
1071 $SVN::Error::handler = $err_handler;
1073 return undef unless defined $paths;
1075 # look for a parent from another branch:
1076 my @b_path_components = split m#/#, $self->rel_path;
1077 my @a_path_components;
1078 my $i;
1079 while (@b_path_components) {
1080 $i = $paths->{'/'.join('/', @b_path_components)};
1081 last if $i;
1082 unshift(@a_path_components, pop(@b_path_components));
1084 goto not_found unless defined $i;
1085 my $branch_from = $i->{copyfrom_path} or goto not_found;
1086 if (@a_path_components) {
1087 print STDERR "branch_from: $branch_from => ";
1088 $branch_from .= '/'.join('/', @a_path_components);
1089 print STDERR $branch_from, "\n";
1091 my $r = $i->{copyfrom_rev};
1092 my $repos_root = $self->ra->{repos_root};
1093 my $url = $self->ra->{url};
1094 my $new_url = $repos_root . $branch_from;
1095 print STDERR "Found possible branch point: ",
1096 "$new_url => ", $self->full_url, ", $r\n";
1097 $branch_from =~ s#^/##;
1098 my $remotes = read_all_remotes();
1099 my $gs;
1100 foreach my $repo_id (keys %$remotes) {
1101 my $u = $remotes->{$repo_id}->{url} or next;
1102 next if $url ne $u;
1103 my $fetch = $remotes->{$repo_id}->{fetch};
1104 foreach my $f (keys %$fetch) {
1105 next if $f ne $branch_from;
1106 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1107 last;
1109 last if $gs;
1111 unless ($gs) {
1112 my $ref_id = $self->{ref_id};
1113 $ref_id =~ s/\@\d+$//;
1114 $ref_id .= "\@$r";
1115 # just grow a tail if we're not unique enough :x
1116 $ref_id .= '-' while find_ref($ref_id);
1117 print STDERR "Initializing parent: $ref_id\n";
1118 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1120 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1121 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1122 $gs->fetch(0, $r);
1123 ($r0, $parent) = $gs->last_rev_commit;
1125 if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1126 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1127 $self->assert_index_clean($parent);
1128 my $ed;
1129 if ($self->ra->can_do_switch) {
1130 print STDERR "Following parent with do_switch\n";
1131 # do_switch works with svn/trunk >= r22312, but that
1132 # is not included with SVN 1.4.3 (the latest version
1133 # at the moment), so we can't rely on it
1134 $self->{last_commit} = $parent;
1135 $ed = SVN::Git::Fetcher->new($self);
1136 $gs->ra->gs_do_switch($r0, $rev, $gs,
1137 $self->full_url, $ed)
1138 or die "SVN connection failed somewhere...\n";
1139 } else {
1140 print STDERR "Following parent with do_update\n";
1141 $ed = SVN::Git::Fetcher->new($self);
1142 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1143 or die "SVN connection failed somewhere...\n";
1145 print STDERR "Successfully followed parent\n";
1146 return $self->make_log_entry($rev, [$parent], $ed);
1148 not_found:
1149 print STDERR "Branch parent for path: '/",
1150 $self->rel_path, "' @ r$rev not found:\n";
1151 return undef unless $paths;
1152 print STDERR "Changed paths:\n";
1153 foreach my $x (sort keys %$paths) {
1154 my $p = $paths->{$x};
1155 print STDERR "\t$p->{action}\t$x";
1156 if ($p->{copyfrom_path}) {
1157 print STDERR "(from $p->{copyfrom_path}: ",
1158 "$p->{copyfrom_rev})";
1160 print STDERR "\n";
1162 print STDERR '-'x72, "\n";
1163 return undef;
1166 sub do_fetch {
1167 my ($self, $paths, $rev) = @_;
1168 my $ed;
1169 my ($last_rev, @parents);
1170 if ($self->{last_commit}) {
1171 $ed = SVN::Git::Fetcher->new($self);
1172 $last_rev = $self->{last_rev};
1173 $ed->{c} = $self->{last_commit};
1174 @parents = ($self->{last_commit});
1175 } else {
1176 $last_rev = $rev;
1177 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1178 return $log_entry;
1180 $ed = SVN::Git::Fetcher->new($self);
1182 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1183 die "SVN connection failed somewhere...\n";
1185 $self->make_log_entry($rev, \@parents, $ed);
1188 sub get_untracked {
1189 my ($self, $ed) = @_;
1190 my @out;
1191 my $h = $ed->{empty};
1192 foreach (sort keys %$h) {
1193 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1194 push @out, " $act: " . uri_encode($_);
1195 warn "W: $act: $_\n";
1197 foreach my $t (qw/dir_prop file_prop/) {
1198 $h = $ed->{$t} or next;
1199 foreach my $path (sort keys %$h) {
1200 my $ppath = $path eq '' ? '.' : $path;
1201 foreach my $prop (sort keys %{$h->{$path}}) {
1202 next if $SKIP_PROP{$prop};
1203 my $v = $h->{$path}->{$prop};
1204 my $t_ppath_prop = "$t: " .
1205 uri_encode($ppath) . ' ' .
1206 uri_encode($prop);
1207 if (defined $v) {
1208 push @out, " +$t_ppath_prop " .
1209 uri_encode($v);
1210 } else {
1211 push @out, " -$t_ppath_prop";
1216 foreach my $t (qw/absent_file absent_directory/) {
1217 $h = $ed->{$t} or next;
1218 foreach my $parent (sort keys %$h) {
1219 foreach my $path (sort @{$h->{$parent}}) {
1220 push @out, " $t: " .
1221 uri_encode("$parent/$path");
1222 warn "W: $t: $parent/$path ",
1223 "Insufficient permissions?\n";
1227 \@out;
1230 sub parse_svn_date {
1231 my $date = shift || return '+0000 1970-01-01 00:00:00';
1232 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1233 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1234 croak "Unable to parse date: $date\n";
1235 "+0000 $Y-$m-$d $H:$M:$S";
1238 sub check_author {
1239 my ($author) = @_;
1240 if (!defined $author || length $author == 0) {
1241 $author = '(no author)';
1243 if (defined $::_authors && ! defined $::users{$author}) {
1244 die "Author: $author not defined in $::_authors file\n";
1246 $author;
1249 sub make_log_entry {
1250 my ($self, $rev, $parents, $ed) = @_;
1251 my $untracked = $self->get_untracked($ed);
1253 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1254 print $un "r$rev\n" or croak $!;
1255 print $un $_, "\n" foreach @$untracked;
1256 my %log_entry = ( parents => $parents || [], revision => $rev,
1257 log => '');
1258 my $rp = $self->ra->rev_proplist($rev);
1259 foreach (sort keys %$rp) {
1260 my $v = $rp->{$_};
1261 if (/^svn:(author|date|log)$/) {
1262 $log_entry{$1} = $v;
1263 } else {
1264 print $un " rev_prop: ", uri_encode($_), ' ',
1265 uri_encode($v), "\n";
1268 close $un or croak $!;
1270 $log_entry{date} = parse_svn_date($log_entry{date});
1271 $log_entry{author} = check_author($log_entry{author});
1272 $log_entry{log} .= "\n";
1273 \%log_entry;
1276 sub fetch {
1277 my ($self, $min_rev, $max_rev, @parents) = @_;
1278 my ($last_rev, $last_commit) = $self->last_rev_commit;
1279 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1280 return if ($base > $head);
1281 $self->ra->gs_fetch_loop_common($base, $head, $self);
1284 sub set_tree_cb {
1285 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1286 # TODO: enable and test optimized commits:
1287 if (0 && $rev == ($self->{last_rev} + 1)) {
1288 $log_entry->{revision} = $rev;
1289 $log_entry->{author} = $author;
1290 $self->do_git_commit($log_entry, "$rev=$tree");
1291 } else {
1292 $self->{inject_parents} = { $rev => $tree };
1293 $self->fetch(undef, undef);
1297 sub set_tree {
1298 my ($self, $tree) = (shift, shift);
1299 my $log_entry = ::get_commit_entry($tree);
1300 unless ($self->{last_rev}) {
1301 fatal("Must have an existing revision to commit\n");
1303 my %ed_opts = ( r => $self->{last_rev},
1304 log => $log_entry->{log},
1305 ra => $self->ra,
1306 tree_a => $self->{last_commit},
1307 tree_b => $tree,
1308 editor_cb => sub {
1309 $self->set_tree_cb($log_entry, $tree, @_) },
1310 svn_path => $self->{path} );
1311 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1312 print "No changes\nr$self->{last_rev} = $tree\n";
1316 sub rebuild {
1317 my ($self) = @_;
1318 print "Rebuilding $self->{db_path} ...\n";
1319 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1320 my $latest;
1321 my $full_url = $self->full_url;
1322 my $svn_uuid;
1323 while (<$rev_list>) {
1324 chomp;
1325 my $c = $_;
1326 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1327 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1329 # ignore merges (from set-tree)
1330 next if (!defined $rev || !$uuid);
1332 # if we merged or otherwise started elsewhere, this is
1333 # how we break out of it
1334 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1335 ($full_url && $url && ($url ne $full_url))) {
1336 next;
1338 $latest ||= $rev;
1339 $svn_uuid ||= $uuid;
1341 $self->rev_db_set($rev, $c);
1342 print "r$rev = $c\n";
1344 command_close_pipe($rev_list, $ctx);
1345 print "Done rebuilding $self->{db_path}\n";
1348 # rev_db:
1349 # Tie::File seems to be prone to offset errors if revisions get sparse,
1350 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1351 # one of my favorite modules is out :< Next up would be one of the DBM
1352 # modules, but I'm not sure which is most portable... So I'll just
1353 # go with something that's plain-text, but still capable of
1354 # being randomly accessed. So here's my ultra-simple fixed-width
1355 # database. All records are 40 characters + "\n", so it's easy to seek
1356 # to a revision: (41 * rev) is the byte offset.
1357 # A record of 40 0s denotes an empty revision.
1358 # And yes, it's still pretty fast (faster than Tie::File).
1359 # These files are disposable unless --no-metadata is set
1361 sub rev_db_set {
1362 my ($self, $rev, $commit, $update_ref) = @_;
1363 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1364 my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1365 my $sig;
1366 if ($update_ref) {
1367 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1368 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1370 $LOCKFILES{$db_lock} = 1;
1371 if ($_no_metadata) {
1372 copy($db, $db_lock) or die "rev_db_set(@_): ",
1373 "Failed to copy: ",
1374 "$db => $db_lock ($!)\n";
1375 } else {
1376 rename $db, $db_lock or die "rev_db_set(@_): ",
1377 "Failed to rename: ",
1378 "$db => $db_lock ($!)\n";
1380 open my $fh, '+<', $db_lock or croak $!;
1381 my $offset = $rev * 41;
1382 # assume that append is the common case:
1383 seek $fh, 0, 2 or croak $!;
1384 my $pos = tell $fh;
1385 if ($pos < $offset) {
1386 for (1 .. (($offset - $pos) / 41)) {
1387 print $fh (('0' x 40),"\n") or croak $!;
1390 seek $fh, $offset, 0 or croak $!;
1391 print $fh $commit,"\n" or croak $!;
1392 close $fh or croak $!;
1393 if ($update_ref) {
1394 command_noisy('update-ref', '-m', "r$rev",
1395 $self->refname, $commit);
1397 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1398 "$db_lock => $db ($!)\n";
1399 delete $LOCKFILES{$db_lock};
1400 if ($update_ref) {
1401 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1402 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1403 kill $sig, $$ if defined $sig;
1407 sub rev_db_max {
1408 my ($self) = @_;
1409 my @stat = stat $self->{db_path} or
1410 die "Couldn't stat $self->{db_path}: $!\n";
1411 ($stat[7] % 41) == 0 or
1412 die "$self->{db_path} inconsistent size:$stat[7]\n";
1413 my $max = $stat[7] / 41;
1414 (($max > 0) ? $max - 1 : 0);
1417 sub rev_db_get {
1418 my ($self, $rev) = @_;
1419 my $ret;
1420 my $offset = $rev * 41;
1421 open my $fh, '<', $self->{db_path} or croak $!;
1422 if (seek $fh, $offset, 0) {
1423 $ret = readline $fh;
1424 if (defined $ret) {
1425 chomp $ret;
1426 $ret = undef if ($ret =~ /^0{40}$/);
1429 close $fh or croak $!;
1430 $ret;
1433 sub find_rev_before {
1434 my ($self, $rev, $eq_ok) = @_;
1435 --$rev unless $eq_ok;
1436 while ($rev > 0) {
1437 if (my $c = $self->rev_db_get($rev)) {
1438 return ($rev, $c);
1440 --$rev;
1442 return (undef, undef);
1445 sub _new {
1446 my ($class, $repo_id, $ref_id, $path) = @_;
1447 unless (defined $repo_id && length $repo_id) {
1448 $repo_id = $Git::SVN::default_repo_id;
1450 unless (defined $ref_id && length $ref_id) {
1451 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1453 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1454 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1455 $_[3] = $path = '' unless (defined $path);
1456 mkpath([$dir]);
1457 unless (-f "$dir/.rev_db") {
1458 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1459 close $fh or croak $!;
1461 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1462 path => $path,
1463 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1466 sub uri_encode {
1467 my ($f) = @_;
1468 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1472 package Git::SVN::Prompt;
1473 use strict;
1474 use warnings;
1475 require SVN::Core;
1476 use vars qw/$_no_auth_cache $_username/;
1478 sub simple {
1479 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1480 $may_save = undef if $_no_auth_cache;
1481 $default_username = $_username if defined $_username;
1482 if (defined $default_username && length $default_username) {
1483 if (defined $realm && length $realm) {
1484 print STDERR "Authentication realm: $realm\n";
1485 STDERR->flush;
1487 $cred->username($default_username);
1488 } else {
1489 username($cred, $realm, $may_save, $pool);
1491 $cred->password(_read_password("Password for '" .
1492 $cred->username . "': ", $realm));
1493 $cred->may_save($may_save);
1494 $SVN::_Core::SVN_NO_ERROR;
1497 sub ssl_server_trust {
1498 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1499 $may_save = undef if $_no_auth_cache;
1500 print STDERR "Error validating server certificate for '$realm':\n";
1501 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1502 print STDERR " - The certificate is not issued by a trusted ",
1503 "authority. Use the\n",
1504 " fingerprint to validate the certificate manually!\n";
1506 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1507 print STDERR " - The certificate hostname does not match.\n";
1509 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1510 print STDERR " - The certificate is not yet valid.\n";
1512 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1513 print STDERR " - The certificate has expired.\n";
1515 if ($failures & $SVN::Auth::SSL::OTHER) {
1516 print STDERR " - The certificate has an unknown error.\n";
1518 printf STDERR
1519 "Certificate information:\n".
1520 " - Hostname: %s\n".
1521 " - Valid: from %s until %s\n".
1522 " - Issuer: %s\n".
1523 " - Fingerprint: %s\n",
1524 map $cert_info->$_, qw(hostname valid_from valid_until
1525 issuer_dname fingerprint);
1526 my $choice;
1527 prompt:
1528 print STDERR $may_save ?
1529 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1530 "(R)eject or accept (t)emporarily? ";
1531 STDERR->flush;
1532 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1533 if ($choice =~ /^t$/i) {
1534 $cred->may_save(undef);
1535 } elsif ($choice =~ /^r$/i) {
1536 return -1;
1537 } elsif ($may_save && $choice =~ /^p$/i) {
1538 $cred->may_save($may_save);
1539 } else {
1540 goto prompt;
1542 $cred->accepted_failures($failures);
1543 $SVN::_Core::SVN_NO_ERROR;
1546 sub ssl_client_cert {
1547 my ($cred, $realm, $may_save, $pool) = @_;
1548 $may_save = undef if $_no_auth_cache;
1549 print STDERR "Client certificate filename: ";
1550 STDERR->flush;
1551 chomp(my $filename = <STDIN>);
1552 $cred->cert_file($filename);
1553 $cred->may_save($may_save);
1554 $SVN::_Core::SVN_NO_ERROR;
1557 sub ssl_client_cert_pw {
1558 my ($cred, $realm, $may_save, $pool) = @_;
1559 $may_save = undef if $_no_auth_cache;
1560 $cred->password(_read_password("Password: ", $realm));
1561 $cred->may_save($may_save);
1562 $SVN::_Core::SVN_NO_ERROR;
1565 sub username {
1566 my ($cred, $realm, $may_save, $pool) = @_;
1567 $may_save = undef if $_no_auth_cache;
1568 if (defined $realm && length $realm) {
1569 print STDERR "Authentication realm: $realm\n";
1571 my $username;
1572 if (defined $_username) {
1573 $username = $_username;
1574 } else {
1575 print STDERR "Username: ";
1576 STDERR->flush;
1577 chomp($username = <STDIN>);
1579 $cred->username($username);
1580 $cred->may_save($may_save);
1581 $SVN::_Core::SVN_NO_ERROR;
1584 sub _read_password {
1585 my ($prompt, $realm) = @_;
1586 print STDERR $prompt;
1587 STDERR->flush;
1588 require Term::ReadKey;
1589 Term::ReadKey::ReadMode('noecho');
1590 my $password = '';
1591 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1592 last if $key =~ /[\012\015]/; # \n\r
1593 $password .= $key;
1595 Term::ReadKey::ReadMode('restore');
1596 print STDERR "\n";
1597 STDERR->flush;
1598 $password;
1601 package main;
1604 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1605 $SVN::Node::dir.$SVN::Node::unknown.
1606 $SVN::Node::none.$SVN::Node::file.
1607 $SVN::Node::dir.$SVN::Node::unknown.
1608 $SVN::Auth::SSL::CNMISMATCH.
1609 $SVN::Auth::SSL::NOTYETVALID.
1610 $SVN::Auth::SSL::EXPIRED.
1611 $SVN::Auth::SSL::UNKNOWNCA.
1612 $SVN::Auth::SSL::OTHER;
1615 package SVN::Git::Fetcher;
1616 use vars qw/@ISA/;
1617 use strict;
1618 use warnings;
1619 use Carp qw/croak/;
1620 use IO::File qw//;
1621 use Digest::MD5;
1623 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1624 sub new {
1625 my ($class, $git_svn) = @_;
1626 my $self = SVN::Delta::Editor->new;
1627 bless $self, $class;
1628 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1629 $self->{empty} = {};
1630 $self->{dir_prop} = {};
1631 $self->{file_prop} = {};
1632 $self->{absent_dir} = {};
1633 $self->{absent_file} = {};
1634 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1635 $self;
1638 sub set_path_strip {
1639 my ($self, $path) = @_;
1640 $self->{path_strip} = qr/^\Q$path\E\/?/;
1643 sub open_root {
1644 { path => '' };
1647 sub open_directory {
1648 my ($self, $path, $pb, $rev) = @_;
1649 { path => $path };
1652 sub git_path {
1653 my ($self, $path) = @_;
1654 if ($self->{path_strip}) {
1655 $path =~ s!$self->{path_strip}!! or
1656 die "Failed to strip path '$path' ($self->{path_strip})\n";
1658 $path;
1661 sub delete_entry {
1662 my ($self, $path, $rev, $pb) = @_;
1664 my $gpath = $self->git_path($path);
1665 return undef if ($gpath eq '');
1667 # remove entire directories.
1668 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1669 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1670 -r --name-only -z/,
1671 $self->{c}, '--', $gpath);
1672 local $/ = "\0";
1673 while (<$ls>) {
1674 chomp;
1675 $self->{gii}->remove($_);
1676 print "\tD\t$_\n" unless $self->{q};
1678 print "\tD\t$gpath/\n" unless $self->{q};
1679 command_close_pipe($ls, $ctx);
1680 $self->{empty}->{$path} = 0
1681 } else {
1682 $self->{gii}->remove($gpath);
1683 print "\tD\t$gpath\n" unless $self->{q};
1685 undef;
1688 sub open_file {
1689 my ($self, $path, $pb, $rev) = @_;
1690 my $gpath = $self->git_path($path);
1691 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1692 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1693 unless (defined $mode && defined $blob) {
1694 die "$path was not found in commit $self->{c} (r$rev)\n";
1696 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1697 pool => SVN::Pool->new, action => 'M' };
1700 sub add_file {
1701 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1702 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1703 delete $self->{empty}->{$dir};
1704 { path => $path, mode_a => 100644, mode_b => 100644,
1705 pool => SVN::Pool->new, action => 'A' };
1708 sub add_directory {
1709 my ($self, $path, $cp_path, $cp_rev) = @_;
1710 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1711 delete $self->{empty}->{$dir};
1712 $self->{empty}->{$path} = 1;
1713 { path => $path };
1716 sub change_dir_prop {
1717 my ($self, $db, $prop, $value) = @_;
1718 $self->{dir_prop}->{$db->{path}} ||= {};
1719 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1720 undef;
1723 sub absent_directory {
1724 my ($self, $path, $pb) = @_;
1725 $self->{absent_dir}->{$pb->{path}} ||= [];
1726 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1727 undef;
1730 sub absent_file {
1731 my ($self, $path, $pb) = @_;
1732 $self->{absent_file}->{$pb->{path}} ||= [];
1733 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1734 undef;
1737 sub change_file_prop {
1738 my ($self, $fb, $prop, $value) = @_;
1739 if ($prop eq 'svn:executable') {
1740 if ($fb->{mode_b} != 120000) {
1741 $fb->{mode_b} = defined $value ? 100755 : 100644;
1743 } elsif ($prop eq 'svn:special') {
1744 $fb->{mode_b} = defined $value ? 120000 : 100644;
1745 } else {
1746 $self->{file_prop}->{$fb->{path}} ||= {};
1747 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1749 undef;
1752 sub apply_textdelta {
1753 my ($self, $fb, $exp) = @_;
1754 my $fh = IO::File->new_tmpfile;
1755 $fh->autoflush(1);
1756 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1757 # (but $base does not,) so dup() it for reading in close_file
1758 open my $dup, '<&', $fh or croak $!;
1759 my $base = IO::File->new_tmpfile;
1760 $base->autoflush(1);
1761 if ($fb->{blob}) {
1762 defined (my $pid = fork) or croak $!;
1763 if (!$pid) {
1764 open STDOUT, '>&', $base or croak $!;
1765 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1766 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1768 waitpid $pid, 0;
1769 croak $? if $?;
1771 if (defined $exp) {
1772 seek $base, 0, 0 or croak $!;
1773 my $md5 = Digest::MD5->new;
1774 $md5->addfile($base);
1775 my $got = $md5->hexdigest;
1776 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1777 "expected: $exp\n",
1778 " got: $got\n" if ($got ne $exp);
1781 seek $base, 0, 0 or croak $!;
1782 $fb->{fh} = $dup;
1783 $fb->{base} = $base;
1784 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1787 sub close_file {
1788 my ($self, $fb, $exp) = @_;
1789 my $hash;
1790 my $path = $self->git_path($fb->{path});
1791 if (my $fh = $fb->{fh}) {
1792 seek($fh, 0, 0) or croak $!;
1793 my $md5 = Digest::MD5->new;
1794 $md5->addfile($fh);
1795 my $got = $md5->hexdigest;
1796 die "Checksum mismatch: $path\n",
1797 "expected: $exp\n got: $got\n" if ($got ne $exp);
1798 seek($fh, 0, 0) or croak $!;
1799 if ($fb->{mode_b} == 120000) {
1800 read($fh, my $buf, 5) == 5 or croak $!;
1801 $buf eq 'link ' or die "$path has mode 120000",
1802 "but is not a link\n";
1804 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1805 if (!$pid) {
1806 open STDIN, '<&', $fh or croak $!;
1807 exec qw/git-hash-object -w --stdin/ or croak $!;
1809 chomp($hash = do { local $/; <$out> });
1810 close $out or croak $!;
1811 close $fh or croak $!;
1812 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1813 close $fb->{base} or croak $!;
1814 } else {
1815 $hash = $fb->{blob} or die "no blob information\n";
1817 $fb->{pool}->clear;
1818 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1819 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1820 undef;
1823 sub abort_edit {
1824 my $self = shift;
1825 $self->{nr} = $self->{gii}->{nr};
1826 delete $self->{gii};
1827 $self->SUPER::abort_edit(@_);
1830 sub close_edit {
1831 my $self = shift;
1832 $self->{git_commit_ok} = 1;
1833 $self->{nr} = $self->{gii}->{nr};
1834 delete $self->{gii};
1835 $self->SUPER::close_edit(@_);
1838 package SVN::Git::Editor;
1839 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1840 use strict;
1841 use warnings;
1842 use Carp qw/croak/;
1843 use IO::File;
1844 use Digest::MD5;
1846 sub new {
1847 my ($class, $opts) = @_;
1848 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1849 die "$_ required!\n" unless (defined $opts->{$_});
1852 my $pool = SVN::Pool->new;
1853 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1854 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1855 $opts->{r}, $mods);
1857 # $opts->{ra} functions should not be used after this:
1858 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
1859 $opts->{editor_cb}, $pool);
1860 my $self = SVN::Delta::Editor->new(@ce, $pool);
1861 bless $self, $class;
1862 foreach (qw/svn_path r tree_a tree_b/) {
1863 $self->{$_} = $opts->{$_};
1865 $self->{url} = $opts->{ra}->{url};
1866 $self->{mods} = $mods;
1867 $self->{types} = $types;
1868 $self->{pool} = $pool;
1869 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1870 $self->{rm} = { };
1871 $self->{path_prefix} = length $self->{svn_path} ?
1872 "$self->{svn_path}/" : '';
1873 return $self;
1876 sub generate_diff {
1877 my ($tree_a, $tree_b) = @_;
1878 my @diff_tree = qw(diff-tree -z -r);
1879 if ($_cp_similarity) {
1880 push @diff_tree, "-C$_cp_similarity";
1881 } else {
1882 push @diff_tree, '-C';
1884 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1885 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1886 push @diff_tree, $tree_a, $tree_b;
1887 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1888 local $/ = "\0";
1889 my $state = 'meta';
1890 my @mods;
1891 while (<$diff_fh>) {
1892 chomp $_; # this gets rid of the trailing "\0"
1893 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1894 $::sha1\s($::sha1)\s
1895 ([MTCRAD])\d*$/xo) {
1896 push @mods, { mode_a => $1, mode_b => $2,
1897 sha1_b => $3, chg => $4 };
1898 if ($4 =~ /^(?:C|R)$/) {
1899 $state = 'file_a';
1900 } else {
1901 $state = 'file_b';
1903 } elsif ($state eq 'file_a') {
1904 my $x = $mods[$#mods] or croak "Empty array\n";
1905 if ($x->{chg} !~ /^(?:C|R)$/) {
1906 croak "Error parsing $_, $x->{chg}\n";
1908 $x->{file_a} = $_;
1909 $state = 'file_b';
1910 } elsif ($state eq 'file_b') {
1911 my $x = $mods[$#mods] or croak "Empty array\n";
1912 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1913 croak "Error parsing $_, $x->{chg}\n";
1915 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1916 croak "Error parsing $_, $x->{chg}\n";
1918 $x->{file_b} = $_;
1919 $state = 'meta';
1920 } else {
1921 croak "Error parsing $_\n";
1924 command_close_pipe($diff_fh, $ctx);
1925 \@mods;
1928 sub check_diff_paths {
1929 my ($ra, $pfx, $rev, $mods) = @_;
1930 my %types;
1931 $pfx .= '/' if length $pfx;
1933 sub type_diff_paths {
1934 my ($ra, $types, $path, $rev) = @_;
1935 my @p = split m#/+#, $path;
1936 my $c = shift @p;
1937 unless (defined $types->{$c}) {
1938 $types->{$c} = $ra->check_path($c, $rev);
1940 while (@p) {
1941 $c .= '/' . shift @p;
1942 next if defined $types->{$c};
1943 $types->{$c} = $ra->check_path($c, $rev);
1947 foreach my $m (@$mods) {
1948 foreach my $f (qw/file_a file_b/) {
1949 next unless defined $m->{$f};
1950 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
1951 if (length $pfx.$dir && ! defined $types{$dir}) {
1952 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
1956 \%types;
1959 sub split_path {
1960 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1963 sub repo_path {
1964 my ($self, $path) = @_;
1965 $self->{path_prefix}.(defined $path ? $path : '');
1968 sub url_path {
1969 my ($self, $path) = @_;
1970 $self->{url} . '/' . $self->repo_path($path);
1973 sub rmdirs {
1974 my ($self) = @_;
1975 my $rm = $self->{rm};
1976 delete $rm->{''}; # we never delete the url we're tracking
1977 return unless %$rm;
1979 foreach (keys %$rm) {
1980 my @d = split m#/#, $_;
1981 my $c = shift @d;
1982 $rm->{$c} = 1;
1983 while (@d) {
1984 $c .= '/' . shift @d;
1985 $rm->{$c} = 1;
1988 delete $rm->{$self->{svn_path}};
1989 delete $rm->{''}; # we never delete the url we're tracking
1990 return unless %$rm;
1992 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
1993 $self->{tree_b});
1994 local $/ = "\0";
1995 while (<$fh>) {
1996 chomp;
1997 my @dn = split m#/#, $_;
1998 while (pop @dn) {
1999 delete $rm->{join '/', @dn};
2001 unless (%$rm) {
2002 close $fh;
2003 return;
2006 command_close_pipe($fh, $ctx);
2008 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2009 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2010 $self->close_directory($bat->{$d}, $p);
2011 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2012 print "\tD+\t$d/\n" unless $::_q;
2013 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2014 delete $bat->{$d};
2018 sub open_or_add_dir {
2019 my ($self, $full_path, $baton) = @_;
2020 my $t = $self->{types}->{$full_path};
2021 if (!defined $t) {
2022 die "$full_path not known in r$self->{r} or we have a bug!\n";
2024 if ($t == $SVN::Node::none) {
2025 return $self->add_directory($full_path, $baton,
2026 undef, -1, $self->{pool});
2027 } elsif ($t == $SVN::Node::dir) {
2028 return $self->open_directory($full_path, $baton,
2029 $self->{r}, $self->{pool});
2031 print STDERR "$full_path already exists in repository at ",
2032 "r$self->{r} and it is not a directory (",
2033 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2034 exit 1;
2037 sub ensure_path {
2038 my ($self, $path) = @_;
2039 my $bat = $self->{bat};
2040 my $repo_path = $self->repo_path($path);
2041 return $bat->{''} unless (length $repo_path);
2042 my @p = split m#/+#, $repo_path;
2043 my $c = shift @p;
2044 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2045 while (@p) {
2046 my $c0 = $c;
2047 $c .= '/' . shift @p;
2048 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2050 return $bat->{$c};
2053 sub A {
2054 my ($self, $m) = @_;
2055 my ($dir, $file) = split_path($m->{file_b});
2056 my $pbat = $self->ensure_path($dir);
2057 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2058 undef, -1);
2059 print "\tA\t$m->{file_b}\n" unless $::_q;
2060 $self->chg_file($fbat, $m);
2061 $self->close_file($fbat,undef,$self->{pool});
2064 sub C {
2065 my ($self, $m) = @_;
2066 my ($dir, $file) = split_path($m->{file_b});
2067 my $pbat = $self->ensure_path($dir);
2068 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2069 $self->url_path($m->{file_a}), $self->{r});
2070 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2071 $self->chg_file($fbat, $m);
2072 $self->close_file($fbat,undef,$self->{pool});
2075 sub delete_entry {
2076 my ($self, $path, $pbat) = @_;
2077 my $rpath = $self->repo_path($path);
2078 my ($dir, $file) = split_path($rpath);
2079 $self->{rm}->{$dir} = 1;
2080 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2083 sub R {
2084 my ($self, $m) = @_;
2085 my ($dir, $file) = split_path($m->{file_b});
2086 my $pbat = $self->ensure_path($dir);
2087 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2088 $self->url_path($m->{file_a}), $self->{r});
2089 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2090 $self->chg_file($fbat, $m);
2091 $self->close_file($fbat,undef,$self->{pool});
2093 ($dir, $file) = split_path($m->{file_a});
2094 $pbat = $self->ensure_path($dir);
2095 $self->delete_entry($m->{file_a}, $pbat);
2098 sub M {
2099 my ($self, $m) = @_;
2100 my ($dir, $file) = split_path($m->{file_b});
2101 my $pbat = $self->ensure_path($dir);
2102 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2103 $pbat,$self->{r},$self->{pool});
2104 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2105 $self->chg_file($fbat, $m);
2106 $self->close_file($fbat,undef,$self->{pool});
2109 sub T { shift->M(@_) }
2111 sub change_file_prop {
2112 my ($self, $fbat, $pname, $pval) = @_;
2113 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2116 sub chg_file {
2117 my ($self, $fbat, $m) = @_;
2118 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2119 $self->change_file_prop($fbat,'svn:executable','*');
2120 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2121 $self->change_file_prop($fbat,'svn:executable',undef);
2123 my $fh = IO::File->new_tmpfile or croak $!;
2124 if ($m->{mode_b} =~ /^120/) {
2125 print $fh 'link ' or croak $!;
2126 $self->change_file_prop($fbat,'svn:special','*');
2127 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2128 $self->change_file_prop($fbat,'svn:special',undef);
2130 defined(my $pid = fork) or croak $!;
2131 if (!$pid) {
2132 open STDOUT, '>&', $fh or croak $!;
2133 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2135 waitpid $pid, 0;
2136 croak $? if $?;
2137 $fh->flush == 0 or croak $!;
2138 seek $fh, 0, 0 or croak $!;
2140 my $md5 = Digest::MD5->new;
2141 $md5->addfile($fh) or croak $!;
2142 seek $fh, 0, 0 or croak $!;
2144 my $exp = $md5->hexdigest;
2145 my $pool = SVN::Pool->new;
2146 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2147 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2148 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2149 $pool->clear;
2151 close $fh or croak $!;
2154 sub D {
2155 my ($self, $m) = @_;
2156 my ($dir, $file) = split_path($m->{file_b});
2157 my $pbat = $self->ensure_path($dir);
2158 print "\tD\t$m->{file_b}\n" unless $::_q;
2159 $self->delete_entry($m->{file_b}, $pbat);
2162 sub close_edit {
2163 my ($self) = @_;
2164 my ($p,$bat) = ($self->{pool}, $self->{bat});
2165 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2166 $self->close_directory($bat->{$_}, $p);
2168 $self->SUPER::close_edit($p);
2169 $p->clear;
2172 sub abort_edit {
2173 my ($self) = @_;
2174 $self->SUPER::abort_edit($self->{pool});
2177 sub DESTROY {
2178 my $self = shift;
2179 $self->SUPER::DESTROY(@_);
2180 $self->{pool}->clear;
2183 # this drives the editor
2184 sub apply_diff {
2185 my ($self) = @_;
2186 my $mods = $self->{mods};
2187 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2188 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2189 my $f = $m->{chg};
2190 if (defined $o{$f}) {
2191 $self->$f($m);
2192 } else {
2193 fatal("Invalid change type: $f\n");
2196 $self->rmdirs if $_rmdir;
2197 if (@$mods == 0) {
2198 $self->abort_edit;
2199 } else {
2200 $self->close_edit;
2202 return scalar @$mods;
2205 package Git::SVN::Ra;
2206 use vars qw/@ISA $config_dir/;
2207 use strict;
2208 use warnings;
2209 my ($can_do_switch);
2210 my $RA;
2212 BEGIN {
2213 # enforce temporary pool usage for some simple functions
2214 my $e;
2215 foreach (qw/get_latest_revnum rev_proplist get_file
2216 check_path get_dir get_uuid get_repos_root/) {
2217 $e .= "sub $_ {
2218 my \$self = shift;
2219 my \$pool = SVN::Pool->new;
2220 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2221 \$pool->clear;
2222 wantarray ? \@ret : \$ret[0]; }\n";
2224 eval $e;
2227 sub new {
2228 my ($class, $url) = @_;
2229 $url =~ s!/+$!!;
2230 return $RA if ($RA && $RA->{url} eq $url);
2232 SVN::_Core::svn_config_ensure($config_dir, undef);
2233 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2234 SVN::Client::get_simple_provider(),
2235 SVN::Client::get_ssl_server_trust_file_provider(),
2236 SVN::Client::get_simple_prompt_provider(
2237 \&Git::SVN::Prompt::simple, 2),
2238 SVN::Client::get_ssl_client_cert_prompt_provider(
2239 \&Git::SVN::Prompt::ssl_client_cert, 2),
2240 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2241 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2242 SVN::Client::get_username_provider(),
2243 SVN::Client::get_ssl_server_trust_prompt_provider(
2244 \&Git::SVN::Prompt::ssl_server_trust),
2245 SVN::Client::get_username_prompt_provider(
2246 \&Git::SVN::Prompt::username, 2),
2248 my $config = SVN::Core::config_get_config($config_dir);
2249 my $self = SVN::Ra->new(url => $url, auth => $baton,
2250 config => $config,
2251 pool => SVN::Pool->new,
2252 auth_provider_callbacks => $callbacks);
2253 $self->{svn_path} = $url;
2254 $self->{repos_root} = $self->get_repos_root;
2255 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2256 $RA = bless $self, $class;
2259 sub DESTROY {
2260 # do not call the real DESTROY since we store ourselves in $RA
2263 sub get_log {
2264 my ($self, @args) = @_;
2265 my $pool = SVN::Pool->new;
2266 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2267 my $ret = $self->SUPER::get_log(@args, $pool);
2268 $pool->clear;
2269 $ret;
2272 sub get_commit_editor {
2273 my ($self, $log, $cb, $pool) = @_;
2274 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2275 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2278 sub uuid {
2279 my ($self) = @_;
2280 $self->{uuid} ||= $self->get_uuid;
2283 sub gs_do_update {
2284 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2285 my $new = ($rev_a == $rev_b);
2286 my $path = $gs->{path};
2288 my $ta = $self->check_path($path, $rev_a);
2289 my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2290 return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2291 if ($ta == $SVN::Node::none) {
2292 $rev_a = $rev_b;
2293 $new = 1;
2296 my $pool = SVN::Pool->new;
2297 $editor->set_path_strip($path);
2298 my (@pc) = split m#/#, $path;
2299 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2300 1, $editor, $pool);
2301 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2303 # Since we can't rely on svn_ra_reparent being available, we'll
2304 # just have to do some magic with set_path to make it so
2305 # we only want a partial path.
2306 my $sp = '';
2307 my $final = join('/', @pc);
2308 while (@pc) {
2309 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2310 $sp .= '/' if length $sp;
2311 $sp .= shift @pc;
2313 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2315 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2317 $reporter->finish_report($pool);
2318 $pool->clear;
2319 $editor->{git_commit_ok};
2322 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2323 # svn_ra_reparent didn't work before 1.4)
2324 sub gs_do_switch {
2325 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2326 my $path = $gs->{path};
2327 my $pool = SVN::Pool->new;
2329 my $full_url = $self->{url};
2330 my $old_url = $full_url;
2331 $full_url .= "/$path" if length $path;
2332 my ($ra, $reparented);
2333 if ($old_url ne $full_url) {
2334 if ($old_url !~ m#^svn(\+ssh)?://#) {
2335 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2336 $pool);
2337 $self->{url} = $full_url;
2338 $reparented = 1;
2339 } else {
2340 $ra = Git::SVN::Ra->new($full_url);
2343 $ra ||= $self;
2344 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2345 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2346 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2347 $reporter->finish_report($pool);
2349 if ($reparented) {
2350 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2351 $self->{url} = $old_url;
2354 $pool->clear;
2355 $editor->{git_commit_ok};
2358 sub gs_fetch_loop_common {
2359 my ($self, $base, $head, @gs) = @_;
2360 my $inc = 1000;
2361 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2362 foreach my $gs (@gs) {
2363 if (my $last_commit = $gs->last_commit) {
2364 $gs->assert_index_clean($last_commit);
2367 while (1) {
2368 my %revs;
2369 my $err;
2370 my $err_handler = $SVN::Error::handler;
2371 $SVN::Error::handler = sub {
2372 ($err) = @_;
2373 skip_unknown_revs($err);
2375 foreach my $gs (@gs) {
2376 $self->get_log([$gs->{path}], $min, $max, 0, 1, 1, sub
2377 { my ($paths, $rev) = @_;
2378 push @{$revs{$rev}},
2379 [ $gs,
2380 dup_changed_paths($paths) ] });
2382 next unless ($err && $max >= $head);
2384 print STDERR "Path '$gs->{path}' ",
2385 "was probably deleted:\n",
2386 $err->expanded_message,
2387 "\nWill attempt to follow ",
2388 "revisions r$min .. r$max ",
2389 "committed before the deletion\n";
2390 my $hi = $max;
2391 while (--$hi >= $min) {
2392 my $ok;
2393 $self->get_log([$gs->{path}], $min, $hi,
2394 0, 1, 1, sub {
2395 my ($paths, $rev) = @_;
2396 $ok = $rev;
2397 push @{$revs{$rev}}, [ $gs,
2398 dup_changed_paths($_[0])]});
2399 if ($ok) {
2400 print STDERR "r$min .. r$ok OK\n";
2401 last;
2405 $SVN::Error::handler = $err_handler;
2406 foreach my $r (sort {$a <=> $b} keys %revs) {
2407 foreach (@{$revs{$r}}) {
2408 my ($gs, $paths) = @$_;
2409 my $lr = $gs->last_rev;
2410 next if defined $lr && $lr >= $r;
2411 next if defined $gs->rev_db_get($r);
2412 if (my $log_entry = $gs->do_fetch($paths, $r)) {
2413 $gs->do_git_commit($log_entry);
2417 # pre-fill the .rev_db since it'll eventually get filled in
2418 # with '0' x40 if something new gets committed
2419 foreach my $gs (@gs) {
2420 next if defined $gs->rev_db_get($max);
2421 $gs->rev_db_set($max, 0 x40);
2423 last if $max >= $head;
2424 $min = $max + 1;
2425 $max += $inc;
2426 $max = $head if ($max > $head);
2430 sub minimize_url {
2431 my ($self) = @_;
2432 return $self->{url} if ($self->{url} eq $self->{repos_root});
2433 my $url = $self->{repos_root};
2434 my @components = split(m!/!, $self->{svn_path});
2435 my $c = '';
2436 do {
2437 $url .= "/$c" if length $c;
2438 eval { (ref $self)->new($url)->get_latest_revnum };
2439 } while ($@ && ($c = shift @components));
2440 $url;
2443 sub can_do_switch {
2444 my $self = shift;
2445 unless (defined $can_do_switch) {
2446 my $pool = SVN::Pool->new;
2447 my $rep = eval {
2448 $self->do_switch(1, '', 0, $self->{url},
2449 SVN::Delta::Editor->new, $pool);
2451 if ($@) {
2452 $can_do_switch = 0;
2453 } else {
2454 $rep->abort_report($pool);
2455 $can_do_switch = 1;
2457 $pool->clear;
2459 $can_do_switch;
2462 sub skip_unknown_revs {
2463 my ($err) = @_;
2464 my $errno = $err->apr_err();
2465 # Maybe the branch we're tracking didn't
2466 # exist when the repo started, so it's
2467 # not an error if it doesn't, just continue
2469 # Wonderfully consistent library, eh?
2470 # 160013 - svn:// and file://
2471 # 175002 - http(s)://
2472 # 175007 - http(s):// (this repo required authorization, too...)
2473 # More codes may be discovered later...
2474 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2475 return;
2477 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2480 # svn_log_changed_path_t objects passed to get_log are likely to be
2481 # overwritten even if only the refs are copied to an external variable,
2482 # so we should dup the structures in their entirety. Using an externally
2483 # passed pool (instead of our temporary and quickly cleared pool in
2484 # Git::SVN::Ra) does not help matters at all...
2485 sub dup_changed_paths {
2486 my ($paths) = @_;
2487 return undef unless $paths;
2488 my %ret;
2489 foreach my $p (keys %$paths) {
2490 my $i = $paths->{$p};
2491 my %s = map { $_ => $i->$_ }
2492 qw/copyfrom_path copyfrom_rev action/;
2493 $ret{$p} = \%s;
2495 \%ret;
2498 package Git::SVN::Log;
2499 use strict;
2500 use warnings;
2501 use POSIX qw/strftime/;
2502 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2503 %rusers $show_commit $incremental/;
2504 my $l_fmt;
2506 sub cmt_showable {
2507 my ($c) = @_;
2508 return 1 if defined $c->{r};
2509 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2510 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2511 my @log = command(qw/cat-file commit/, $c->{c});
2512 shift @log while ($log[0] ne "\n");
2513 shift @log;
2514 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2516 (undef, $c->{r}, undef) = ::extract_metadata(
2517 (grep(/^git-svn-id: /, @log))[-1]);
2519 return defined $c->{r};
2522 sub log_use_color {
2523 return 1 if $color;
2524 my ($dc, $dcvar);
2525 $dcvar = 'color.diff';
2526 $dc = `git-config --get $dcvar`;
2527 if ($dc eq '') {
2528 # nothing at all; fallback to "diff.color"
2529 $dcvar = 'diff.color';
2530 $dc = `git-config --get $dcvar`;
2532 chomp($dc);
2533 if ($dc eq 'auto') {
2534 my $pc;
2535 $pc = `git-config --get color.pager`;
2536 if ($pc eq '') {
2537 # does not have it -- fallback to pager.color
2538 $pc = `git-config --bool --get pager.color`;
2540 else {
2541 $pc = `git-config --bool --get color.pager`;
2542 if ($?) {
2543 $pc = 'false';
2546 chomp($pc);
2547 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2548 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2550 return 0;
2552 return 0 if $dc eq 'never';
2553 return 1 if $dc eq 'always';
2554 chomp($dc = `git-config --bool --get $dcvar`);
2555 return ($dc eq 'true');
2558 sub git_svn_log_cmd {
2559 my ($r_min, $r_max) = @_;
2560 my $gs = Git::SVN->_new;
2561 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2562 $gs->refname);
2563 push @cmd, '-r' unless $non_recursive;
2564 push @cmd, qw/--raw --name-status/ if $verbose;
2565 push @cmd, '--color' if log_use_color();
2566 return @cmd unless defined $r_max;
2567 if ($r_max == $r_min) {
2568 push @cmd, '--max-count=1';
2569 if (my $c = $gs->rev_db_get($r_max)) {
2570 push @cmd, $c;
2572 } else {
2573 my ($c_min, $c_max);
2574 $c_max = $gs->rev_db_get($r_max);
2575 $c_min = $gs->rev_db_get($r_min);
2576 if (defined $c_min && defined $c_max) {
2577 if ($r_max > $r_max) {
2578 push @cmd, "$c_min..$c_max";
2579 } else {
2580 push @cmd, "$c_max..$c_min";
2582 } elsif ($r_max > $r_min) {
2583 push @cmd, $c_max;
2584 } else {
2585 push @cmd, $c_min;
2588 return @cmd;
2591 # adapted from pager.c
2592 sub config_pager {
2593 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2594 if (!defined $pager) {
2595 $pager = 'less';
2596 } elsif (length $pager == 0 || $pager eq 'cat') {
2597 $pager = undef;
2601 sub run_pager {
2602 return unless -t *STDOUT;
2603 pipe my $rfd, my $wfd or return;
2604 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2605 if (!$pid) {
2606 open STDOUT, '>&', $wfd or
2607 ::fatal "Can't redirect to stdout: $!\n";
2608 return;
2610 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2611 $ENV{LESS} ||= 'FRSX';
2612 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2615 sub tz_to_s_offset {
2616 my ($tz) = @_;
2617 $tz =~ s/(\d\d)$//;
2618 return ($1 * 60) + ($tz * 3600);
2621 sub get_author_info {
2622 my ($dest, $author, $t, $tz) = @_;
2623 $author =~ s/(?:^\s*|\s*$)//g;
2624 $dest->{a_raw} = $author;
2625 my $au;
2626 if ($::_authors) {
2627 $au = $rusers{$author} || undef;
2629 if (!$au) {
2630 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2632 $dest->{t} = $t;
2633 $dest->{tz} = $tz;
2634 $dest->{a} = $au;
2635 # Date::Parse isn't in the standard Perl distro :(
2636 if ($tz =~ s/^\+//) {
2637 $t += tz_to_s_offset($tz);
2638 } elsif ($tz =~ s/^\-//) {
2639 $t -= tz_to_s_offset($tz);
2641 $dest->{t_utc} = $t;
2644 sub process_commit {
2645 my ($c, $r_min, $r_max, $defer) = @_;
2646 if (defined $r_min && defined $r_max) {
2647 if ($r_min == $c->{r} && $r_min == $r_max) {
2648 show_commit($c);
2649 return 0;
2651 return 1 if $r_min == $r_max;
2652 if ($r_min < $r_max) {
2653 # we need to reverse the print order
2654 return 0 if (defined $limit && --$limit < 0);
2655 push @$defer, $c;
2656 return 1;
2658 if ($r_min != $r_max) {
2659 return 1 if ($r_min < $c->{r});
2660 return 1 if ($r_max > $c->{r});
2663 return 0 if (defined $limit && --$limit < 0);
2664 show_commit($c);
2665 return 1;
2668 sub show_commit {
2669 my $c = shift;
2670 if ($oneline) {
2671 my $x = "\n";
2672 if (my $l = $c->{l}) {
2673 while ($l->[0] =~ /^\s*$/) { shift @$l }
2674 $x = $l->[0];
2676 $l_fmt ||= 'A' . length($c->{r});
2677 print 'r',pack($l_fmt, $c->{r}),' | ';
2678 print "$c->{c} | " if $show_commit;
2679 print $x;
2680 } else {
2681 show_commit_normal($c);
2685 sub show_commit_changed_paths {
2686 my ($c) = @_;
2687 return unless $c->{changed};
2688 print "Changed paths:\n", @{$c->{changed}};
2691 sub show_commit_normal {
2692 my ($c) = @_;
2693 print '-' x72, "\nr$c->{r} | ";
2694 print "$c->{c} | " if $show_commit;
2695 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2696 localtime($c->{t_utc})), ' | ';
2697 my $nr_line = 0;
2699 if (my $l = $c->{l}) {
2700 while ($l->[$#$l] eq "\n" && $#$l > 0
2701 && $l->[($#$l - 1)] eq "\n") {
2702 pop @$l;
2704 $nr_line = scalar @$l;
2705 if (!$nr_line) {
2706 print "1 line\n\n\n";
2707 } else {
2708 if ($nr_line == 1) {
2709 $nr_line = '1 line';
2710 } else {
2711 $nr_line .= ' lines';
2713 print $nr_line, "\n";
2714 show_commit_changed_paths($c);
2715 print "\n";
2716 print $_ foreach @$l;
2718 } else {
2719 print "1 line\n";
2720 show_commit_changed_paths($c);
2721 print "\n";
2724 foreach my $x (qw/raw diff/) {
2725 if ($c->{$x}) {
2726 print "\n";
2727 print $_ foreach @{$c->{$x}}
2732 sub cmd_show_log {
2733 my (@args) = @_;
2734 my ($r_min, $r_max);
2735 my $r_last = -1; # prevent dupes
2736 if (defined $TZ) {
2737 $ENV{TZ} = $TZ;
2738 } else {
2739 delete $ENV{TZ};
2741 if (defined $::_revision) {
2742 if ($::_revision =~ /^(\d+):(\d+)$/) {
2743 ($r_min, $r_max) = ($1, $2);
2744 } elsif ($::_revision =~ /^\d+$/) {
2745 $r_min = $r_max = $::_revision;
2746 } else {
2747 ::fatal "-r$::_revision is not supported, use ",
2748 "standard \'git log\' arguments instead\n";
2752 config_pager();
2753 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2754 my $log = command_output_pipe(@args);
2755 run_pager();
2756 my (@k, $c, $d);
2757 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2758 while (<$log>) {
2759 if (/^${esc_color}commit ($::sha1_short)/o) {
2760 my $cmt = $1;
2761 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2762 $r_last = $c->{r};
2763 process_commit($c, $r_min, $r_max, \@k) or
2764 goto out;
2766 $d = undef;
2767 $c = { c => $cmt };
2768 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2769 get_author_info($c, $1, $2, $3);
2770 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2771 # ignore
2772 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2773 push @{$c->{raw}}, $_;
2774 } elsif (/^${esc_color}[ACRMDT]\t/) {
2775 # we could add $SVN->{svn_path} here, but that requires
2776 # remote access at the moment (repo_path_split)...
2777 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2778 push @{$c->{changed}}, $_;
2779 } elsif (/^${esc_color}diff /o) {
2780 $d = 1;
2781 push @{$c->{diff}}, $_;
2782 } elsif ($d) {
2783 push @{$c->{diff}}, $_;
2784 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2785 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2786 } elsif (s/^${esc_color} //o) {
2787 push @{$c->{l}}, $_;
2790 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2791 $r_last = $c->{r};
2792 process_commit($c, $r_min, $r_max, \@k);
2794 if (@k) {
2795 my $swap = $r_max;
2796 $r_max = $r_min;
2797 $r_min = $swap;
2798 process_commit($_, $r_min, $r_max) foreach reverse @k;
2800 out:
2801 close $log;
2802 print '-' x72,"\n" unless $incremental || $oneline;
2805 package Git::SVN::Migration;
2806 # these version numbers do NOT correspond to actual version numbers
2807 # of git nor git-svn. They are just relative.
2809 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2811 # v1 layout: .git/$id/info/url, refs/remotes/$id
2813 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2815 # v3 layout: .git/svn/$id, refs/remotes/$id
2816 # - info/url may remain for backwards compatibility
2817 # - this is what we migrate up to this layout automatically,
2818 # - this will be used by git svn init on single branches
2820 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2821 # - this is only created for newly multi-init-ed
2822 # repositories. Similar in spirit to the
2823 # --use-separate-remotes option in git-clone (now default)
2824 # - we do not automatically migrate to this (following
2825 # the example set by core git)
2826 use strict;
2827 use warnings;
2828 use Carp qw/croak/;
2829 use File::Path qw/mkpath/;
2830 use File::Basename qw/dirname basename/;
2831 use vars qw/$_minimize/;
2833 sub migrate_from_v0 {
2834 my $git_dir = $ENV{GIT_DIR};
2835 return undef unless -d $git_dir;
2836 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2837 my $migrated = 0;
2838 while (<$fh>) {
2839 chomp;
2840 my ($id, $orig_ref) = ($_, $_);
2841 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2842 next unless -f "$git_dir/$id/info/url";
2843 my $new_ref = "refs/remotes/$id";
2844 if (::verify_ref("$new_ref^0")) {
2845 print STDERR "W: $orig_ref is probably an old ",
2846 "branch used by an ancient version of ",
2847 "git-svn.\n",
2848 "However, $new_ref also exists.\n",
2849 "We will not be able ",
2850 "to use this branch until this ",
2851 "ambiguity is resolved.\n";
2852 next;
2854 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2855 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2856 command_noisy('update-ref', $new_ref, $orig_ref);
2857 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2858 $migrated++;
2860 command_close_pipe($fh, $ctx);
2861 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2862 $migrated;
2865 sub migrate_from_v1 {
2866 my $git_dir = $ENV{GIT_DIR};
2867 my $migrated = 0;
2868 return $migrated unless -d $git_dir;
2869 my $svn_dir = "$git_dir/svn";
2871 # just in case somebody used 'svn' as their $id at some point...
2872 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2874 print STDERR "Migrating from a git-svn v1 layout...\n";
2875 mkpath([$svn_dir]);
2876 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2877 "$svn_dir\n\t(required for this version ",
2878 "($::VERSION) of git-svn) does not. exist\n";
2879 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2880 while (<$fh>) {
2881 my $x = $_;
2882 next unless $x =~ s#^refs/remotes/##;
2883 chomp $x;
2884 next unless -f "$git_dir/$x/info/url";
2885 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2886 next unless $u;
2887 my $dn = dirname("$git_dir/svn/$x");
2888 mkpath([$dn]) unless -d $dn;
2889 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2890 mkpath(["$git_dir/svn/svn"]);
2891 print STDERR " - $git_dir/$x/info => ",
2892 "$git_dir/svn/$x/info\n";
2893 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2894 croak "$!: $x";
2895 # don't worry too much about these, they probably
2896 # don't exist with repos this old (save for index,
2897 # and we can easily regenerate that)
2898 foreach my $f (qw/unhandled.log index .rev_db/) {
2899 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2901 } else {
2902 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2903 rename "$git_dir/$x", "$git_dir/svn/$x" or
2904 croak "$!: $x";
2906 $migrated++;
2908 command_close_pipe($fh, $ctx);
2909 print STDERR "Done migrating from a git-svn v1 layout\n";
2910 $migrated;
2913 sub read_old_urls {
2914 my ($l_map, $pfx, $path) = @_;
2915 my @dir;
2916 foreach (<$path/*>) {
2917 if (-r "$_/info/url") {
2918 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2919 my $ref_id = $pfx . basename $_;
2920 my $url = ::file_to_s("$_/info/url");
2921 $l_map->{$ref_id} = $url;
2922 } elsif (-d $_) {
2923 push @dir, $_;
2926 foreach (@dir) {
2927 my $x = $_;
2928 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2929 read_old_urls($l_map, $x, $_);
2933 sub migrate_from_v2 {
2934 my @cfg = command(qw/config -l/);
2935 return if grep /^svn-remote\..+\.url=/, @cfg;
2936 my %l_map;
2937 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2938 my $migrated = 0;
2940 foreach my $ref_id (sort keys %l_map) {
2941 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2942 $migrated++;
2944 $migrated;
2947 sub minimize_connections {
2948 my $r = Git::SVN::read_all_remotes();
2949 my $new_urls = {};
2950 my $root_repos = {};
2951 foreach my $repo_id (keys %$r) {
2952 my $url = $r->{$repo_id}->{url} or next;
2953 my $fetch = $r->{$repo_id}->{fetch} or next;
2954 my $ra = Git::SVN::Ra->new($url);
2956 # skip existing cases where we already connect to the root
2957 if (($ra->{url} eq $ra->{repos_root}) ||
2958 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2959 $repo_id)) {
2960 $root_repos->{$ra->{url}} = $repo_id;
2961 next;
2964 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2965 my $root_path = $ra->{url};
2966 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2967 foreach my $path (keys %$fetch) {
2968 my $ref_id = $fetch->{$path};
2969 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2971 # make sure we can read when connecting to
2972 # a higher level of a repository
2973 my ($last_rev, undef) = $gs->last_rev_commit;
2974 if (!defined $last_rev) {
2975 $last_rev = eval {
2976 $root_ra->get_latest_revnum;
2978 next if $@;
2980 my $new = $root_path;
2981 $new .= length $path ? "/$path" : '';
2982 eval {
2983 $root_ra->get_log([$new], $last_rev, $last_rev,
2984 0, 0, 1, sub { });
2986 next if $@;
2987 $new_urls->{$ra->{repos_root}}->{$new} =
2988 { ref_id => $ref_id,
2989 old_repo_id => $repo_id,
2990 old_path => $path };
2994 my @emptied;
2995 foreach my $url (keys %$new_urls) {
2996 # see if we can re-use an existing [svn-remote "repo_id"]
2997 # instead of creating a(n ugly) new section:
2998 my $repo_id = $root_repos->{$url} ||
2999 Git::SVN::sanitize_remote_name($url);
3001 my $fetch = $new_urls->{$url};
3002 foreach my $path (keys %$fetch) {
3003 my $x = $fetch->{$path};
3004 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3005 my $pfx = "svn-remote.$x->{old_repo_id}";
3007 my $old_fetch = quotemeta("$x->{old_path}:".
3008 "refs/remotes/$x->{ref_id}");
3009 command_noisy(qw/config --unset/,
3010 "$pfx.fetch", '^'. $old_fetch . '$');
3011 delete $r->{$x->{old_repo_id}}->
3012 {fetch}->{$x->{old_path}};
3013 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3014 command_noisy(qw/config --unset/,
3015 "$pfx.url");
3016 push @emptied, $x->{old_repo_id}
3020 if (@emptied) {
3021 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3022 "$ENV{GIT_DIR}/config";
3023 print STDERR <<EOF;
3024 The following [svn-remote] sections in your config file ($file) are empty
3025 and can be safely removed:
3027 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3031 sub migration_check {
3032 migrate_from_v0();
3033 migrate_from_v1();
3034 migrate_from_v2();
3035 minimize_connections() if $_minimize;
3038 package Git::IndexInfo;
3039 use strict;
3040 use warnings;
3041 use Git qw/command_input_pipe command_close_pipe/;
3043 sub new {
3044 my ($class) = @_;
3045 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3046 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3049 sub remove {
3050 my ($self, $path) = @_;
3051 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3052 return ++$self->{nr};
3054 undef;
3057 sub update {
3058 my ($self, $mode, $hash, $path) = @_;
3059 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3060 return ++$self->{nr};
3062 undef;
3065 sub DESTROY {
3066 my ($self) = @_;
3067 command_close_pipe($self->{gui}, $self->{ctx});
3070 __END__
3072 Data structures:
3074 $log_entry hashref as returned by libsvn_log_entry()
3076 log => 'whitespace-formatted log entry
3077 ', # trailing newline is preserved
3078 revision => '8', # integer
3079 date => '2004-02-24T17:01:44.108345Z', # commit date
3080 author => 'committer name'
3084 # this is generated by generate_diff();
3085 @mods = array of diff-index line hashes, each element represents one line
3086 of diff-index output
3088 diff-index line ($m hash)
3090 mode_a => first column of diff-index output, no leading ':',
3091 mode_b => second column of diff-index output,
3092 sha1_b => sha1sum of the final blob,
3093 chg => change type [MCRADT],
3094 file_a => original file name of a file (iff chg is 'C' or 'R')
3095 file_b => new/current file name of a file (any chg)
3099 # retval of read_url_paths{,_all}();
3100 $l_map = {
3101 # repository root url
3102 'https://svn.musicpd.org' => {
3103 # repository path # GIT_SVN_ID
3104 'mpd/trunk' => 'trunk',
3105 'mpd/tags/0.11.5' => 'tags/0.11.5',
3109 Notes:
3110 I don't trust the each() function on unless I created %hash myself
3111 because the internal iterator may not have started at base.