git-svn: include merges when calling rev-list for decommit
[git/dscho.git] / git-svn.perl
blob66653f9eb44ad2f834ccd8d53d59540c4d662df7
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 = '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 $sha1 = qr/[a-f\d]{40}/;
52 $sha1_short = qr/[a-f\d]{4,40}/;
53 my ($_stdin, $_help, $_edit,
54 $_message, $_file,
55 $_template, $_shared,
56 $_version,
57 $_merge, $_strategy, $_dry_run,
58 $_prefix);
59 $Git::SVN::_follow_parent = 1;
60 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
61 'config-dir=s' => \$Git::SVN::Ra::config_dir,
62 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
63 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
64 'authors-file|A=s' => \$_authors,
65 'repack:i' => \$Git::SVN::_repack,
66 'noMetadata' => \$Git::SVN::_no_metadata,
67 'useSvmProps' => \$Git::SVN::_use_svm_props,
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 $head ||= 'HEAD';
280 my ($url, $rev, $uuid);
281 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
282 my @refs;
283 my $c;
284 while (<$fh>) {
285 $c = $_;
286 chomp $c;
287 ($url, $rev, $uuid) = cmt_metadata($c);
288 last if (defined $url && defined $rev && defined $uuid);
289 unshift @refs, $c;
291 close $fh; # most likely breaking the pipe
292 unless (defined $url && defined $rev && defined $uuid) {
293 die "Unable to determine upstream SVN information from ",
294 "$head history:\n $ctx\n";
296 my $gs = Git::SVN->find_by_url($url) or
297 die "Can't determine fetch information for $url\n";
298 my $last_rev;
299 foreach my $d (@refs) {
300 if (!verify_ref("$d~1")) {
301 fatal "Commit $d\n",
302 "has no parent commit, and therefore ",
303 "nothing to diff against.\n",
304 "You should be working from a repository ",
305 "originally created by git-svn\n";
307 unless (defined $last_rev) {
308 (undef, $last_rev, undef) = cmt_metadata("$d~1");
309 unless (defined $last_rev) {
310 fatal "Unable to extract revision information ",
311 "from commit $d~1\n";
314 if ($_dry_run) {
315 print "diff-tree $d~1 $d\n";
316 } else {
317 my %ed_opts = ( r => $last_rev,
318 log => get_commit_entry($d)->{log},
319 ra => Git::SVN::Ra->new($url),
320 tree_a => "$d~1",
321 tree_b => $d,
322 editor_cb => sub {
323 print "Committed r$_[0]\n";
324 $last_rev = $_[0]; },
325 svn_path => '');
326 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
327 print "No changes\n$d~1 == $d\n";
331 return if $_dry_run;
332 $gs->fetch;
333 # we always want to rebase against the current HEAD, not any
334 # head that was passed to us
335 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
336 my @finish;
337 if (@diff) {
338 @finish = qw/rebase/;
339 push @finish, qw/--merge/ if $_merge;
340 push @finish, "--strategy=$_strategy" if $_strategy;
341 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
342 "using @finish:\n", "@diff";
343 } else {
344 print "No changes between current HEAD and ",
345 $gs->refname, "\nResetting to the latest ",
346 $gs->refname, "\n";
347 @finish = qw/reset --mixed/;
349 command_noisy(@finish, $gs->refname);
352 sub cmd_show_ignore {
353 my $gs = Git::SVN->new;
354 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
355 $gs->traverse_ignore(\*STDOUT, '', $r);
358 sub cmd_multi_init {
359 my $url = shift;
360 unless (defined $_trunk || defined $_branches || defined $_tags) {
361 usage(1);
363 do_git_init_db();
364 $_prefix = '' unless defined $_prefix;
365 $url =~ s#/+$## if defined $url;
366 if (defined $_trunk) {
367 my $trunk_ref = $_prefix . 'trunk';
368 # try both old-style and new-style lookups:
369 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
370 unless ($gs_trunk) {
371 my ($trunk_url, $trunk_path) =
372 complete_svn_url($url, $_trunk);
373 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
374 undef, $trunk_ref);
377 return unless defined $_branches || defined $_tags;
378 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
379 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
380 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
383 sub cmd_multi_fetch {
384 my $remotes = Git::SVN::read_all_remotes();
385 foreach my $repo_id (sort keys %$remotes) {
386 if ($remotes->{$repo_id}->{url}) {
387 Git::SVN::fetch_all($repo_id, $remotes);
392 # this command is special because it requires no metadata
393 sub cmd_commit_diff {
394 my ($ta, $tb, $url) = @_;
395 my $usage = "Usage: $0 commit-diff -r<revision> ".
396 "<tree-ish> <tree-ish> [<URL>]\n";
397 fatal($usage) if (!defined $ta || !defined $tb);
398 my $svn_path;
399 if (!defined $url) {
400 my $gs = eval { Git::SVN->new };
401 if (!$gs) {
402 fatal("Needed URL or usable git-svn --id in ",
403 "the command-line\n", $usage);
405 $url = $gs->{url};
406 $svn_path = $gs->{path};
408 unless (defined $_revision) {
409 fatal("-r|--revision is a required argument\n", $usage);
411 if (defined $_message && defined $_file) {
412 fatal("Both --message/-m and --file/-F specified ",
413 "for the commit message.\n",
414 "I have no idea what you mean\n");
416 if (defined $_file) {
417 $_message = file_to_s($_file);
418 } else {
419 $_message ||= get_commit_entry($tb)->{log};
421 my $ra ||= Git::SVN::Ra->new($url);
422 $svn_path ||= $ra->{svn_path};
423 my $r = $_revision;
424 if ($r eq 'HEAD') {
425 $r = $ra->get_latest_revnum;
426 } elsif ($r !~ /^\d+$/) {
427 die "revision argument: $r not understood by git-svn\n";
429 my %ed_opts = ( r => $r,
430 log => $_message,
431 ra => $ra,
432 tree_a => $ta,
433 tree_b => $tb,
434 editor_cb => sub { print "Committed r$_[0]\n" },
435 svn_path => $svn_path );
436 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
437 print "No changes\n$ta == $tb\n";
441 ########################### utility functions #########################
443 sub parse_revision_argument {
444 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
445 return (undef, undef);
447 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
448 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
449 return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
450 return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
451 die "revision argument: $_revision not understood by git-svn\n",
452 "Try using the command-line svn client instead\n";
455 sub complete_svn_url {
456 my ($url, $path) = @_;
457 $path =~ s#/+$##;
458 if ($path !~ m#^[a-z\+]+://#) {
459 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
460 fatal("E: '$path' is not a complete URL ",
461 "and a separate URL is not specified\n");
463 return ($url, $path);
465 return ($path, '');
468 sub complete_url_ls_init {
469 my ($ra, $repo_path, $switch, $pfx) = @_;
470 unless ($repo_path) {
471 print STDERR "W: $switch not specified\n";
472 return;
474 $repo_path =~ s#/+$##;
475 if ($repo_path =~ m#^[a-z\+]+://#) {
476 $ra = Git::SVN::Ra->new($repo_path);
477 $repo_path = '';
478 } else {
479 $repo_path =~ s#^/+##;
480 unless ($ra) {
481 fatal("E: '$repo_path' is not a complete URL ",
482 "and a separate URL is not specified\n");
485 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
486 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
487 my $url = $ra->{url};
488 my $remote_id;
489 my $remote_path;
490 foreach my $d (sort keys %$dirent) {
491 next if ($dirent->{$d}->kind != $SVN::Node::dir);
492 my $path = "$repo_path/$d";
493 my $ref = "$pfx$d";
494 my $gs = eval { Git::SVN->new($ref) };
495 # don't try to init already existing refs
496 unless ($gs) {
497 print "init $url/$path => $ref\n";
498 $gs = Git::SVN->init($url, $path, undef, $ref, 1);
500 if ($gs) {
501 my $k = "svn-remote.$gs->{repo_id}.url";
502 my $orig_url = eval {
503 command_oneline(qw/config --get/, $k)
505 if ($orig_url && ($orig_url ne $gs->{url})) {
506 die "$k already set: $orig_url\n",
507 "wanted to set to: $gs->{url}\n";
509 unless ($orig_url) {
510 command_oneline('config', $k, $gs->{url});
512 $remote_id = $gs->{repo_id};
513 last;
516 if (defined $remote_id) {
517 $remote_path = "$ra->{svn_path}/$repo_path/*";
518 $remote_path =~ s#/+#/#g;
519 $remote_path =~ s#^/##g;
520 my ($n) = ($switch =~ /^--(\w+)/);
521 if (length $pfx && $pfx !~ m#/$#) {
522 die "--prefix='$pfx' must have a trailing slash '/'\n";
524 command_noisy('config', "svn-remote.$remote_id.$n",
525 "$remote_path:refs/remotes/$pfx*");
529 sub verify_ref {
530 my ($ref) = @_;
531 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
532 { STDERR => 0 }); };
535 sub get_tree_from_treeish {
536 my ($treeish) = @_;
537 # $treeish can be a symbolic ref, too:
538 my $type = command_oneline(qw/cat-file -t/, $treeish);
539 my $expected;
540 while ($type eq 'tag') {
541 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
543 if ($type eq 'commit') {
544 $expected = (grep /^tree /, command(qw/cat-file commit/,
545 $treeish))[0];
546 ($expected) = ($expected =~ /^tree ($sha1)$/o);
547 die "Unable to get tree from $treeish\n" unless $expected;
548 } elsif ($type eq 'tree') {
549 $expected = $treeish;
550 } else {
551 die "$treeish is a $type, expected tree, tag or commit\n";
553 return $expected;
556 sub get_commit_entry {
557 my ($treeish) = shift;
558 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
559 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
560 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
561 open my $log_fh, '>', $commit_editmsg or croak $!;
563 my $type = command_oneline(qw/cat-file -t/, $treeish);
564 if ($type eq 'commit' || $type eq 'tag') {
565 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
566 $type, $treeish);
567 my $in_msg = 0;
568 while (<$msg_fh>) {
569 if (!$in_msg) {
570 $in_msg = 1 if (/^\s*$/);
571 } elsif (/^git-svn-id: /) {
572 # skip this for now, we regenerate the
573 # correct one on re-fetch anyways
574 # TODO: set *:merge properties or like...
575 } else {
576 print $log_fh $_ or croak $!;
579 command_close_pipe($msg_fh, $ctx);
581 close $log_fh or croak $!;
583 if ($_edit || ($type eq 'tree')) {
584 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
585 # TODO: strip out spaces, comments, like git-commit.sh
586 system($editor, $commit_editmsg);
588 rename $commit_editmsg, $commit_msg or croak $!;
589 open $log_fh, '<', $commit_msg or croak $!;
590 { local $/; chomp($log_entry{log} = <$log_fh>); }
591 close $log_fh or croak $!;
592 unlink $commit_msg;
593 \%log_entry;
596 sub s_to_file {
597 my ($str, $file, $mode) = @_;
598 open my $fd,'>',$file or croak $!;
599 print $fd $str,"\n" or croak $!;
600 close $fd or croak $!;
601 chmod ($mode &~ umask, $file) if (defined $mode);
604 sub file_to_s {
605 my $file = shift;
606 open my $fd,'<',$file or croak "$!: file: $file\n";
607 local $/;
608 my $ret = <$fd>;
609 close $fd or croak $!;
610 $ret =~ s/\s*$//s;
611 return $ret;
614 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
615 sub load_authors {
616 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
617 my $log = $cmd eq 'log';
618 while (<$authors>) {
619 chomp;
620 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
621 my ($user, $name, $email) = ($1, $2, $3);
622 if ($log) {
623 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
624 } else {
625 $users{$user} = [$name, $email];
628 close $authors or croak $!;
631 # convert GetOpt::Long specs for use by git-config
632 sub read_repo_config {
633 return unless -d $ENV{GIT_DIR};
634 my $opts = shift;
635 my @config_only;
636 foreach my $o (keys %$opts) {
637 # if we have mixedCase and a long option-only, then
638 # it's a config-only variable that we don't need for
639 # the command-line.
640 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
641 my $v = $opts->{$o};
642 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
643 $key =~ s/-//g;
644 my $arg = 'git-config';
645 $arg .= ' --int' if ($o =~ /[:=]i$/);
646 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
647 if (ref $v eq 'ARRAY') {
648 chomp(my @tmp = `$arg --get-all svn.$key`);
649 @$v = @tmp if @tmp;
650 } else {
651 chomp(my $tmp = `$arg --get svn.$key`);
652 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
653 $$v = $tmp;
657 delete @$opts{@config_only} if @config_only;
660 sub extract_metadata {
661 my $id = shift or return (undef, undef, undef);
662 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
663 \s([a-f\d\-]+)$/x);
664 if (!defined $rev || !$uuid || !$url) {
665 # some of the original repositories I made had
666 # identifiers like this:
667 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
669 return ($url, $rev, $uuid);
672 sub cmt_metadata {
673 return extract_metadata((grep(/^git-svn-id: /,
674 command(qw/cat-file commit/, shift)))[-1]);
677 package Git::SVN;
678 use strict;
679 use warnings;
680 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
681 $_repack $_repack_flags $_use_svm_props/;
682 use Carp qw/croak/;
683 use File::Path qw/mkpath/;
684 use File::Copy qw/copy/;
685 use IPC::Open3;
687 my $_repack_nr;
688 # properties that we do not log:
689 my %SKIP_PROP;
690 BEGIN {
691 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
692 svn:special svn:executable
693 svn:entry:committed-rev
694 svn:entry:last-author
695 svn:entry:uuid
696 svn:entry:committed-date/;
698 # some options are read globally, but can be overridden locally
699 # per [svn-remote "..."] section. Command-line options will *NOT*
700 # override options set in an [svn-remote "..."] section
701 my $e;
702 foreach (qw/follow_parent no_metadata use_svm_props/) {
703 my $key = $_;
704 $key =~ tr/_//d;
705 $e .= "sub $_ {
706 my (\$self) = \@_;
707 return \$self->{-$_} if exists \$self->{-$_};
708 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
709 eval { command_oneline(qw/config --get/, \$k) };
710 if (\$@) {
711 \$self->{-$_} = \$Git::SVN::_$_;
712 } else {
713 my \$v = command_oneline(qw/config --bool/,\$k);
714 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
716 return \$self->{-$_} }\n";
718 $e .= "1;\n";
719 eval $e or die $@;
722 my %LOCKFILES;
723 END { unlink keys %LOCKFILES if %LOCKFILES }
725 sub resolve_local_globs {
726 my ($url, $fetch, $glob_spec) = @_;
727 return unless defined $glob_spec;
728 my $ref = $glob_spec->{ref};
729 my $path = $glob_spec->{path};
730 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
731 next unless m#^refs/remotes/$ref->{regex}$#;
732 my $p = $1;
733 my $pathname = $path->full_path($p);
734 my $refname = $ref->full_path($p);
735 if (my $existing = $fetch->{$pathname}) {
736 if ($existing ne $refname) {
737 die "Refspec conflict:\n",
738 "existing: refs/remotes/$existing\n",
739 " globbed: refs/remotes/$refname\n";
741 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
742 $u =~ s!^\Q$url\E(/|$)!! or die
743 "refs/remotes/$refname: '$url' not found in '$u'\n";
744 if ($pathname ne $u) {
745 warn "W: Refspec glob conflict ",
746 "(ref: refs/remotes/$refname):\n",
747 "expected path: $pathname\n",
748 " real path: $u\n",
749 "Continuing ahead with $u\n";
750 next;
752 } else {
753 $fetch->{$pathname} = $refname;
758 sub fetch_all {
759 my ($repo_id, $remotes) = @_;
760 my $remote = $remotes->{$repo_id};
761 my $fetch = $remote->{fetch};
762 my $url = $remote->{url};
763 my (@gs, @globs);
764 my $ra = Git::SVN::Ra->new($url);
765 my $uuid = $ra->get_uuid;
766 my $head = $ra->get_latest_revnum;
767 my $base = $head;
769 # read the max revs for wildcard expansion (branches/*, tags/*)
770 foreach my $t (qw/branches tags/) {
771 defined $remote->{$t} or next;
772 push @globs, $remote->{$t};
773 my $max_rev = eval { tmp_config(qw/--int --get/,
774 "svn-remote.$repo_id.${t}-maxRev") };
775 if (defined $max_rev && ($max_rev < $base)) {
776 $base = $max_rev;
780 if ($fetch) {
781 foreach my $p (sort keys %$fetch) {
782 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
783 my $lr = $gs->rev_db_max;
784 if (defined $lr) {
785 $base = $lr if ($lr < $base);
787 push @gs, $gs;
790 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
793 sub read_all_remotes {
794 my $r = {};
795 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
796 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
797 $r->{$1}->{fetch}->{$2} = $3;
798 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
799 $r->{$1}->{url} = $2;
800 } elsif (m!^(.+)\.(branches|tags)=
801 (.*):refs/remotes/(.+)\s*$/!x) {
802 my ($p, $g) = ($3, $4);
803 my $rs = $r->{$1}->{$2} = {
804 t => $2,
805 remote => $1,
806 path => Git::SVN::GlobSpec->new($p),
807 ref => Git::SVN::GlobSpec->new($g) };
808 if (length($rs->{ref}->{right}) != 0) {
809 die "The '*' glob character must be the last ",
810 "character of '$g'\n";
817 sub init_vars {
818 if (defined $_repack) {
819 $_repack = 1000 if ($_repack <= 0);
820 $_repack_nr = $_repack;
821 $_repack_flags ||= '-d';
825 sub verify_remotes_sanity {
826 return unless -d $ENV{GIT_DIR};
827 my %seen;
828 foreach (command(qw/config -l/)) {
829 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
830 if ($seen{$1}) {
831 die "Remote ref refs/remote/$1 is tracked by",
832 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
833 "Please resolve this ambiguity in ",
834 "your git configuration file before ",
835 "continuing\n";
837 $seen{$1} = $_;
842 # we allow more chars than remotes2config.sh...
843 sub sanitize_remote_name {
844 my ($name) = @_;
845 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
846 $name;
849 sub find_existing_remote {
850 my ($url, $remotes) = @_;
851 my $existing;
852 foreach my $repo_id (keys %$remotes) {
853 my $u = $remotes->{$repo_id}->{url} or next;
854 next if $u ne $url;
855 $existing = $repo_id;
856 last;
858 $existing;
861 sub init_remote_config {
862 my ($self, $url, $no_write) = @_;
863 $url =~ s!/+$!!; # strip trailing slash
864 my $r = read_all_remotes();
865 my $existing = find_existing_remote($url, $r);
866 if ($existing) {
867 unless ($no_write) {
868 print STDERR "Using existing ",
869 "[svn-remote \"$existing\"]\n";
871 $self->{repo_id} = $existing;
872 } else {
873 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
874 $existing = find_existing_remote($min_url, $r);
875 if ($existing) {
876 unless ($no_write) {
877 print STDERR "Using existing ",
878 "[svn-remote \"$existing\"]\n";
880 $self->{repo_id} = $existing;
882 if ($min_url ne $url) {
883 unless ($no_write) {
884 print STDERR "Using higher level of URL: ",
885 "$url => $min_url\n";
887 my $old_path = $self->{path};
888 $self->{path} = $url;
889 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
890 if (length $old_path) {
891 $self->{path} .= "/$old_path";
893 $url = $min_url;
896 my $orig_url;
897 if (!$existing) {
898 # verify that we aren't overwriting anything:
899 $orig_url = eval {
900 command_oneline('config', '--get',
901 "svn-remote.$self->{repo_id}.url")
903 if ($orig_url && ($orig_url ne $url)) {
904 die "svn-remote.$self->{repo_id}.url already set: ",
905 "$orig_url\nwanted to set to: $url\n";
908 my ($xrepo_id, $xpath) = find_ref($self->refname);
909 if (defined $xpath) {
910 die "svn-remote.$xrepo_id.fetch already set to track ",
911 "$xpath:refs/remotes/", $self->refname, "\n";
913 unless ($no_write) {
914 command_noisy('config',
915 "svn-remote.$self->{repo_id}.url", $url);
916 command_noisy('config', '--add',
917 "svn-remote.$self->{repo_id}.fetch",
918 "$self->{path}:".$self->refname);
920 $self->{url} = $url;
923 sub find_by_url { # repos_root and, path are optional
924 my ($class, $full_url, $repos_root, $path) = @_;
925 my $remotes = read_all_remotes();
926 if (defined $full_url && defined $repos_root && !defined $path) {
927 $path = $full_url;
928 $path =~ s#^\Q$repos_root\E(?:/|$)##;
930 foreach my $repo_id (keys %$remotes) {
931 my $u = $remotes->{$repo_id}->{url} or next;
932 next if defined $repos_root && $repos_root ne $u;
934 my $fetch = $remotes->{$repo_id}->{fetch} || {};
935 foreach (qw/branches tags/) {
936 resolve_local_globs($u, $fetch,
937 $remotes->{$repo_id}->{$_});
939 my $p = $path;
940 unless (defined $p) {
941 $p = $full_url;
942 $p =~ s#^\Q$u\E(?:/|$)## or next;
944 foreach my $f (keys %$fetch) {
945 next if $f ne $p;
946 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
949 undef;
952 sub init {
953 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
954 my $self = _new($class, $repo_id, $ref_id, $path);
955 if (defined $url) {
956 $self->init_remote_config($url, $no_write);
958 $self;
961 sub find_ref {
962 my ($ref_id) = @_;
963 foreach (command(qw/config -l/)) {
964 next unless m!^svn-remote\.(.+)\.fetch=
965 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
966 my ($repo_id, $path, $ref) = ($1, $2, $3);
967 if ($ref eq $ref_id) {
968 $path = '' if ($path =~ m#^\./?#);
969 return ($repo_id, $path);
972 (undef, undef, undef);
975 sub new {
976 my ($class, $ref_id, $repo_id, $path) = @_;
977 if (defined $ref_id && !defined $repo_id && !defined $path) {
978 ($repo_id, $path) = find_ref($ref_id);
979 if (!defined $repo_id) {
980 die "Could not find a \"svn-remote.*.fetch\" key ",
981 "in the repository configuration matching: ",
982 "refs/remotes/$ref_id\n";
985 my $self = _new($class, $repo_id, $ref_id, $path);
986 if (!defined $self->{path} || !length $self->{path}) {
987 my $fetch = command_oneline('config', '--get',
988 "svn-remote.$repo_id.fetch",
989 ":refs/remotes/$ref_id\$") or
990 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
991 "\":refs/remotes/$ref_id\$\" in config\n";
992 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
994 $self->{url} = command_oneline('config', '--get',
995 "svn-remote.$repo_id.url") or
996 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
997 if ((-z $self->db_path || ! -e $self->db_path) &&
998 ::verify_ref($self->refname.'^0')) {
999 $self->rebuild;
1001 $self;
1004 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1006 sub svm_uuid {
1007 my ($self) = @_;
1008 return $self->{svm}->{uuid} if $self->svm;
1009 $self->ra;
1010 unless ($self->{svm}) {
1011 die "SVM UUID not cached, and reading remotely failed\n";
1013 $self->{svm}->{uuid};
1016 sub svm {
1017 my ($self) = @_;
1018 return $self->{svm} if $self->{svm};
1019 my $svm;
1020 # see if we have it in our config, first:
1021 eval {
1022 my $section = "svn-remote.$self->{repo_id}";
1023 $svm = {
1024 source => tmp_config('--get', "$section.svm-source"),
1025 uuid => tmp_config('--get', "$section.svm-uuid"),
1028 $self->{svm} = $svm if ($svm && $svm->{source} && $svm->{uuid});
1029 $self->{svm};
1032 sub _set_svm_vars {
1033 my ($self, $ra) = @_;
1034 return $ra if $self->svm;
1036 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1037 "(svm:source, svm:mirror, svm:mirror) ",
1038 "from the following URLs:\n" );
1039 sub read_svm_props {
1040 my ($self, $props) = @_;
1041 my $src = $props->{'svm:source'};
1042 my $mirror = $props->{'svm:mirror'};
1043 my $uuid = $props->{'svm:uuid'};
1044 return undef if (!$src || !$mirror || !$uuid);
1046 chomp($src, $mirror, $uuid);
1048 $uuid =~ m{^[0-9a-f\-]{30,}$}
1049 or die "doesn't look right - svm:uuid is '$uuid'\n";
1050 # don't know what a '!' is there for, also the
1051 # username is of no interest
1052 $src =~ s{/?!$}{$mirror};
1053 $src =~ s{/+$}{}; # no trailing slashes please
1054 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1056 my $section = "svn-remote.$self->{repo_id}";
1057 tmp_config('--add', "$section.svm-source", $src);
1058 tmp_config('--add', "$section.svm-uuid", $uuid);
1059 $self->{svm} = { source => $src , uuid => $uuid };
1060 return 1;
1063 my $r = $ra->get_latest_revnum;
1064 my $path = $self->{path};
1065 my @tried_a = ($path);
1066 while (length $path) {
1067 if ($self->read_svm_props(($ra->get_dir($path, $r))[2])) {
1068 return $ra;
1070 $path =~ s#/?[^/]+$## && push @tried_a, $path;
1072 if ($self->read_svm_props(($ra->get_dir('', $r))[2])) {
1073 return $ra;
1076 if ($ra->{repos_root} eq $self->{url}) {
1077 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n";
1080 # nope, make sure we're connected to the repository root:
1081 my $ok;
1082 my @tried_b;
1083 $path = $ra->{svn_path};
1084 $path =~ s#/?[^/]+$##; # we already tried this one above
1085 $ra = Git::SVN::Ra->new($ra->{repos_root});
1086 while (length $path) {
1087 $ok = $self->read_svm_props(($ra->get_dir($path, $r))[2]);
1088 last if $ok;
1089 $path =~ s#/?[^/]+$## && push @tried_b, $path;
1091 $ok = $self->read_svm_props(($ra->get_dir('', $r))[2]) unless $ok;
1092 if (!$ok) {
1093 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n",
1094 map { " $ra->{url}/$_\n" } @tried_b, "\n"
1096 Git::SVN::Ra->new($self->{url});
1099 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1100 # remote lookup (useful for 'git svn log').
1101 sub ra_uuid {
1102 my ($self) = @_;
1103 unless ($self->{ra_uuid}) {
1104 my $key = "svn-remote.$self->{repo_id}.uuid";
1105 my $uuid = eval { tmp_config('--get', $key) };
1106 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1107 $self->{ra_uuid} = $uuid;
1108 } else {
1109 die "ra_uuid called without URL\n" unless $self->{url};
1110 $self->{ra_uuid} = $self->ra->get_uuid;
1111 tmp_config('--add', $key, $self->{ra_uuid});
1114 $self->{ra_uuid};
1117 sub ra {
1118 my ($self) = shift;
1119 my $ra = Git::SVN::Ra->new($self->{url});
1120 if ($self->use_svm_props && !$self->{svm}) {
1121 if ($self->no_metadata) {
1122 die "Can't have both 'noMetadata' and ",
1123 "'useSvmProps' options set!\n";
1125 $ra = $self->_set_svm_vars($ra);
1126 $self->{-want_revprops} = 1;
1128 $ra;
1131 sub rel_path {
1132 my ($self) = @_;
1133 my $repos_root = $self->ra->{repos_root};
1134 return $self->{path} if ($self->{url} eq $repos_root);
1135 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
1136 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
1139 sub traverse_ignore {
1140 my ($self, $fh, $path, $r) = @_;
1141 $path =~ s#^/+##g;
1142 my $ra = $self->ra;
1143 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1144 my $p = $path;
1145 $p =~ s#^\Q$ra->{svn_path}\E/##;
1146 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1147 if (my $s = $props->{'svn:ignore'}) {
1148 $s =~ s/[\r\n]+/\n/g;
1149 chomp $s;
1150 if (length $p == 0) {
1151 $s =~ s#\n#\n/$p#g;
1152 print $fh "/$s\n";
1153 } else {
1154 $s =~ s#\n#\n/$p/#g;
1155 print $fh "/$p/$s\n";
1158 foreach (sort keys %$dirent) {
1159 next if $dirent->{$_}->kind != $SVN::Node::dir;
1160 $self->traverse_ignore($fh, "$path/$_", $r);
1164 sub last_rev { ($_[0]->last_rev_commit)[0] }
1165 sub last_commit { ($_[0]->last_rev_commit)[1] }
1167 # returns the newest SVN revision number and newest commit SHA1
1168 sub last_rev_commit {
1169 my ($self) = @_;
1170 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1171 return ($self->{last_rev}, $self->{last_commit});
1173 my $c = ::verify_ref($self->refname.'^0');
1174 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1175 my $rev = (::cmt_metadata($c))[1];
1176 if (defined $rev) {
1177 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1178 return ($rev, $c);
1181 my $db_path = $self->db_path;
1182 unless (-e $db_path) {
1183 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1184 return (undef, undef);
1186 my $offset = -41; # from tail
1187 my $rl;
1188 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1189 sysseek($fh, $offset, 2); # don't care for errors
1190 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1191 chomp $rl;
1192 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1193 $offset -= 41;
1194 sysseek($fh, $offset, 2); # don't care for errors
1195 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1196 chomp $rl;
1198 if ($c && $c ne $rl) {
1199 die "$db_path and ", $self->refname,
1200 " inconsistent!:\n$c != $rl\n";
1202 my $rev = sysseek($fh, 0, 1) or croak $!;
1203 $rev = ($rev - 41) / 41;
1204 close $fh or croak $!;
1205 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1206 return ($rev, $c);
1209 sub get_fetch_range {
1210 my ($self, $min, $max) = @_;
1211 $max ||= $self->ra->get_latest_revnum;
1212 $min ||= $self->rev_db_max;
1213 (++$min, $max);
1216 sub tmp_config {
1217 my (@args) = @_;
1218 my $config = "$ENV{GIT_DIR}/svn/config";
1219 unless (-f $config) {
1220 open my $fh, '>', $config or
1221 die "Can't open $config: $!\n";
1222 print $fh "; This file is used internally by git-svn\n" or
1223 die "Couldn't write to $config: $!\n";
1224 print $fh "; You should not have to edit it\n" or
1225 die "Couldn't write to $config: $!\n";
1226 close $fh or die "Couldn't close $config: $!\n";
1228 my $old_config = $ENV{GIT_CONFIG};
1229 $ENV{GIT_CONFIG} = $config;
1230 $@ = undef;
1231 my @ret = eval { command('config', @args) };
1232 my $err = $@;
1233 if (defined $old_config) {
1234 $ENV{GIT_CONFIG} = $old_config;
1235 } else {
1236 delete $ENV{GIT_CONFIG};
1238 die $err if $err;
1239 wantarray ? @ret : $ret[0];
1242 sub tmp_index_do {
1243 my ($self, $sub) = @_;
1244 my $old_index = $ENV{GIT_INDEX_FILE};
1245 $ENV{GIT_INDEX_FILE} = $self->{index};
1246 $@ = undef;
1247 my @ret = eval { &$sub };
1248 my $err = $@;
1249 if (defined $old_index) {
1250 $ENV{GIT_INDEX_FILE} = $old_index;
1251 } else {
1252 delete $ENV{GIT_INDEX_FILE};
1254 die $err if $err;
1255 wantarray ? @ret : $ret[0];
1258 sub assert_index_clean {
1259 my ($self, $treeish) = @_;
1261 $self->tmp_index_do(sub {
1262 command_noisy('read-tree', $treeish) unless -e $self->{index};
1263 my $x = command_oneline('write-tree');
1264 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1265 /^tree ($::sha1)/mo);
1266 if ($y ne $x) {
1267 unlink $self->{index} or croak $!;
1268 command_noisy('read-tree', $treeish);
1270 $x = command_oneline('write-tree');
1271 if ($y ne $x) {
1272 ::fatal "trees ($treeish) $y != $x\n",
1273 "Something is seriously wrong...\n";
1278 sub get_commit_parents {
1279 my ($self, $log_entry) = @_;
1280 my (%seen, @ret, @tmp);
1281 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1282 if (my $ip = $self->{inject_parents}) {
1283 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1284 push @tmp, $commit;
1287 if (my $cur = ::verify_ref($self->refname.'^0')) {
1288 push @tmp, $cur;
1290 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1291 while (my $p = shift @tmp) {
1292 next if $seen{$p};
1293 $seen{$p} = 1;
1294 push @ret, $p;
1295 # MAXPARENT is defined to 16 in commit-tree.c:
1296 last if @ret >= 16;
1298 if (@tmp) {
1299 die "r$log_entry->{revision}: No room for parents:\n\t",
1300 join("\n\t", @tmp), "\n";
1302 @ret;
1305 sub full_url {
1306 my ($self) = @_;
1307 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1310 sub do_git_commit {
1311 my ($self, $log_entry) = @_;
1312 my $lr = $self->last_rev;
1313 if (defined $lr && $lr >= $log_entry->{revision}) {
1314 die "Last fetched revision of ", $self->refname,
1315 " was r$lr, but we are about to fetch: ",
1316 "r$log_entry->{revision}!\n";
1318 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1319 croak "$log_entry->{revision} = $c already exists! ",
1320 "Why are we refetching it?\n";
1322 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1323 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1324 $log_entry->{email};
1325 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1327 my $tree = $log_entry->{tree};
1328 if (!defined $tree) {
1329 $tree = $self->tmp_index_do(sub {
1330 command_oneline('write-tree') });
1332 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1334 my @exec = ('git-commit-tree', $tree);
1335 foreach ($self->get_commit_parents($log_entry)) {
1336 push @exec, '-p', $_;
1338 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1339 or croak $!;
1340 print $msg_fh $log_entry->{log} or croak $!;
1341 unless ($self->no_metadata) {
1342 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1343 or croak $!;
1345 $msg_fh->flush == 0 or croak $!;
1346 close $msg_fh or croak $!;
1347 chomp(my $commit = do { local $/; <$out_fh> });
1348 close $out_fh or croak $!;
1349 waitpid $pid, 0;
1350 croak $? if $?;
1351 if ($commit !~ /^$::sha1$/o) {
1352 die "Failed to commit, invalid sha1: $commit\n";
1355 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1357 $self->{last_rev} = $log_entry->{revision};
1358 $self->{last_commit} = $commit;
1359 print "r$log_entry->{revision}";
1360 if (defined $log_entry->{svm_revision}) {
1361 print " (\@$log_entry->{svm_revision})";
1362 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1363 0, $self->svm_uuid);
1365 print " = $commit ($self->{ref_id})\n";
1366 if (defined $_repack && (--$_repack_nr == 0)) {
1367 $_repack_nr = $_repack;
1368 # repack doesn't use any arguments with spaces in them, does it?
1369 print "Running git repack $_repack_flags ...\n";
1370 command_noisy('repack', split(/\s+/, $_repack_flags));
1371 print "Done repacking\n";
1373 return $commit;
1376 sub match_paths {
1377 my ($self, $paths, $r) = @_;
1378 return 1 if $self->{path} eq '';
1379 if (my $path = $paths->{"/$self->{path}"}) {
1380 return ($path->{action} eq 'D') ? 0 : 1;
1382 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1383 if (grep /$self->{path_regex}/, keys %$paths) {
1384 return 1;
1386 my $c = '';
1387 foreach (split m#/#, $self->{path}) {
1388 $c .= "/$_";
1389 next unless ($paths->{$c} &&
1390 ($paths->{$c}->{action} =~ /^[AR]$/));
1391 if ($self->ra->check_path($self->{path}, $r) ==
1392 $SVN::Node::dir) {
1393 return 1;
1396 return 0;
1399 sub find_parent_branch {
1400 my ($self, $paths, $rev) = @_;
1401 return undef unless $self->follow_parent;
1402 unless (defined $paths) {
1403 my $err_handler = $SVN::Error::handler;
1404 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1405 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1406 $paths =
1407 Git::SVN::Ra::dup_changed_paths($_[0]) });
1408 $SVN::Error::handler = $err_handler;
1410 return undef unless defined $paths;
1412 # look for a parent from another branch:
1413 my @b_path_components = split m#/#, $self->rel_path;
1414 my @a_path_components;
1415 my $i;
1416 while (@b_path_components) {
1417 $i = $paths->{'/'.join('/', @b_path_components)};
1418 last if $i && defined $i->{copyfrom_path};
1419 unshift(@a_path_components, pop(@b_path_components));
1421 return undef unless defined $i && defined $i->{copyfrom_path};
1422 my $branch_from = $i->{copyfrom_path};
1423 if (@a_path_components) {
1424 print STDERR "branch_from: $branch_from => ";
1425 $branch_from .= '/'.join('/', @a_path_components);
1426 print STDERR $branch_from, "\n";
1428 my $r = $i->{copyfrom_rev};
1429 my $repos_root = $self->ra->{repos_root};
1430 my $url = $self->ra->{url};
1431 my $new_url = $repos_root . $branch_from;
1432 print STDERR "Found possible branch point: ",
1433 "$new_url => ", $self->full_url, ", $r\n";
1434 $branch_from =~ s#^/##;
1435 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1436 unless ($gs) {
1437 my $ref_id = $self->{ref_id};
1438 $ref_id =~ s/\@\d+$//;
1439 $ref_id .= "\@$r";
1440 # just grow a tail if we're not unique enough :x
1441 $ref_id .= '-' while find_ref($ref_id);
1442 print STDERR "Initializing parent: $ref_id\n";
1443 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1445 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1446 if (!defined $r0 || !defined $parent) {
1447 $gs->fetch(0, $r);
1448 ($r0, $parent) = $gs->last_rev_commit;
1450 if (defined $r0 && defined $parent) {
1451 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1452 $self->assert_index_clean($parent);
1453 my $ed;
1454 if ($self->ra->can_do_switch) {
1455 print STDERR "Following parent with do_switch\n";
1456 # do_switch works with svn/trunk >= r22312, but that
1457 # is not included with SVN 1.4.3 (the latest version
1458 # at the moment), so we can't rely on it
1459 $self->{last_commit} = $parent;
1460 $ed = SVN::Git::Fetcher->new($self);
1461 $gs->ra->gs_do_switch($r0, $rev, $gs,
1462 $self->full_url, $ed)
1463 or die "SVN connection failed somewhere...\n";
1464 } else {
1465 print STDERR "Following parent with do_update\n";
1466 $ed = SVN::Git::Fetcher->new($self);
1467 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1468 or die "SVN connection failed somewhere...\n";
1470 print STDERR "Successfully followed parent\n";
1471 return $self->make_log_entry($rev, [$parent], $ed);
1473 return undef;
1476 sub do_fetch {
1477 my ($self, $paths, $rev) = @_;
1478 my $ed;
1479 my ($last_rev, @parents);
1480 if (my $lc = $self->last_commit) {
1481 # we can have a branch that was deleted, then re-added
1482 # under the same name but copied from another path, in
1483 # which case we'll have multiple parents (we don't
1484 # want to break the original ref, nor lose copypath info):
1485 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1486 push @{$log_entry->{parents}}, $lc;
1487 return $log_entry;
1489 $ed = SVN::Git::Fetcher->new($self);
1490 $last_rev = $self->{last_rev};
1491 $ed->{c} = $lc;
1492 @parents = ($lc);
1493 } else {
1494 $last_rev = $rev;
1495 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1496 return $log_entry;
1498 $ed = SVN::Git::Fetcher->new($self);
1500 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1501 die "SVN connection failed somewhere...\n";
1503 $self->make_log_entry($rev, \@parents, $ed);
1506 sub get_untracked {
1507 my ($self, $ed) = @_;
1508 my @out;
1509 my $h = $ed->{empty};
1510 foreach (sort keys %$h) {
1511 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1512 push @out, " $act: " . uri_encode($_);
1513 warn "W: $act: $_\n";
1515 foreach my $t (qw/dir_prop file_prop/) {
1516 $h = $ed->{$t} or next;
1517 foreach my $path (sort keys %$h) {
1518 my $ppath = $path eq '' ? '.' : $path;
1519 foreach my $prop (sort keys %{$h->{$path}}) {
1520 next if $SKIP_PROP{$prop};
1521 my $v = $h->{$path}->{$prop};
1522 my $t_ppath_prop = "$t: " .
1523 uri_encode($ppath) . ' ' .
1524 uri_encode($prop);
1525 if (defined $v) {
1526 push @out, " +$t_ppath_prop " .
1527 uri_encode($v);
1528 } else {
1529 push @out, " -$t_ppath_prop";
1534 foreach my $t (qw/absent_file absent_directory/) {
1535 $h = $ed->{$t} or next;
1536 foreach my $parent (sort keys %$h) {
1537 foreach my $path (sort @{$h->{$parent}}) {
1538 push @out, " $t: " .
1539 uri_encode("$parent/$path");
1540 warn "W: $t: $parent/$path ",
1541 "Insufficient permissions?\n";
1545 \@out;
1548 sub parse_svn_date {
1549 my $date = shift || return '+0000 1970-01-01 00:00:00';
1550 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1551 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1552 croak "Unable to parse date: $date\n";
1553 "+0000 $Y-$m-$d $H:$M:$S";
1556 sub check_author {
1557 my ($author) = @_;
1558 if (!defined $author || length $author == 0) {
1559 $author = '(no author)';
1561 if (defined $::_authors && ! defined $::users{$author}) {
1562 die "Author: $author not defined in $::_authors file\n";
1564 $author;
1567 sub make_log_entry {
1568 my ($self, $rev, $parents, $ed) = @_;
1569 my $untracked = $self->get_untracked($ed);
1571 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1572 print $un "r$rev\n" or croak $!;
1573 print $un $_, "\n" foreach @$untracked;
1574 my %log_entry = ( parents => $parents || [], revision => $rev,
1575 log => '');
1577 my $headrev;
1578 my $logged = delete $self->{logged_rev_props};
1579 if (!$logged || $self->{-want_revprops}) {
1580 my $rp = $self->ra->rev_proplist($rev);
1581 foreach (sort keys %$rp) {
1582 my $v = $rp->{$_};
1583 if (/^svn:(author|date|log)$/) {
1584 $log_entry{$1} = $v;
1585 } elsif ($_ eq 'svm:headrev') {
1586 $headrev = $v;
1587 } else {
1588 print $un " rev_prop: ", uri_encode($_), ' ',
1589 uri_encode($v), "\n";
1592 } else {
1593 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1595 close $un or croak $!;
1597 $log_entry{date} = parse_svn_date($log_entry{date});
1598 $log_entry{log} .= "\n";
1599 my $author = $log_entry{author} = check_author($log_entry{author});
1600 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1601 : ($author, undef);
1602 if (defined $headrev && $self->use_svm_props) {
1603 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1604 if ($uuid ne $self->{svm}->{uuid}) {
1605 die "UUID mismatch on SVM path:\n",
1606 "expected: $self->{svm}->{uuid}\n",
1607 " got: $uuid\n";
1609 my $full_url = $self->{svm}->{source};
1610 $full_url .= "/$self->{path}" if length $self->{path};
1611 $log_entry{metadata} = "$full_url\@$r $uuid";
1612 $log_entry{svm_revision} = $r;
1613 $email ||= "$author\@$uuid"
1614 } else {
1615 $log_entry{metadata} = $self->full_url . "\@$rev " .
1616 $self->ra->get_uuid;
1617 $email ||= "$author\@" . $self->ra->get_uuid;
1619 $log_entry{name} = $name;
1620 $log_entry{email} = $email;
1621 \%log_entry;
1624 sub fetch {
1625 my ($self, $min_rev, $max_rev, @parents) = @_;
1626 my ($last_rev, $last_commit) = $self->last_rev_commit;
1627 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1628 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1631 sub set_tree_cb {
1632 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1633 $self->{inject_parents} = { $rev => $tree };
1634 $self->fetch(undef, undef);
1637 sub set_tree {
1638 my ($self, $tree) = (shift, shift);
1639 my $log_entry = ::get_commit_entry($tree);
1640 unless ($self->{last_rev}) {
1641 fatal("Must have an existing revision to commit\n");
1643 my %ed_opts = ( r => $self->{last_rev},
1644 log => $log_entry->{log},
1645 ra => $self->ra,
1646 tree_a => $self->{last_commit},
1647 tree_b => $tree,
1648 editor_cb => sub {
1649 $self->set_tree_cb($log_entry, $tree, @_) },
1650 svn_path => $self->{path} );
1651 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1652 print "No changes\nr$self->{last_rev} = $tree\n";
1656 sub rebuild {
1657 my ($self) = @_;
1658 my $db_path = $self->db_path;
1659 if (-f $self->{db_root}) {
1660 rename $self->{db_root}, $db_path or die
1661 "rename $self->{db_root} => $db_path failed: $!\n";
1662 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1663 symlink $base, $self->{db_root} or die
1664 "symlink $base => $self->{db_root} failed: $!\n";
1665 return;
1667 print "Rebuilding $db_path ...\n";
1668 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1669 my $latest;
1670 my $full_url = $self->full_url;
1671 my $svn_uuid;
1672 while (<$rev_list>) {
1673 chomp;
1674 my $c = $_;
1675 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1676 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1678 # ignore merges (from set-tree)
1679 next if (!defined $rev || !$uuid);
1681 # if we merged or otherwise started elsewhere, this is
1682 # how we break out of it
1683 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1684 ($full_url && $url && ($url ne $full_url))) {
1685 next;
1687 $latest ||= $rev;
1688 $svn_uuid ||= $uuid;
1690 $self->rev_db_set($rev, $c);
1691 print "r$rev = $c\n";
1693 command_close_pipe($rev_list, $ctx);
1694 print "Done rebuilding $db_path\n";
1697 # rev_db:
1698 # Tie::File seems to be prone to offset errors if revisions get sparse,
1699 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1700 # one of my favorite modules is out :< Next up would be one of the DBM
1701 # modules, but I'm not sure which is most portable... So I'll just
1702 # go with something that's plain-text, but still capable of
1703 # being randomly accessed. So here's my ultra-simple fixed-width
1704 # database. All records are 40 characters + "\n", so it's easy to seek
1705 # to a revision: (41 * rev) is the byte offset.
1706 # A record of 40 0s denotes an empty revision.
1707 # And yes, it's still pretty fast (faster than Tie::File).
1708 # These files are disposable unless noMetadata or useSvmProps is set
1710 sub _rev_db_set {
1711 my ($fh, $rev, $commit) = @_;
1712 my $offset = $rev * 41;
1713 # assume that append is the common case:
1714 seek $fh, 0, 2 or croak $!;
1715 my $pos = tell $fh;
1716 if ($pos < $offset) {
1717 for (1 .. (($offset - $pos) / 41)) {
1718 print $fh (('0' x 40),"\n") or croak $!;
1721 seek $fh, $offset, 0 or croak $!;
1722 print $fh $commit,"\n" or croak $!;
1725 sub mkfile {
1726 my ($path) = @_;
1727 unless (-e $path) {
1728 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1729 mkpath([$dir]) unless -d $dir;
1730 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1731 close $fh or die "Couldn't close (create) $path: $!\n";
1735 sub rev_db_set {
1736 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1737 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1738 my $db = $self->db_path($uuid);
1739 my $db_lock = "$db.lock";
1740 my $sig;
1741 if ($update_ref) {
1742 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1743 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1745 mkfile($db);
1747 $LOCKFILES{$db_lock} = 1;
1748 my $sync;
1749 # both of these options make our .rev_db file very, very important
1750 # and we can't afford to lose it because rebuild() won't work
1751 if ($self->use_svm_props || $self->no_metadata) {
1752 $sync = 1;
1753 copy($db, $db_lock) or die "rev_db_set(@_): ",
1754 "Failed to copy: ",
1755 "$db => $db_lock ($!)\n";
1756 } else {
1757 rename $db, $db_lock or die "rev_db_set(@_): ",
1758 "Failed to rename: ",
1759 "$db => $db_lock ($!)\n";
1761 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
1762 _rev_db_set($fh, $rev, $commit);
1763 if ($sync) {
1764 $fh->flush or die "Couldn't flush $db_lock: $!\n";
1765 $fh->sync or die "Couldn't sync $db_lock: $!\n";
1767 close $fh or croak $!;
1768 if ($update_ref) {
1769 command_noisy('update-ref', '-m', "r$rev",
1770 $self->refname, $commit);
1772 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1773 "$db_lock => $db ($!)\n";
1774 delete $LOCKFILES{$db_lock};
1775 if ($update_ref) {
1776 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1777 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1778 kill $sig, $$ if defined $sig;
1782 sub rev_db_max {
1783 my ($self) = @_;
1784 my $db_path = $self->db_path;
1785 my @stat = stat $db_path or return 0;
1786 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
1787 my $max = $stat[7] / 41;
1788 (($max > 0) ? $max - 1 : 0);
1791 sub rev_db_get {
1792 my ($self, $rev, $uuid) = @_;
1793 my $ret;
1794 my $offset = $rev * 41;
1795 my $db_path = $self->db_path($uuid);
1796 return undef unless -e $db_path;
1797 open my $fh, '<', $db_path or croak $!;
1798 if (sysseek($fh, $offset, 0) == $offset) {
1799 my $read = sysread($fh, $ret, 40);
1800 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1802 close $fh or croak $!;
1803 $ret;
1806 sub find_rev_before {
1807 my ($self, $rev, $eq_ok) = @_;
1808 --$rev unless $eq_ok;
1809 while ($rev > 0) {
1810 if (my $c = $self->rev_db_get($rev)) {
1811 return ($rev, $c);
1813 --$rev;
1815 return (undef, undef);
1818 sub _new {
1819 my ($class, $repo_id, $ref_id, $path) = @_;
1820 unless (defined $repo_id && length $repo_id) {
1821 $repo_id = $Git::SVN::default_repo_id;
1823 unless (defined $ref_id && length $ref_id) {
1824 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1826 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1827 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1828 $_[3] = $path = '' unless (defined $path);
1829 mkpath([$dir]);
1830 bless {
1831 ref_id => $ref_id, dir => $dir, index => "$dir/index",
1832 path => $path, config => "$ENV{GIT_DIR}/svn/config",
1833 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
1836 sub db_path {
1837 my ($self, $uuid) = @_;
1838 $uuid ||= $self->ra_uuid;
1839 "$self->{db_root}.$uuid";
1842 sub uri_encode {
1843 my ($f) = @_;
1844 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1848 package Git::SVN::Prompt;
1849 use strict;
1850 use warnings;
1851 require SVN::Core;
1852 use vars qw/$_no_auth_cache $_username/;
1854 sub simple {
1855 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1856 $may_save = undef if $_no_auth_cache;
1857 $default_username = $_username if defined $_username;
1858 if (defined $default_username && length $default_username) {
1859 if (defined $realm && length $realm) {
1860 print STDERR "Authentication realm: $realm\n";
1861 STDERR->flush;
1863 $cred->username($default_username);
1864 } else {
1865 username($cred, $realm, $may_save, $pool);
1867 $cred->password(_read_password("Password for '" .
1868 $cred->username . "': ", $realm));
1869 $cred->may_save($may_save);
1870 $SVN::_Core::SVN_NO_ERROR;
1873 sub ssl_server_trust {
1874 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1875 $may_save = undef if $_no_auth_cache;
1876 print STDERR "Error validating server certificate for '$realm':\n";
1877 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1878 print STDERR " - The certificate is not issued by a trusted ",
1879 "authority. Use the\n",
1880 " fingerprint to validate the certificate manually!\n";
1882 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1883 print STDERR " - The certificate hostname does not match.\n";
1885 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1886 print STDERR " - The certificate is not yet valid.\n";
1888 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1889 print STDERR " - The certificate has expired.\n";
1891 if ($failures & $SVN::Auth::SSL::OTHER) {
1892 print STDERR " - The certificate has an unknown error.\n";
1894 printf STDERR
1895 "Certificate information:\n".
1896 " - Hostname: %s\n".
1897 " - Valid: from %s until %s\n".
1898 " - Issuer: %s\n".
1899 " - Fingerprint: %s\n",
1900 map $cert_info->$_, qw(hostname valid_from valid_until
1901 issuer_dname fingerprint);
1902 my $choice;
1903 prompt:
1904 print STDERR $may_save ?
1905 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1906 "(R)eject or accept (t)emporarily? ";
1907 STDERR->flush;
1908 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1909 if ($choice =~ /^t$/i) {
1910 $cred->may_save(undef);
1911 } elsif ($choice =~ /^r$/i) {
1912 return -1;
1913 } elsif ($may_save && $choice =~ /^p$/i) {
1914 $cred->may_save($may_save);
1915 } else {
1916 goto prompt;
1918 $cred->accepted_failures($failures);
1919 $SVN::_Core::SVN_NO_ERROR;
1922 sub ssl_client_cert {
1923 my ($cred, $realm, $may_save, $pool) = @_;
1924 $may_save = undef if $_no_auth_cache;
1925 print STDERR "Client certificate filename: ";
1926 STDERR->flush;
1927 chomp(my $filename = <STDIN>);
1928 $cred->cert_file($filename);
1929 $cred->may_save($may_save);
1930 $SVN::_Core::SVN_NO_ERROR;
1933 sub ssl_client_cert_pw {
1934 my ($cred, $realm, $may_save, $pool) = @_;
1935 $may_save = undef if $_no_auth_cache;
1936 $cred->password(_read_password("Password: ", $realm));
1937 $cred->may_save($may_save);
1938 $SVN::_Core::SVN_NO_ERROR;
1941 sub username {
1942 my ($cred, $realm, $may_save, $pool) = @_;
1943 $may_save = undef if $_no_auth_cache;
1944 if (defined $realm && length $realm) {
1945 print STDERR "Authentication realm: $realm\n";
1947 my $username;
1948 if (defined $_username) {
1949 $username = $_username;
1950 } else {
1951 print STDERR "Username: ";
1952 STDERR->flush;
1953 chomp($username = <STDIN>);
1955 $cred->username($username);
1956 $cred->may_save($may_save);
1957 $SVN::_Core::SVN_NO_ERROR;
1960 sub _read_password {
1961 my ($prompt, $realm) = @_;
1962 print STDERR $prompt;
1963 STDERR->flush;
1964 require Term::ReadKey;
1965 Term::ReadKey::ReadMode('noecho');
1966 my $password = '';
1967 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1968 last if $key =~ /[\012\015]/; # \n\r
1969 $password .= $key;
1971 Term::ReadKey::ReadMode('restore');
1972 print STDERR "\n";
1973 STDERR->flush;
1974 $password;
1977 package main;
1980 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1981 $SVN::Node::dir.$SVN::Node::unknown.
1982 $SVN::Node::none.$SVN::Node::file.
1983 $SVN::Node::dir.$SVN::Node::unknown.
1984 $SVN::Auth::SSL::CNMISMATCH.
1985 $SVN::Auth::SSL::NOTYETVALID.
1986 $SVN::Auth::SSL::EXPIRED.
1987 $SVN::Auth::SSL::UNKNOWNCA.
1988 $SVN::Auth::SSL::OTHER;
1991 package SVN::Git::Fetcher;
1992 use vars qw/@ISA/;
1993 use strict;
1994 use warnings;
1995 use Carp qw/croak/;
1996 use IO::File qw//;
1997 use Digest::MD5;
1999 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2000 sub new {
2001 my ($class, $git_svn) = @_;
2002 my $self = SVN::Delta::Editor->new;
2003 bless $self, $class;
2004 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2005 $self->{empty} = {};
2006 $self->{dir_prop} = {};
2007 $self->{file_prop} = {};
2008 $self->{absent_dir} = {};
2009 $self->{absent_file} = {};
2010 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2011 $self;
2014 sub set_path_strip {
2015 my ($self, $path) = @_;
2016 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2019 sub open_root {
2020 { path => '' };
2023 sub open_directory {
2024 my ($self, $path, $pb, $rev) = @_;
2025 { path => $path };
2028 sub git_path {
2029 my ($self, $path) = @_;
2030 if ($self->{path_strip}) {
2031 $path =~ s!$self->{path_strip}!! or
2032 die "Failed to strip path '$path' ($self->{path_strip})\n";
2034 $path;
2037 sub delete_entry {
2038 my ($self, $path, $rev, $pb) = @_;
2040 my $gpath = $self->git_path($path);
2041 return undef if ($gpath eq '');
2043 # remove entire directories.
2044 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2045 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2046 -r --name-only -z/,
2047 $self->{c}, '--', $gpath);
2048 local $/ = "\0";
2049 while (<$ls>) {
2050 chomp;
2051 $self->{gii}->remove($_);
2052 print "\tD\t$_\n" unless $::_q;
2054 print "\tD\t$gpath/\n" unless $::_q;
2055 command_close_pipe($ls, $ctx);
2056 $self->{empty}->{$path} = 0
2057 } else {
2058 $self->{gii}->remove($gpath);
2059 print "\tD\t$gpath\n" unless $::_q;
2061 undef;
2064 sub open_file {
2065 my ($self, $path, $pb, $rev) = @_;
2066 my $gpath = $self->git_path($path);
2067 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2068 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2069 unless (defined $mode && defined $blob) {
2070 die "$path was not found in commit $self->{c} (r$rev)\n";
2072 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2073 pool => SVN::Pool->new, action => 'M' };
2076 sub add_file {
2077 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2078 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2079 delete $self->{empty}->{$dir};
2080 { path => $path, mode_a => 100644, mode_b => 100644,
2081 pool => SVN::Pool->new, action => 'A' };
2084 sub add_directory {
2085 my ($self, $path, $cp_path, $cp_rev) = @_;
2086 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2087 delete $self->{empty}->{$dir};
2088 $self->{empty}->{$path} = 1;
2089 { path => $path };
2092 sub change_dir_prop {
2093 my ($self, $db, $prop, $value) = @_;
2094 $self->{dir_prop}->{$db->{path}} ||= {};
2095 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2096 undef;
2099 sub absent_directory {
2100 my ($self, $path, $pb) = @_;
2101 $self->{absent_dir}->{$pb->{path}} ||= [];
2102 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2103 undef;
2106 sub absent_file {
2107 my ($self, $path, $pb) = @_;
2108 $self->{absent_file}->{$pb->{path}} ||= [];
2109 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2110 undef;
2113 sub change_file_prop {
2114 my ($self, $fb, $prop, $value) = @_;
2115 if ($prop eq 'svn:executable') {
2116 if ($fb->{mode_b} != 120000) {
2117 $fb->{mode_b} = defined $value ? 100755 : 100644;
2119 } elsif ($prop eq 'svn:special') {
2120 $fb->{mode_b} = defined $value ? 120000 : 100644;
2121 } else {
2122 $self->{file_prop}->{$fb->{path}} ||= {};
2123 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2125 undef;
2128 sub apply_textdelta {
2129 my ($self, $fb, $exp) = @_;
2130 my $fh = IO::File->new_tmpfile;
2131 $fh->autoflush(1);
2132 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2133 # (but $base does not,) so dup() it for reading in close_file
2134 open my $dup, '<&', $fh or croak $!;
2135 my $base = IO::File->new_tmpfile;
2136 $base->autoflush(1);
2137 if ($fb->{blob}) {
2138 defined (my $pid = fork) or croak $!;
2139 if (!$pid) {
2140 open STDOUT, '>&', $base or croak $!;
2141 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2142 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2144 waitpid $pid, 0;
2145 croak $? if $?;
2147 if (defined $exp) {
2148 seek $base, 0, 0 or croak $!;
2149 my $md5 = Digest::MD5->new;
2150 $md5->addfile($base);
2151 my $got = $md5->hexdigest;
2152 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2153 "expected: $exp\n",
2154 " got: $got\n" if ($got ne $exp);
2157 seek $base, 0, 0 or croak $!;
2158 $fb->{fh} = $dup;
2159 $fb->{base} = $base;
2160 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2163 sub close_file {
2164 my ($self, $fb, $exp) = @_;
2165 my $hash;
2166 my $path = $self->git_path($fb->{path});
2167 if (my $fh = $fb->{fh}) {
2168 seek($fh, 0, 0) or croak $!;
2169 my $md5 = Digest::MD5->new;
2170 $md5->addfile($fh);
2171 my $got = $md5->hexdigest;
2172 die "Checksum mismatch: $path\n",
2173 "expected: $exp\n got: $got\n" if ($got ne $exp);
2174 seek($fh, 0, 0) or croak $!;
2175 if ($fb->{mode_b} == 120000) {
2176 read($fh, my $buf, 5) == 5 or croak $!;
2177 $buf eq 'link ' or die "$path has mode 120000",
2178 "but is not a link\n";
2180 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2181 if (!$pid) {
2182 open STDIN, '<&', $fh or croak $!;
2183 exec qw/git-hash-object -w --stdin/ or croak $!;
2185 chomp($hash = do { local $/; <$out> });
2186 close $out or croak $!;
2187 close $fh or croak $!;
2188 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2189 close $fb->{base} or croak $!;
2190 } else {
2191 $hash = $fb->{blob} or die "no blob information\n";
2193 $fb->{pool}->clear;
2194 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2195 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2196 undef;
2199 sub abort_edit {
2200 my $self = shift;
2201 $self->{nr} = $self->{gii}->{nr};
2202 delete $self->{gii};
2203 $self->SUPER::abort_edit(@_);
2206 sub close_edit {
2207 my $self = shift;
2208 $self->{git_commit_ok} = 1;
2209 $self->{nr} = $self->{gii}->{nr};
2210 delete $self->{gii};
2211 $self->SUPER::close_edit(@_);
2214 package SVN::Git::Editor;
2215 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2216 use strict;
2217 use warnings;
2218 use Carp qw/croak/;
2219 use IO::File;
2220 use Digest::MD5;
2222 sub new {
2223 my ($class, $opts) = @_;
2224 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2225 die "$_ required!\n" unless (defined $opts->{$_});
2228 my $pool = SVN::Pool->new;
2229 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2230 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2231 $opts->{r}, $mods);
2233 # $opts->{ra} functions should not be used after this:
2234 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2235 $opts->{editor_cb}, $pool);
2236 my $self = SVN::Delta::Editor->new(@ce, $pool);
2237 bless $self, $class;
2238 foreach (qw/svn_path r tree_a tree_b/) {
2239 $self->{$_} = $opts->{$_};
2241 $self->{url} = $opts->{ra}->{url};
2242 $self->{mods} = $mods;
2243 $self->{types} = $types;
2244 $self->{pool} = $pool;
2245 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2246 $self->{rm} = { };
2247 $self->{path_prefix} = length $self->{svn_path} ?
2248 "$self->{svn_path}/" : '';
2249 return $self;
2252 sub generate_diff {
2253 my ($tree_a, $tree_b) = @_;
2254 my @diff_tree = qw(diff-tree -z -r);
2255 if ($_cp_similarity) {
2256 push @diff_tree, "-C$_cp_similarity";
2257 } else {
2258 push @diff_tree, '-C';
2260 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2261 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2262 push @diff_tree, $tree_a, $tree_b;
2263 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2264 local $/ = "\0";
2265 my $state = 'meta';
2266 my @mods;
2267 while (<$diff_fh>) {
2268 chomp $_; # this gets rid of the trailing "\0"
2269 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2270 $::sha1\s($::sha1)\s
2271 ([MTCRAD])\d*$/xo) {
2272 push @mods, { mode_a => $1, mode_b => $2,
2273 sha1_b => $3, chg => $4 };
2274 if ($4 =~ /^(?:C|R)$/) {
2275 $state = 'file_a';
2276 } else {
2277 $state = 'file_b';
2279 } elsif ($state eq 'file_a') {
2280 my $x = $mods[$#mods] or croak "Empty array\n";
2281 if ($x->{chg} !~ /^(?:C|R)$/) {
2282 croak "Error parsing $_, $x->{chg}\n";
2284 $x->{file_a} = $_;
2285 $state = 'file_b';
2286 } elsif ($state eq 'file_b') {
2287 my $x = $mods[$#mods] or croak "Empty array\n";
2288 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2289 croak "Error parsing $_, $x->{chg}\n";
2291 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2292 croak "Error parsing $_, $x->{chg}\n";
2294 $x->{file_b} = $_;
2295 $state = 'meta';
2296 } else {
2297 croak "Error parsing $_\n";
2300 command_close_pipe($diff_fh, $ctx);
2301 \@mods;
2304 sub check_diff_paths {
2305 my ($ra, $pfx, $rev, $mods) = @_;
2306 my %types;
2307 $pfx .= '/' if length $pfx;
2309 sub type_diff_paths {
2310 my ($ra, $types, $path, $rev) = @_;
2311 my @p = split m#/+#, $path;
2312 my $c = shift @p;
2313 unless (defined $types->{$c}) {
2314 $types->{$c} = $ra->check_path($c, $rev);
2316 while (@p) {
2317 $c .= '/' . shift @p;
2318 next if defined $types->{$c};
2319 $types->{$c} = $ra->check_path($c, $rev);
2323 foreach my $m (@$mods) {
2324 foreach my $f (qw/file_a file_b/) {
2325 next unless defined $m->{$f};
2326 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2327 if (length $pfx.$dir && ! defined $types{$dir}) {
2328 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2332 \%types;
2335 sub split_path {
2336 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2339 sub repo_path {
2340 my ($self, $path) = @_;
2341 $self->{path_prefix}.(defined $path ? $path : '');
2344 sub url_path {
2345 my ($self, $path) = @_;
2346 $self->{url} . '/' . $self->repo_path($path);
2349 sub rmdirs {
2350 my ($self) = @_;
2351 my $rm = $self->{rm};
2352 delete $rm->{''}; # we never delete the url we're tracking
2353 return unless %$rm;
2355 foreach (keys %$rm) {
2356 my @d = split m#/#, $_;
2357 my $c = shift @d;
2358 $rm->{$c} = 1;
2359 while (@d) {
2360 $c .= '/' . shift @d;
2361 $rm->{$c} = 1;
2364 delete $rm->{$self->{svn_path}};
2365 delete $rm->{''}; # we never delete the url we're tracking
2366 return unless %$rm;
2368 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2369 $self->{tree_b});
2370 local $/ = "\0";
2371 while (<$fh>) {
2372 chomp;
2373 my @dn = split m#/#, $_;
2374 while (pop @dn) {
2375 delete $rm->{join '/', @dn};
2377 unless (%$rm) {
2378 close $fh;
2379 return;
2382 command_close_pipe($fh, $ctx);
2384 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2385 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2386 $self->close_directory($bat->{$d}, $p);
2387 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2388 print "\tD+\t$d/\n" unless $::_q;
2389 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2390 delete $bat->{$d};
2394 sub open_or_add_dir {
2395 my ($self, $full_path, $baton) = @_;
2396 my $t = $self->{types}->{$full_path};
2397 if (!defined $t) {
2398 die "$full_path not known in r$self->{r} or we have a bug!\n";
2400 if ($t == $SVN::Node::none) {
2401 return $self->add_directory($full_path, $baton,
2402 undef, -1, $self->{pool});
2403 } elsif ($t == $SVN::Node::dir) {
2404 return $self->open_directory($full_path, $baton,
2405 $self->{r}, $self->{pool});
2407 print STDERR "$full_path already exists in repository at ",
2408 "r$self->{r} and it is not a directory (",
2409 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2410 exit 1;
2413 sub ensure_path {
2414 my ($self, $path) = @_;
2415 my $bat = $self->{bat};
2416 my $repo_path = $self->repo_path($path);
2417 return $bat->{''} unless (length $repo_path);
2418 my @p = split m#/+#, $repo_path;
2419 my $c = shift @p;
2420 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2421 while (@p) {
2422 my $c0 = $c;
2423 $c .= '/' . shift @p;
2424 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2426 return $bat->{$c};
2429 sub A {
2430 my ($self, $m) = @_;
2431 my ($dir, $file) = split_path($m->{file_b});
2432 my $pbat = $self->ensure_path($dir);
2433 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2434 undef, -1);
2435 print "\tA\t$m->{file_b}\n" unless $::_q;
2436 $self->chg_file($fbat, $m);
2437 $self->close_file($fbat,undef,$self->{pool});
2440 sub C {
2441 my ($self, $m) = @_;
2442 my ($dir, $file) = split_path($m->{file_b});
2443 my $pbat = $self->ensure_path($dir);
2444 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2445 $self->url_path($m->{file_a}), $self->{r});
2446 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2447 $self->chg_file($fbat, $m);
2448 $self->close_file($fbat,undef,$self->{pool});
2451 sub delete_entry {
2452 my ($self, $path, $pbat) = @_;
2453 my $rpath = $self->repo_path($path);
2454 my ($dir, $file) = split_path($rpath);
2455 $self->{rm}->{$dir} = 1;
2456 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2459 sub R {
2460 my ($self, $m) = @_;
2461 my ($dir, $file) = split_path($m->{file_b});
2462 my $pbat = $self->ensure_path($dir);
2463 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2464 $self->url_path($m->{file_a}), $self->{r});
2465 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2466 $self->chg_file($fbat, $m);
2467 $self->close_file($fbat,undef,$self->{pool});
2469 ($dir, $file) = split_path($m->{file_a});
2470 $pbat = $self->ensure_path($dir);
2471 $self->delete_entry($m->{file_a}, $pbat);
2474 sub M {
2475 my ($self, $m) = @_;
2476 my ($dir, $file) = split_path($m->{file_b});
2477 my $pbat = $self->ensure_path($dir);
2478 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2479 $pbat,$self->{r},$self->{pool});
2480 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2481 $self->chg_file($fbat, $m);
2482 $self->close_file($fbat,undef,$self->{pool});
2485 sub T { shift->M(@_) }
2487 sub change_file_prop {
2488 my ($self, $fbat, $pname, $pval) = @_;
2489 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2492 sub chg_file {
2493 my ($self, $fbat, $m) = @_;
2494 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2495 $self->change_file_prop($fbat,'svn:executable','*');
2496 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2497 $self->change_file_prop($fbat,'svn:executable',undef);
2499 my $fh = IO::File->new_tmpfile or croak $!;
2500 if ($m->{mode_b} =~ /^120/) {
2501 print $fh 'link ' or croak $!;
2502 $self->change_file_prop($fbat,'svn:special','*');
2503 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2504 $self->change_file_prop($fbat,'svn:special',undef);
2506 defined(my $pid = fork) or croak $!;
2507 if (!$pid) {
2508 open STDOUT, '>&', $fh or croak $!;
2509 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2511 waitpid $pid, 0;
2512 croak $? if $?;
2513 $fh->flush == 0 or croak $!;
2514 seek $fh, 0, 0 or croak $!;
2516 my $md5 = Digest::MD5->new;
2517 $md5->addfile($fh) or croak $!;
2518 seek $fh, 0, 0 or croak $!;
2520 my $exp = $md5->hexdigest;
2521 my $pool = SVN::Pool->new;
2522 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2523 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2524 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2525 $pool->clear;
2527 close $fh or croak $!;
2530 sub D {
2531 my ($self, $m) = @_;
2532 my ($dir, $file) = split_path($m->{file_b});
2533 my $pbat = $self->ensure_path($dir);
2534 print "\tD\t$m->{file_b}\n" unless $::_q;
2535 $self->delete_entry($m->{file_b}, $pbat);
2538 sub close_edit {
2539 my ($self) = @_;
2540 my ($p,$bat) = ($self->{pool}, $self->{bat});
2541 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2542 $self->close_directory($bat->{$_}, $p);
2544 $self->SUPER::close_edit($p);
2545 $p->clear;
2548 sub abort_edit {
2549 my ($self) = @_;
2550 $self->SUPER::abort_edit($self->{pool});
2553 sub DESTROY {
2554 my $self = shift;
2555 $self->SUPER::DESTROY(@_);
2556 $self->{pool}->clear;
2559 # this drives the editor
2560 sub apply_diff {
2561 my ($self) = @_;
2562 my $mods = $self->{mods};
2563 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2564 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2565 my $f = $m->{chg};
2566 if (defined $o{$f}) {
2567 $self->$f($m);
2568 } else {
2569 fatal("Invalid change type: $f\n");
2572 $self->rmdirs if $_rmdir;
2573 if (@$mods == 0) {
2574 $self->abort_edit;
2575 } else {
2576 $self->close_edit;
2578 return scalar @$mods;
2581 package Git::SVN::Ra;
2582 use vars qw/@ISA $config_dir/;
2583 use strict;
2584 use warnings;
2585 my ($can_do_switch);
2586 my $RA;
2588 BEGIN {
2589 # enforce temporary pool usage for some simple functions
2590 my $e;
2591 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2592 $e .= "sub $_ {
2593 my \$self = shift;
2594 my \$pool = SVN::Pool->new;
2595 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2596 \$pool->clear;
2597 wantarray ? \@ret : \$ret[0]; }\n";
2600 # get_dir needs $pool held in cache for dirents to work,
2601 # check_path is cacheable and rev_proplist is close enough
2602 # for our purposes.
2603 foreach (qw/check_path get_dir rev_proplist/) {
2604 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2605 my \$self = shift;
2606 my \$r = pop;
2607 my \$k = join(\"\\0\", \@_);
2608 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2609 return wantarray ? \@\$x : \$x->[0];
2611 my \$pool = SVN::Pool->new;
2612 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2613 if (\$r != \$${_}_rev) {
2614 \%${_}_cache = ( pool => [] );
2615 \$${_}_rev = \$r;
2617 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2618 push \@{\$${_}_cache{pool}}, \$pool;
2619 wantarray ? \@ret : \$ret[0]; }\n";
2621 $e .= "\n1;";
2622 eval $e or die $@;
2625 sub new {
2626 my ($class, $url) = @_;
2627 $url =~ s!/+$!!;
2628 return $RA if ($RA && $RA->{url} eq $url);
2630 SVN::_Core::svn_config_ensure($config_dir, undef);
2631 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2632 SVN::Client::get_simple_provider(),
2633 SVN::Client::get_ssl_server_trust_file_provider(),
2634 SVN::Client::get_simple_prompt_provider(
2635 \&Git::SVN::Prompt::simple, 2),
2636 SVN::Client::get_ssl_client_cert_prompt_provider(
2637 \&Git::SVN::Prompt::ssl_client_cert, 2),
2638 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2639 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2640 SVN::Client::get_username_provider(),
2641 SVN::Client::get_ssl_server_trust_prompt_provider(
2642 \&Git::SVN::Prompt::ssl_server_trust),
2643 SVN::Client::get_username_prompt_provider(
2644 \&Git::SVN::Prompt::username, 2),
2646 my $config = SVN::Core::config_get_config($config_dir);
2647 my $self = SVN::Ra->new(url => $url, auth => $baton,
2648 config => $config,
2649 pool => SVN::Pool->new,
2650 auth_provider_callbacks => $callbacks);
2651 $self->{svn_path} = $url;
2652 $self->{repos_root} = $self->get_repos_root;
2653 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2654 $RA = bless $self, $class;
2657 sub DESTROY {
2658 # do not call the real DESTROY since we store ourselves in $RA
2661 sub get_log {
2662 my ($self, @args) = @_;
2663 my $pool = SVN::Pool->new;
2664 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2665 my $ret = $self->SUPER::get_log(@args, $pool);
2666 $pool->clear;
2667 $ret;
2670 sub get_commit_editor {
2671 my ($self, $log, $cb, $pool) = @_;
2672 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2673 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2676 sub gs_do_update {
2677 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2678 my $new = ($rev_a == $rev_b);
2679 my $path = $gs->{path};
2681 my $pool = SVN::Pool->new;
2682 $editor->set_path_strip($path);
2683 my (@pc) = split m#/#, $path;
2684 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2685 1, $editor, $pool);
2686 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2688 # Since we can't rely on svn_ra_reparent being available, we'll
2689 # just have to do some magic with set_path to make it so
2690 # we only want a partial path.
2691 my $sp = '';
2692 my $final = join('/', @pc);
2693 while (@pc) {
2694 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2695 $sp .= '/' if length $sp;
2696 $sp .= shift @pc;
2698 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2700 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2702 $reporter->finish_report($pool);
2703 $pool->clear;
2704 $editor->{git_commit_ok};
2707 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2708 # svn_ra_reparent didn't work before 1.4)
2709 sub gs_do_switch {
2710 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2711 my $path = $gs->{path};
2712 my $pool = SVN::Pool->new;
2714 my $full_url = $self->{url};
2715 my $old_url = $full_url;
2716 $full_url .= "/$path" if length $path;
2717 my ($ra, $reparented);
2718 if ($old_url ne $full_url) {
2719 if ($old_url !~ m#^svn(\+ssh)?://#) {
2720 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2721 $pool);
2722 $self->{url} = $full_url;
2723 $reparented = 1;
2724 } else {
2725 $ra = Git::SVN::Ra->new($full_url);
2728 $ra ||= $self;
2729 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2730 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2731 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2732 $reporter->finish_report($pool);
2734 if ($reparented) {
2735 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2736 $self->{url} = $old_url;
2739 $pool->clear;
2740 $editor->{git_commit_ok};
2743 sub gs_fetch_loop_common {
2744 my ($self, $base, $head, $gsv, $globs) = @_;
2745 return if ($base > $head);
2746 my $inc = 1000;
2747 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2748 my %common;
2749 my $common_max = scalar @$gsv;
2751 foreach my $gs (@$gsv) {
2752 if (my $last_commit = $gs->last_commit) {
2753 $gs->assert_index_clean($last_commit);
2755 my @tmp = split m#/#, $gs->{path};
2756 my $p = '';
2757 foreach (@tmp) {
2758 $p .= length($p) ? "/$_" : $_;
2759 $common{$p} ||= 0;
2760 $common{$p}++;
2763 $globs ||= [];
2764 $common_max += scalar @$globs;
2765 foreach my $glob (@$globs) {
2766 my @tmp = split m#/#, $glob->{path}->{left};
2767 my $p = '';
2768 foreach (@tmp) {
2769 $p .= length($p) ? "/$_" : $_;
2770 $common{$p} ||= 0;
2771 $common{$p}++;
2775 my $longest_path = '';
2776 foreach (sort {length $b <=> length $a} keys %common) {
2777 if ($common{$_} == $common_max) {
2778 $longest_path = $_;
2779 last;
2782 while (1) {
2783 my %revs;
2784 my $err;
2785 my $err_handler = $SVN::Error::handler;
2786 $SVN::Error::handler = sub {
2787 ($err) = @_;
2788 skip_unknown_revs($err);
2790 sub _cb {
2791 my ($paths, $r, $author, $date, $log) = @_;
2792 [ dup_changed_paths($paths),
2793 { author => $author, date => $date, log => $log } ];
2795 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2796 sub { $revs{$_[1]} = _cb(@_) });
2797 if ($err && $max >= $head) {
2798 print STDERR "Path '$longest_path' ",
2799 "was probably deleted:\n",
2800 $err->expanded_message,
2801 "\nWill attempt to follow ",
2802 "revisions r$min .. r$max ",
2803 "committed before the deletion\n";
2804 my $hi = $max;
2805 while (--$hi >= $min) {
2806 my $ok;
2807 $self->get_log([$longest_path], $min, $hi,
2808 0, 1, 1, sub {
2809 $ok ||= $_[1];
2810 $revs{$_[1]} = _cb(@_) });
2811 if ($ok) {
2812 print STDERR "r$min .. r$ok OK\n";
2813 last;
2817 $SVN::Error::handler = $err_handler;
2819 my %exists = map { $_->{path} => $_ } @$gsv;
2820 foreach my $r (sort {$a <=> $b} keys %revs) {
2821 my ($paths, $logged) = @{$revs{$r}};
2823 foreach my $gs ($self->match_globs(\%exists, $paths,
2824 $globs, $r)) {
2825 if ($gs->rev_db_max >= $r) {
2826 next;
2828 next unless $gs->match_paths($paths, $r);
2829 $gs->{logged_rev_props} = $logged;
2830 my $log_entry = $gs->do_fetch($paths, $r);
2831 if ($log_entry) {
2832 $gs->do_git_commit($log_entry);
2835 foreach my $g (@$globs) {
2836 my $k = "svn-remote.$g->{remote}." .
2837 "$g->{t}-maxRev";
2838 Git::SVN::tmp_config($k, $r);
2841 # pre-fill the .rev_db since it'll eventually get filled in
2842 # with '0' x40 if something new gets committed
2843 foreach my $gs (@$gsv) {
2844 next if defined $gs->rev_db_get($max);
2845 $gs->rev_db_set($max, 0 x40);
2847 foreach my $g (@$globs) {
2848 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
2849 Git::SVN::tmp_config($k, $max);
2851 last if $max >= $head;
2852 $min = $max + 1;
2853 $max += $inc;
2854 $max = $head if ($max > $head);
2858 sub match_globs {
2859 my ($self, $exists, $paths, $globs, $r) = @_;
2861 sub get_dir_check {
2862 my ($self, $exists, $g, $r) = @_;
2863 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2864 return unless scalar @x == 3;
2865 my $dirents = $x[0];
2866 foreach my $de (keys %$dirents) {
2867 next if $dirents->{$de}->kind != $SVN::Node::dir;
2868 my $p = $g->{path}->full_path($de);
2869 next if $exists->{$p};
2870 next if (length $g->{path}->{right} &&
2871 ($self->check_path($p, $r) !=
2872 $SVN::Node::dir));
2873 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
2874 $g->{ref}->full_path($de), 1);
2877 foreach my $g (@$globs) {
2878 if (my $path = $paths->{"/$g->{path}->{left}"}) {
2879 if ($path->{action} =~ /^[AR]$/) {
2880 get_dir_check($self, $exists, $g, $r);
2883 foreach (keys %$paths) {
2884 if (/$g->{path}->{left_regex}/) {
2885 next if $paths->{$_}->{action} !~ /^[AR]$/;
2886 get_dir_check($self, $exists, $g, $r);
2888 next unless /$g->{path}->{regex}/;
2889 my $p = $1;
2890 my $pathname = $g->{path}->full_path($p);
2891 next if $exists->{$pathname};
2892 $exists->{$pathname} = Git::SVN->init(
2893 $self->{url}, $pathname, undef,
2894 $g->{ref}->full_path($p), 1);
2896 my $c = '';
2897 foreach (split m#/#, $g->{path}->{left}) {
2898 $c .= "/$_";
2899 next unless ($paths->{$c} &&
2900 ($paths->{$c}->{action} =~ /^[AR]$/));
2901 get_dir_check($self, $exists, $g, $r);
2904 values %$exists;
2907 sub minimize_url {
2908 my ($self) = @_;
2909 return $self->{url} if ($self->{url} eq $self->{repos_root});
2910 my $url = $self->{repos_root};
2911 my @components = split(m!/!, $self->{svn_path});
2912 my $c = '';
2913 do {
2914 $url .= "/$c" if length $c;
2915 eval { (ref $self)->new($url)->get_latest_revnum };
2916 } while ($@ && ($c = shift @components));
2917 $url;
2920 sub can_do_switch {
2921 my $self = shift;
2922 unless (defined $can_do_switch) {
2923 my $pool = SVN::Pool->new;
2924 my $rep = eval {
2925 $self->do_switch(1, '', 0, $self->{url},
2926 SVN::Delta::Editor->new, $pool);
2928 if ($@) {
2929 $can_do_switch = 0;
2930 } else {
2931 $rep->abort_report($pool);
2932 $can_do_switch = 1;
2934 $pool->clear;
2936 $can_do_switch;
2939 sub skip_unknown_revs {
2940 my ($err) = @_;
2941 my $errno = $err->apr_err();
2942 # Maybe the branch we're tracking didn't
2943 # exist when the repo started, so it's
2944 # not an error if it doesn't, just continue
2946 # Wonderfully consistent library, eh?
2947 # 160013 - svn:// and file://
2948 # 175002 - http(s)://
2949 # 175007 - http(s):// (this repo required authorization, too...)
2950 # More codes may be discovered later...
2951 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2952 return;
2954 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2957 # svn_log_changed_path_t objects passed to get_log are likely to be
2958 # overwritten even if only the refs are copied to an external variable,
2959 # so we should dup the structures in their entirety. Using an externally
2960 # passed pool (instead of our temporary and quickly cleared pool in
2961 # Git::SVN::Ra) does not help matters at all...
2962 sub dup_changed_paths {
2963 my ($paths) = @_;
2964 return undef unless $paths;
2965 my %ret;
2966 foreach my $p (keys %$paths) {
2967 my $i = $paths->{$p};
2968 my %s = map { $_ => $i->$_ }
2969 qw/copyfrom_path copyfrom_rev action/;
2970 $ret{$p} = \%s;
2972 \%ret;
2975 package Git::SVN::Log;
2976 use strict;
2977 use warnings;
2978 use POSIX qw/strftime/;
2979 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2980 %rusers $show_commit $incremental/;
2981 my $l_fmt;
2983 sub cmt_showable {
2984 my ($c) = @_;
2985 return 1 if defined $c->{r};
2986 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2987 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2988 my @log = command(qw/cat-file commit/, $c->{c});
2989 shift @log while ($log[0] ne "\n");
2990 shift @log;
2991 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2993 (undef, $c->{r}, undef) = ::extract_metadata(
2994 (grep(/^git-svn-id: /, @log))[-1]);
2996 return defined $c->{r};
2999 sub log_use_color {
3000 return 1 if $color;
3001 my ($dc, $dcvar);
3002 $dcvar = 'color.diff';
3003 $dc = `git-config --get $dcvar`;
3004 if ($dc eq '') {
3005 # nothing at all; fallback to "diff.color"
3006 $dcvar = 'diff.color';
3007 $dc = `git-config --get $dcvar`;
3009 chomp($dc);
3010 if ($dc eq 'auto') {
3011 my $pc;
3012 $pc = `git-config --get color.pager`;
3013 if ($pc eq '') {
3014 # does not have it -- fallback to pager.color
3015 $pc = `git-config --bool --get pager.color`;
3017 else {
3018 $pc = `git-config --bool --get color.pager`;
3019 if ($?) {
3020 $pc = 'false';
3023 chomp($pc);
3024 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3025 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3027 return 0;
3029 return 0 if $dc eq 'never';
3030 return 1 if $dc eq 'always';
3031 chomp($dc = `git-config --bool --get $dcvar`);
3032 return ($dc eq 'true');
3035 sub git_svn_log_cmd {
3036 my ($r_min, $r_max) = @_;
3037 my $gs = Git::SVN->_new;
3038 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3039 $gs->refname);
3040 push @cmd, '-r' unless $non_recursive;
3041 push @cmd, qw/--raw --name-status/ if $verbose;
3042 push @cmd, '--color' if log_use_color();
3043 return @cmd unless defined $r_max;
3044 if ($r_max == $r_min) {
3045 push @cmd, '--max-count=1';
3046 if (my $c = $gs->rev_db_get($r_max)) {
3047 push @cmd, $c;
3049 } else {
3050 my ($c_min, $c_max);
3051 $c_max = $gs->rev_db_get($r_max);
3052 $c_min = $gs->rev_db_get($r_min);
3053 if (defined $c_min && defined $c_max) {
3054 if ($r_max > $r_max) {
3055 push @cmd, "$c_min..$c_max";
3056 } else {
3057 push @cmd, "$c_max..$c_min";
3059 } elsif ($r_max > $r_min) {
3060 push @cmd, $c_max;
3061 } else {
3062 push @cmd, $c_min;
3065 return @cmd;
3068 # adapted from pager.c
3069 sub config_pager {
3070 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3071 if (!defined $pager) {
3072 $pager = 'less';
3073 } elsif (length $pager == 0 || $pager eq 'cat') {
3074 $pager = undef;
3078 sub run_pager {
3079 return unless -t *STDOUT;
3080 pipe my $rfd, my $wfd or return;
3081 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3082 if (!$pid) {
3083 open STDOUT, '>&', $wfd or
3084 ::fatal "Can't redirect to stdout: $!\n";
3085 return;
3087 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3088 $ENV{LESS} ||= 'FRSX';
3089 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3092 sub tz_to_s_offset {
3093 my ($tz) = @_;
3094 $tz =~ s/(\d\d)$//;
3095 return ($1 * 60) + ($tz * 3600);
3098 sub get_author_info {
3099 my ($dest, $author, $t, $tz) = @_;
3100 $author =~ s/(?:^\s*|\s*$)//g;
3101 $dest->{a_raw} = $author;
3102 my $au;
3103 if ($::_authors) {
3104 $au = $rusers{$author} || undef;
3106 if (!$au) {
3107 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3109 $dest->{t} = $t;
3110 $dest->{tz} = $tz;
3111 $dest->{a} = $au;
3112 # Date::Parse isn't in the standard Perl distro :(
3113 if ($tz =~ s/^\+//) {
3114 $t += tz_to_s_offset($tz);
3115 } elsif ($tz =~ s/^\-//) {
3116 $t -= tz_to_s_offset($tz);
3118 $dest->{t_utc} = $t;
3121 sub process_commit {
3122 my ($c, $r_min, $r_max, $defer) = @_;
3123 if (defined $r_min && defined $r_max) {
3124 if ($r_min == $c->{r} && $r_min == $r_max) {
3125 show_commit($c);
3126 return 0;
3128 return 1 if $r_min == $r_max;
3129 if ($r_min < $r_max) {
3130 # we need to reverse the print order
3131 return 0 if (defined $limit && --$limit < 0);
3132 push @$defer, $c;
3133 return 1;
3135 if ($r_min != $r_max) {
3136 return 1 if ($r_min < $c->{r});
3137 return 1 if ($r_max > $c->{r});
3140 return 0 if (defined $limit && --$limit < 0);
3141 show_commit($c);
3142 return 1;
3145 sub show_commit {
3146 my $c = shift;
3147 if ($oneline) {
3148 my $x = "\n";
3149 if (my $l = $c->{l}) {
3150 while ($l->[0] =~ /^\s*$/) { shift @$l }
3151 $x = $l->[0];
3153 $l_fmt ||= 'A' . length($c->{r});
3154 print 'r',pack($l_fmt, $c->{r}),' | ';
3155 print "$c->{c} | " if $show_commit;
3156 print $x;
3157 } else {
3158 show_commit_normal($c);
3162 sub show_commit_changed_paths {
3163 my ($c) = @_;
3164 return unless $c->{changed};
3165 print "Changed paths:\n", @{$c->{changed}};
3168 sub show_commit_normal {
3169 my ($c) = @_;
3170 print '-' x72, "\nr$c->{r} | ";
3171 print "$c->{c} | " if $show_commit;
3172 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3173 localtime($c->{t_utc})), ' | ';
3174 my $nr_line = 0;
3176 if (my $l = $c->{l}) {
3177 while ($l->[$#$l] eq "\n" && $#$l > 0
3178 && $l->[($#$l - 1)] eq "\n") {
3179 pop @$l;
3181 $nr_line = scalar @$l;
3182 if (!$nr_line) {
3183 print "1 line\n\n\n";
3184 } else {
3185 if ($nr_line == 1) {
3186 $nr_line = '1 line';
3187 } else {
3188 $nr_line .= ' lines';
3190 print $nr_line, "\n";
3191 show_commit_changed_paths($c);
3192 print "\n";
3193 print $_ foreach @$l;
3195 } else {
3196 print "1 line\n";
3197 show_commit_changed_paths($c);
3198 print "\n";
3201 foreach my $x (qw/raw diff/) {
3202 if ($c->{$x}) {
3203 print "\n";
3204 print $_ foreach @{$c->{$x}}
3209 sub cmd_show_log {
3210 my (@args) = @_;
3211 my ($r_min, $r_max);
3212 my $r_last = -1; # prevent dupes
3213 if (defined $TZ) {
3214 $ENV{TZ} = $TZ;
3215 } else {
3216 delete $ENV{TZ};
3218 if (defined $::_revision) {
3219 if ($::_revision =~ /^(\d+):(\d+)$/) {
3220 ($r_min, $r_max) = ($1, $2);
3221 } elsif ($::_revision =~ /^\d+$/) {
3222 $r_min = $r_max = $::_revision;
3223 } else {
3224 ::fatal "-r$::_revision is not supported, use ",
3225 "standard \'git log\' arguments instead\n";
3229 config_pager();
3230 @args = (git_svn_log_cmd($r_min, $r_max), @args);
3231 my $log = command_output_pipe(@args);
3232 run_pager();
3233 my (@k, $c, $d);
3234 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3235 while (<$log>) {
3236 if (/^${esc_color}commit ($::sha1_short)/o) {
3237 my $cmt = $1;
3238 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3239 $r_last = $c->{r};
3240 process_commit($c, $r_min, $r_max, \@k) or
3241 goto out;
3243 $d = undef;
3244 $c = { c => $cmt };
3245 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3246 get_author_info($c, $1, $2, $3);
3247 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3248 # ignore
3249 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3250 push @{$c->{raw}}, $_;
3251 } elsif (/^${esc_color}[ACRMDT]\t/) {
3252 # we could add $SVN->{svn_path} here, but that requires
3253 # remote access at the moment (repo_path_split)...
3254 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3255 push @{$c->{changed}}, $_;
3256 } elsif (/^${esc_color}diff /o) {
3257 $d = 1;
3258 push @{$c->{diff}}, $_;
3259 } elsif ($d) {
3260 push @{$c->{diff}}, $_;
3261 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3262 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3263 } elsif (s/^${esc_color} //o) {
3264 push @{$c->{l}}, $_;
3267 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3268 $r_last = $c->{r};
3269 process_commit($c, $r_min, $r_max, \@k);
3271 if (@k) {
3272 my $swap = $r_max;
3273 $r_max = $r_min;
3274 $r_min = $swap;
3275 process_commit($_, $r_min, $r_max) foreach reverse @k;
3277 out:
3278 close $log;
3279 print '-' x72,"\n" unless $incremental || $oneline;
3282 package Git::SVN::Migration;
3283 # these version numbers do NOT correspond to actual version numbers
3284 # of git nor git-svn. They are just relative.
3286 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3288 # v1 layout: .git/$id/info/url, refs/remotes/$id
3290 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3292 # v3 layout: .git/svn/$id, refs/remotes/$id
3293 # - info/url may remain for backwards compatibility
3294 # - this is what we migrate up to this layout automatically,
3295 # - this will be used by git svn init on single branches
3296 # v3.1 layout (auto migrated):
3297 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3298 # for backwards compatibility
3300 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3301 # - this is only created for newly multi-init-ed
3302 # repositories. Similar in spirit to the
3303 # --use-separate-remotes option in git-clone (now default)
3304 # - we do not automatically migrate to this (following
3305 # the example set by core git)
3306 use strict;
3307 use warnings;
3308 use Carp qw/croak/;
3309 use File::Path qw/mkpath/;
3310 use File::Basename qw/dirname basename/;
3311 use vars qw/$_minimize/;
3313 sub migrate_from_v0 {
3314 my $git_dir = $ENV{GIT_DIR};
3315 return undef unless -d $git_dir;
3316 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3317 my $migrated = 0;
3318 while (<$fh>) {
3319 chomp;
3320 my ($id, $orig_ref) = ($_, $_);
3321 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3322 next unless -f "$git_dir/$id/info/url";
3323 my $new_ref = "refs/remotes/$id";
3324 if (::verify_ref("$new_ref^0")) {
3325 print STDERR "W: $orig_ref is probably an old ",
3326 "branch used by an ancient version of ",
3327 "git-svn.\n",
3328 "However, $new_ref also exists.\n",
3329 "We will not be able ",
3330 "to use this branch until this ",
3331 "ambiguity is resolved.\n";
3332 next;
3334 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3335 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3336 command_noisy('update-ref', $new_ref, $orig_ref);
3337 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3338 $migrated++;
3340 command_close_pipe($fh, $ctx);
3341 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3342 $migrated;
3345 sub migrate_from_v1 {
3346 my $git_dir = $ENV{GIT_DIR};
3347 my $migrated = 0;
3348 return $migrated unless -d $git_dir;
3349 my $svn_dir = "$git_dir/svn";
3351 # just in case somebody used 'svn' as their $id at some point...
3352 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3354 print STDERR "Migrating from a git-svn v1 layout...\n";
3355 mkpath([$svn_dir]);
3356 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3357 "$svn_dir\n\t(required for this version ",
3358 "($::VERSION) of git-svn) does not. exist\n";
3359 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3360 while (<$fh>) {
3361 my $x = $_;
3362 next unless $x =~ s#^refs/remotes/##;
3363 chomp $x;
3364 next unless -f "$git_dir/$x/info/url";
3365 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3366 next unless $u;
3367 my $dn = dirname("$git_dir/svn/$x");
3368 mkpath([$dn]) unless -d $dn;
3369 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3370 mkpath(["$git_dir/svn/svn"]);
3371 print STDERR " - $git_dir/$x/info => ",
3372 "$git_dir/svn/$x/info\n";
3373 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3374 croak "$!: $x";
3375 # don't worry too much about these, they probably
3376 # don't exist with repos this old (save for index,
3377 # and we can easily regenerate that)
3378 foreach my $f (qw/unhandled.log index .rev_db/) {
3379 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3381 } else {
3382 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3383 rename "$git_dir/$x", "$git_dir/svn/$x" or
3384 croak "$!: $x";
3386 $migrated++;
3388 command_close_pipe($fh, $ctx);
3389 print STDERR "Done migrating from a git-svn v1 layout\n";
3390 $migrated;
3393 sub read_old_urls {
3394 my ($l_map, $pfx, $path) = @_;
3395 my @dir;
3396 foreach (<$path/*>) {
3397 if (-r "$_/info/url") {
3398 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3399 my $ref_id = $pfx . basename $_;
3400 my $url = ::file_to_s("$_/info/url");
3401 $l_map->{$ref_id} = $url;
3402 } elsif (-d $_) {
3403 push @dir, $_;
3406 foreach (@dir) {
3407 my $x = $_;
3408 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3409 read_old_urls($l_map, $x, $_);
3413 sub migrate_from_v2 {
3414 my @cfg = command(qw/config -l/);
3415 return if grep /^svn-remote\..+\.url=/, @cfg;
3416 my %l_map;
3417 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3418 my $migrated = 0;
3420 foreach my $ref_id (sort keys %l_map) {
3421 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3422 if ($@) {
3423 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3425 $migrated++;
3427 $migrated;
3430 sub minimize_connections {
3431 my $r = Git::SVN::read_all_remotes();
3432 my $new_urls = {};
3433 my $root_repos = {};
3434 foreach my $repo_id (keys %$r) {
3435 my $url = $r->{$repo_id}->{url} or next;
3436 my $fetch = $r->{$repo_id}->{fetch} or next;
3437 my $ra = Git::SVN::Ra->new($url);
3439 # skip existing cases where we already connect to the root
3440 if (($ra->{url} eq $ra->{repos_root}) ||
3441 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3442 $repo_id)) {
3443 $root_repos->{$ra->{url}} = $repo_id;
3444 next;
3447 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3448 my $root_path = $ra->{url};
3449 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3450 foreach my $path (keys %$fetch) {
3451 my $ref_id = $fetch->{$path};
3452 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3454 # make sure we can read when connecting to
3455 # a higher level of a repository
3456 my ($last_rev, undef) = $gs->last_rev_commit;
3457 if (!defined $last_rev) {
3458 $last_rev = eval {
3459 $root_ra->get_latest_revnum;
3461 next if $@;
3463 my $new = $root_path;
3464 $new .= length $path ? "/$path" : '';
3465 eval {
3466 $root_ra->get_log([$new], $last_rev, $last_rev,
3467 0, 0, 1, sub { });
3469 next if $@;
3470 $new_urls->{$ra->{repos_root}}->{$new} =
3471 { ref_id => $ref_id,
3472 old_repo_id => $repo_id,
3473 old_path => $path };
3477 my @emptied;
3478 foreach my $url (keys %$new_urls) {
3479 # see if we can re-use an existing [svn-remote "repo_id"]
3480 # instead of creating a(n ugly) new section:
3481 my $repo_id = $root_repos->{$url} ||
3482 Git::SVN::sanitize_remote_name($url);
3484 my $fetch = $new_urls->{$url};
3485 foreach my $path (keys %$fetch) {
3486 my $x = $fetch->{$path};
3487 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3488 my $pfx = "svn-remote.$x->{old_repo_id}";
3490 my $old_fetch = quotemeta("$x->{old_path}:".
3491 "refs/remotes/$x->{ref_id}");
3492 command_noisy(qw/config --unset/,
3493 "$pfx.fetch", '^'. $old_fetch . '$');
3494 delete $r->{$x->{old_repo_id}}->
3495 {fetch}->{$x->{old_path}};
3496 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3497 command_noisy(qw/config --unset/,
3498 "$pfx.url");
3499 push @emptied, $x->{old_repo_id}
3503 if (@emptied) {
3504 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3505 "$ENV{GIT_DIR}/config";
3506 print STDERR <<EOF;
3507 The following [svn-remote] sections in your config file ($file) are empty
3508 and can be safely removed:
3510 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3514 sub migration_check {
3515 migrate_from_v0();
3516 migrate_from_v1();
3517 migrate_from_v2();
3518 minimize_connections() if $_minimize;
3521 package Git::IndexInfo;
3522 use strict;
3523 use warnings;
3524 use Git qw/command_input_pipe command_close_pipe/;
3526 sub new {
3527 my ($class) = @_;
3528 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3529 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3532 sub remove {
3533 my ($self, $path) = @_;
3534 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3535 return ++$self->{nr};
3537 undef;
3540 sub update {
3541 my ($self, $mode, $hash, $path) = @_;
3542 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3543 return ++$self->{nr};
3545 undef;
3548 sub DESTROY {
3549 my ($self) = @_;
3550 command_close_pipe($self->{gui}, $self->{ctx});
3553 package Git::SVN::GlobSpec;
3554 use strict;
3555 use warnings;
3557 sub new {
3558 my ($class, $glob) = @_;
3559 my $re = $glob;
3560 $re =~ s!/+$!!g; # no need for trailing slashes
3561 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3562 my ($left, $right) = ($1, $2);
3563 if ($nr > 1) {
3564 die "Only one '*' wildcard expansion ",
3565 "is supported (got $nr): '$glob'\n";
3566 } elsif ($nr == 0) {
3567 die "One '*' is needed for glob: '$glob'\n";
3569 $re = quotemeta($left) . $re . quotemeta($right);
3570 if (length $left && !($left =~ s!/+$!!g)) {
3571 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3573 if (length $right && !($right =~ s!^/+!!g)) {
3574 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3576 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3577 bless { left => $left, right => $right, left_regex => $left_re,
3578 regex => qr/$re/, glob => $glob }, $class;
3581 sub full_path {
3582 my ($self, $path) = @_;
3583 return (length $self->{left} ? "$self->{left}/" : '') .
3584 $path . (length $self->{right} ? "/$self->{right}" : '');
3587 __END__
3589 Data structures:
3592 $remotes = { # returned by read_all_remotes()
3593 'svn' => {
3594 # svn-remote.svn.url=https://svn.musicpd.org
3595 url => 'https://svn.musicpd.org',
3596 # svn-remote.svn.fetch=mpd/trunk:trunk
3597 fetch => {
3598 'mpd/trunk' => 'trunk',
3600 # svn-remote.svn.tags=mpd/tags/*:tags/*
3601 tags => {
3602 path => {
3603 left => 'mpd/tags',
3604 right => '',
3605 regex => qr!mpd/tags/([^/]+)$!,
3606 glob => 'tags/*',
3608 ref => {
3609 left => 'tags',
3610 right => '',
3611 regex => qr!tags/([^/]+)$!,
3612 glob => 'tags/*',
3618 $log_entry hashref as returned by libsvn_log_entry()
3620 log => 'whitespace-formatted log entry
3621 ', # trailing newline is preserved
3622 revision => '8', # integer
3623 date => '2004-02-24T17:01:44.108345Z', # commit date
3624 author => 'committer name'
3628 # this is generated by generate_diff();
3629 @mods = array of diff-index line hashes, each element represents one line
3630 of diff-index output
3632 diff-index line ($m hash)
3634 mode_a => first column of diff-index output, no leading ':',
3635 mode_b => second column of diff-index output,
3636 sha1_b => sha1sum of the final blob,
3637 chg => change type [MCRADT],
3638 file_a => original file name of a file (iff chg is 'C' or 'R')
3639 file_b => new/current file name of a file (any chg)
3643 # retval of read_url_paths{,_all}();
3644 $l_map = {
3645 # repository root url
3646 'https://svn.musicpd.org' => {
3647 # repository path # GIT_SVN_ID
3648 'mpd/trunk' => 'trunk',
3649 'mpd/tags/0.11.5' => 'tags/0.11.5',
3653 Notes:
3654 I don't trust the each() function on unless I created %hash myself
3655 because the internal iterator may not have started at base.