git-svn: brown paper bag fixes
[git/libgit-gsoc.git] / git-svn.perl
blob24ca3087d699ed6e4e1e65f2b69139d82b8bb7fb
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, $_fetch_all,
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 %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
75 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
76 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
77 %remote_opts );
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,
88 'all|a' => \$_fetch_all,
89 %fc_opts } ],
90 init => [ \&cmd_init, "Initialize a repo for tracking" .
91 " (requires URL argument)",
92 \%init_opts ],
93 'multi-init' => [ \&cmd_multi_init,
94 "Deprecated alias for ".
95 "'$0 init -T<trunk> -b<branches> -t<tags>'",
96 \%init_opts ],
97 dcommit => [ \&cmd_dcommit,
98 'Commit several diffs to merge with upstream',
99 { 'merge|m|M' => \$_merge,
100 'strategy|s=s' => \$_strategy,
101 'dry-run|n' => \$_dry_run,
102 %cmt_opts, %fc_opts } ],
103 'set-tree' => [ \&cmd_set_tree,
104 "Set an SVN repository to a git tree-ish",
105 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
106 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
107 { 'revision|r=i' => \$_revision } ],
108 'multi-fetch' => [ \&cmd_multi_fetch,
109 "Deprecated alias for $0 fetch --all",
110 { 'revision|r=s' => \$_revision, %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 next if /^multi-/; # don't show deprecated commands
184 # prints out arguments as they should be passed:
185 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
186 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
187 "--$_" : "-$_" }
188 split /\|/,$_)," $x\n";
191 print $fd <<"";
192 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
193 arbitrary identifier if you're tracking multiple SVN branches/repositories in
194 one git repository and want to keep them separate. See git-svn(1) for more
195 information.
197 exit $exit;
200 sub version {
201 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
202 exit 0;
205 sub do_git_init_db {
206 unless (-d $ENV{GIT_DIR}) {
207 my @init_db = ('init');
208 push @init_db, "--template=$_template" if defined $_template;
209 if (defined $_shared) {
210 if ($_shared =~ /[a-z]/) {
211 push @init_db, "--shared=$_shared";
212 } else {
213 push @init_db, "--shared";
216 command_noisy(@init_db);
220 sub init_subdir {
221 my $repo_path = shift or return;
222 mkpath([$repo_path]) unless -d $repo_path;
223 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
224 $ENV{GIT_DIR} = $repo_path . "/.git";
227 sub cmd_init {
228 if (defined $_trunk || defined $_branches || defined $_tags) {
229 return cmd_multi_init(@_);
231 my $url = shift or die "SVN repository location required ",
232 "as a command-line argument\n";
233 init_subdir(@_);
234 do_git_init_db();
236 Git::SVN->init($url);
239 sub cmd_fetch {
240 if (grep /^\d+=./, @_) {
241 die "'<rev>=<commit>' fetch arguments are ",
242 "no longer supported.\n";
244 my ($remote) = @_;
245 if (@_ > 1) {
246 die "Usage: $0 fetch [--all|-a] [svn-remote]\n";
248 $remote ||= $Git::SVN::default_repo_id;
249 if ($_fetch_all) {
250 cmd_multi_fetch();
251 } else {
252 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
256 sub cmd_set_tree {
257 my (@commits) = @_;
258 if ($_stdin || !@commits) {
259 print "Reading from stdin...\n";
260 @commits = ();
261 while (<STDIN>) {
262 if (/\b($sha1_short)\b/o) {
263 unshift @commits, $1;
267 my @revs;
268 foreach my $c (@commits) {
269 my @tmp = command('rev-parse',$c);
270 if (scalar @tmp == 1) {
271 push @revs, $tmp[0];
272 } elsif (scalar @tmp > 1) {
273 push @revs, reverse(command('rev-list',@tmp));
274 } else {
275 fatal "Failed to rev-parse $c\n";
278 my $gs = Git::SVN->new;
279 my ($r_last, $cmt_last) = $gs->last_rev_commit;
280 $gs->fetch;
281 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
282 fatal "There are new revisions that were fetched ",
283 "and need to be merged (or acknowledged) ",
284 "before committing.\nlast rev: $r_last\n",
285 " current: $gs->{last_rev}\n";
287 $gs->set_tree($_) foreach @revs;
288 print "Done committing ",scalar @revs," revisions to SVN\n";
291 sub cmd_dcommit {
292 my $head = shift;
293 $head ||= 'HEAD';
294 my ($url, $rev, $uuid);
295 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
296 my @refs;
297 my $c;
298 while (<$fh>) {
299 $c = $_;
300 chomp $c;
301 ($url, $rev, $uuid) = cmt_metadata($c);
302 last if (defined $url && defined $rev && defined $uuid);
303 unshift @refs, $c;
305 close $fh; # most likely breaking the pipe
306 unless (defined $url && defined $rev && defined $uuid) {
307 die "Unable to determine upstream SVN information from ",
308 "$head history:\n $ctx\n";
310 my $gs = Git::SVN->find_by_url($url) or
311 die "Can't determine fetch information for $url\n";
312 my $last_rev;
313 foreach my $d (@refs) {
314 if (!verify_ref("$d~1")) {
315 fatal "Commit $d\n",
316 "has no parent commit, and therefore ",
317 "nothing to diff against.\n",
318 "You should be working from a repository ",
319 "originally created by git-svn\n";
321 unless (defined $last_rev) {
322 (undef, $last_rev, undef) = cmt_metadata("$d~1");
323 unless (defined $last_rev) {
324 fatal "Unable to extract revision information ",
325 "from commit $d~1\n";
328 if ($_dry_run) {
329 print "diff-tree $d~1 $d\n";
330 } else {
331 my %ed_opts = ( r => $last_rev,
332 log => get_commit_entry($d)->{log},
333 ra => Git::SVN::Ra->new($url),
334 tree_a => "$d~1",
335 tree_b => $d,
336 editor_cb => sub {
337 print "Committed r$_[0]\n";
338 $last_rev = $_[0]; },
339 svn_path => '');
340 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
341 print "No changes\n$d~1 == $d\n";
345 return if $_dry_run;
346 $gs->fetch;
347 # we always want to rebase against the current HEAD, not any
348 # head that was passed to us
349 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
350 my @finish;
351 if (@diff) {
352 @finish = qw/rebase/;
353 push @finish, qw/--merge/ if $_merge;
354 push @finish, "--strategy=$_strategy" if $_strategy;
355 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
356 "using @finish:\n", "@diff";
357 } else {
358 print "No changes between current HEAD and ",
359 $gs->refname, "\nResetting to the latest ",
360 $gs->refname, "\n";
361 @finish = qw/reset --mixed/;
363 command_noisy(@finish, $gs->refname);
366 sub cmd_show_ignore {
367 my $gs = Git::SVN->new;
368 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
369 $gs->traverse_ignore(\*STDOUT, '', $r);
372 sub cmd_multi_init {
373 my $url = shift;
374 unless (defined $_trunk || defined $_branches || defined $_tags) {
375 usage(1);
377 do_git_init_db();
378 $_prefix = '' unless defined $_prefix;
379 if (defined $url) {
380 $url =~ s#/+$##;
381 init_subdir(@_);
383 if (defined $_trunk) {
384 my $trunk_ref = $_prefix . 'trunk';
385 # try both old-style and new-style lookups:
386 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
387 unless ($gs_trunk) {
388 my ($trunk_url, $trunk_path) =
389 complete_svn_url($url, $_trunk);
390 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
391 undef, $trunk_ref);
394 return unless defined $_branches || defined $_tags;
395 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
396 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
397 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
400 sub cmd_multi_fetch {
401 my $remotes = Git::SVN::read_all_remotes();
402 foreach my $repo_id (sort keys %$remotes) {
403 if ($remotes->{$repo_id}->{url}) {
404 Git::SVN::fetch_all($repo_id, $remotes);
409 # this command is special because it requires no metadata
410 sub cmd_commit_diff {
411 my ($ta, $tb, $url) = @_;
412 my $usage = "Usage: $0 commit-diff -r<revision> ".
413 "<tree-ish> <tree-ish> [<URL>]\n";
414 fatal($usage) if (!defined $ta || !defined $tb);
415 my $svn_path;
416 if (!defined $url) {
417 my $gs = eval { Git::SVN->new };
418 if (!$gs) {
419 fatal("Needed URL or usable git-svn --id in ",
420 "the command-line\n", $usage);
422 $url = $gs->{url};
423 $svn_path = $gs->{path};
425 unless (defined $_revision) {
426 fatal("-r|--revision is a required argument\n", $usage);
428 if (defined $_message && defined $_file) {
429 fatal("Both --message/-m and --file/-F specified ",
430 "for the commit message.\n",
431 "I have no idea what you mean\n");
433 if (defined $_file) {
434 $_message = file_to_s($_file);
435 } else {
436 $_message ||= get_commit_entry($tb)->{log};
438 my $ra ||= Git::SVN::Ra->new($url);
439 $svn_path ||= $ra->{svn_path};
440 my $r = $_revision;
441 if ($r eq 'HEAD') {
442 $r = $ra->get_latest_revnum;
443 } elsif ($r !~ /^\d+$/) {
444 die "revision argument: $r not understood by git-svn\n";
446 my %ed_opts = ( r => $r,
447 log => $_message,
448 ra => $ra,
449 tree_a => $ta,
450 tree_b => $tb,
451 editor_cb => sub { print "Committed r$_[0]\n" },
452 svn_path => $svn_path );
453 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
454 print "No changes\n$ta == $tb\n";
458 ########################### utility functions #########################
460 sub complete_svn_url {
461 my ($url, $path) = @_;
462 $path =~ s#/+$##;
463 if ($path !~ m#^[a-z\+]+://#) {
464 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
465 fatal("E: '$path' is not a complete URL ",
466 "and a separate URL is not specified\n");
468 return ($url, $path);
470 return ($path, '');
473 sub complete_url_ls_init {
474 my ($ra, $repo_path, $switch, $pfx) = @_;
475 unless ($repo_path) {
476 print STDERR "W: $switch not specified\n";
477 return;
479 $repo_path =~ s#/+$##;
480 if ($repo_path =~ m#^[a-z\+]+://#) {
481 $ra = Git::SVN::Ra->new($repo_path);
482 $repo_path = '';
483 } else {
484 $repo_path =~ s#^/+##;
485 unless ($ra) {
486 fatal("E: '$repo_path' is not a complete URL ",
487 "and a separate URL is not specified\n");
490 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
491 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
492 my $url = $ra->{url};
493 my $remote_id;
494 my $remote_path;
495 foreach my $d (sort keys %$dirent) {
496 next if ($dirent->{$d}->kind != $SVN::Node::dir);
497 my $path = "$repo_path/$d";
498 my $ref = "$pfx$d";
499 my $gs = eval { Git::SVN->new($ref) };
500 # don't try to init already existing refs
501 unless ($gs) {
502 print "init $url/$path => $ref\n";
503 $gs = Git::SVN->init($url, $path, undef, $ref, 1);
505 if ($gs) {
506 my $k = "svn-remote.$gs->{repo_id}.url";
507 my $orig_url = eval {
508 command_oneline(qw/config --get/, $k)
510 if ($orig_url && ($orig_url ne $gs->{url})) {
511 die "$k already set: $orig_url\n",
512 "wanted to set to: $gs->{url}\n";
514 unless ($orig_url) {
515 command_oneline('config', $k, $gs->{url});
517 $remote_id = $gs->{repo_id};
518 last;
521 if (defined $remote_id) {
522 $remote_path = "$ra->{svn_path}/$repo_path/*";
523 $remote_path =~ s#/+#/#g;
524 $remote_path =~ s#^/##g;
525 my ($n) = ($switch =~ /^--(\w+)/);
526 if (length $pfx && $pfx !~ m#/$#) {
527 die "--prefix='$pfx' must have a trailing slash '/'\n";
529 command_noisy('config', "svn-remote.$remote_id.$n",
530 "$remote_path:refs/remotes/$pfx*");
534 sub verify_ref {
535 my ($ref) = @_;
536 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
537 { STDERR => 0 }); };
540 sub get_tree_from_treeish {
541 my ($treeish) = @_;
542 # $treeish can be a symbolic ref, too:
543 my $type = command_oneline(qw/cat-file -t/, $treeish);
544 my $expected;
545 while ($type eq 'tag') {
546 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
548 if ($type eq 'commit') {
549 $expected = (grep /^tree /, command(qw/cat-file commit/,
550 $treeish))[0];
551 ($expected) = ($expected =~ /^tree ($sha1)$/o);
552 die "Unable to get tree from $treeish\n" unless $expected;
553 } elsif ($type eq 'tree') {
554 $expected = $treeish;
555 } else {
556 die "$treeish is a $type, expected tree, tag or commit\n";
558 return $expected;
561 sub get_commit_entry {
562 my ($treeish) = shift;
563 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
564 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
565 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
566 open my $log_fh, '>', $commit_editmsg or croak $!;
568 my $type = command_oneline(qw/cat-file -t/, $treeish);
569 if ($type eq 'commit' || $type eq 'tag') {
570 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
571 $type, $treeish);
572 my $in_msg = 0;
573 while (<$msg_fh>) {
574 if (!$in_msg) {
575 $in_msg = 1 if (/^\s*$/);
576 } elsif (/^git-svn-id: /) {
577 # skip this for now, we regenerate the
578 # correct one on re-fetch anyways
579 # TODO: set *:merge properties or like...
580 } else {
581 print $log_fh $_ or croak $!;
584 command_close_pipe($msg_fh, $ctx);
586 close $log_fh or croak $!;
588 if ($_edit || ($type eq 'tree')) {
589 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
590 # TODO: strip out spaces, comments, like git-commit.sh
591 system($editor, $commit_editmsg);
593 rename $commit_editmsg, $commit_msg or croak $!;
594 open $log_fh, '<', $commit_msg or croak $!;
595 { local $/; chomp($log_entry{log} = <$log_fh>); }
596 close $log_fh or croak $!;
597 unlink $commit_msg;
598 \%log_entry;
601 sub s_to_file {
602 my ($str, $file, $mode) = @_;
603 open my $fd,'>',$file or croak $!;
604 print $fd $str,"\n" or croak $!;
605 close $fd or croak $!;
606 chmod ($mode &~ umask, $file) if (defined $mode);
609 sub file_to_s {
610 my $file = shift;
611 open my $fd,'<',$file or croak "$!: file: $file\n";
612 local $/;
613 my $ret = <$fd>;
614 close $fd or croak $!;
615 $ret =~ s/\s*$//s;
616 return $ret;
619 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
620 sub load_authors {
621 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
622 my $log = $cmd eq 'log';
623 while (<$authors>) {
624 chomp;
625 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
626 my ($user, $name, $email) = ($1, $2, $3);
627 if ($log) {
628 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
629 } else {
630 $users{$user} = [$name, $email];
633 close $authors or croak $!;
636 # convert GetOpt::Long specs for use by git-config
637 sub read_repo_config {
638 return unless -d $ENV{GIT_DIR};
639 my $opts = shift;
640 my @config_only;
641 foreach my $o (keys %$opts) {
642 # if we have mixedCase and a long option-only, then
643 # it's a config-only variable that we don't need for
644 # the command-line.
645 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
646 my $v = $opts->{$o};
647 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
648 $key =~ s/-//g;
649 my $arg = 'git-config';
650 $arg .= ' --int' if ($o =~ /[:=]i$/);
651 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
652 if (ref $v eq 'ARRAY') {
653 chomp(my @tmp = `$arg --get-all svn.$key`);
654 @$v = @tmp if @tmp;
655 } else {
656 chomp(my $tmp = `$arg --get svn.$key`);
657 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
658 $$v = $tmp;
662 delete @$opts{@config_only} if @config_only;
665 sub extract_metadata {
666 my $id = shift or return (undef, undef, undef);
667 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
668 \s([a-f\d\-]+)$/x);
669 if (!defined $rev || !$uuid || !$url) {
670 # some of the original repositories I made had
671 # identifiers like this:
672 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
674 return ($url, $rev, $uuid);
677 sub cmt_metadata {
678 return extract_metadata((grep(/^git-svn-id: /,
679 command(qw/cat-file commit/, shift)))[-1]);
682 package Git::SVN;
683 use strict;
684 use warnings;
685 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
686 $_repack $_repack_flags $_use_svm_props/;
687 use Carp qw/croak/;
688 use File::Path qw/mkpath/;
689 use File::Copy qw/copy/;
690 use IPC::Open3;
692 my $_repack_nr;
693 # properties that we do not log:
694 my %SKIP_PROP;
695 BEGIN {
696 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
697 svn:special svn:executable
698 svn:entry:committed-rev
699 svn:entry:last-author
700 svn:entry:uuid
701 svn:entry:committed-date/;
703 # some options are read globally, but can be overridden locally
704 # per [svn-remote "..."] section. Command-line options will *NOT*
705 # override options set in an [svn-remote "..."] section
706 my $e;
707 foreach (qw/follow_parent no_metadata use_svm_props/) {
708 my $key = $_;
709 $key =~ tr/_//d;
710 $e .= "sub $_ {
711 my (\$self) = \@_;
712 return \$self->{-$_} if exists \$self->{-$_};
713 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
714 eval { command_oneline(qw/config --get/, \$k) };
715 if (\$@) {
716 \$self->{-$_} = \$Git::SVN::_$_;
717 } else {
718 my \$v = command_oneline(qw/config --bool/,\$k);
719 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
721 return \$self->{-$_} }\n";
723 $e .= "1;\n";
724 eval $e or die $@;
727 my %LOCKFILES;
728 END { unlink keys %LOCKFILES if %LOCKFILES }
730 sub resolve_local_globs {
731 my ($url, $fetch, $glob_spec) = @_;
732 return unless defined $glob_spec;
733 my $ref = $glob_spec->{ref};
734 my $path = $glob_spec->{path};
735 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
736 next unless m#^refs/remotes/$ref->{regex}$#;
737 my $p = $1;
738 my $pathname = $path->full_path($p);
739 my $refname = $ref->full_path($p);
740 if (my $existing = $fetch->{$pathname}) {
741 if ($existing ne $refname) {
742 die "Refspec conflict:\n",
743 "existing: refs/remotes/$existing\n",
744 " globbed: refs/remotes/$refname\n";
746 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
747 $u =~ s!^\Q$url\E(/|$)!! or die
748 "refs/remotes/$refname: '$url' not found in '$u'\n";
749 if ($pathname ne $u) {
750 warn "W: Refspec glob conflict ",
751 "(ref: refs/remotes/$refname):\n",
752 "expected path: $pathname\n",
753 " real path: $u\n",
754 "Continuing ahead with $u\n";
755 next;
757 } else {
758 $fetch->{$pathname} = $refname;
763 sub parse_revision_argument {
764 my ($base, $head) = @_;
765 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
766 return ($base, $head);
768 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
769 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
770 return ($head, $head) if ($::_revision eq 'HEAD');
771 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
772 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
773 die "revision argument: $::_revision not understood by git-svn\n";
776 sub fetch_all {
777 my ($repo_id, $remotes) = @_;
778 my $remote = $remotes->{$repo_id};
779 my $fetch = $remote->{fetch};
780 my $url = $remote->{url};
781 my (@gs, @globs);
782 my $ra = Git::SVN::Ra->new($url);
783 my $uuid = $ra->get_uuid;
784 my $head = $ra->get_latest_revnum;
785 my $base = defined $fetch ? $head : 0;
787 # read the max revs for wildcard expansion (branches/*, tags/*)
788 foreach my $t (qw/branches tags/) {
789 defined $remote->{$t} or next;
790 push @globs, $remote->{$t};
791 my $max_rev = eval { tmp_config(qw/--int --get/,
792 "svn-remote.$repo_id.${t}-maxRev") };
793 if (defined $max_rev && ($max_rev < $base)) {
794 $base = $max_rev;
798 if ($fetch) {
799 foreach my $p (sort keys %$fetch) {
800 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
801 my $lr = $gs->rev_db_max;
802 if (defined $lr) {
803 $base = $lr if ($lr < $base);
805 push @gs, $gs;
809 ($base, $head) = parse_revision_argument($base, $head);
810 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
813 sub read_all_remotes {
814 my $r = {};
815 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
816 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
817 $r->{$1}->{fetch}->{$2} = $3;
818 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
819 $r->{$1}->{url} = $2;
820 } elsif (m!^(.+)\.(branches|tags)=
821 (.*):refs/remotes/(.+)\s*$/!x) {
822 my ($p, $g) = ($3, $4);
823 my $rs = $r->{$1}->{$2} = {
824 t => $2,
825 remote => $1,
826 path => Git::SVN::GlobSpec->new($p),
827 ref => Git::SVN::GlobSpec->new($g) };
828 if (length($rs->{ref}->{right}) != 0) {
829 die "The '*' glob character must be the last ",
830 "character of '$g'\n";
837 sub init_vars {
838 if (defined $_repack) {
839 $_repack = 1000 if ($_repack <= 0);
840 $_repack_nr = $_repack;
841 $_repack_flags ||= '-d';
845 sub verify_remotes_sanity {
846 return unless -d $ENV{GIT_DIR};
847 my %seen;
848 foreach (command(qw/config -l/)) {
849 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
850 if ($seen{$1}) {
851 die "Remote ref refs/remote/$1 is tracked by",
852 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
853 "Please resolve this ambiguity in ",
854 "your git configuration file before ",
855 "continuing\n";
857 $seen{$1} = $_;
862 # we allow more chars than remotes2config.sh...
863 sub sanitize_remote_name {
864 my ($name) = @_;
865 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
866 $name;
869 sub find_existing_remote {
870 my ($url, $remotes) = @_;
871 my $existing;
872 foreach my $repo_id (keys %$remotes) {
873 my $u = $remotes->{$repo_id}->{url} or next;
874 next if $u ne $url;
875 $existing = $repo_id;
876 last;
878 $existing;
881 sub init_remote_config {
882 my ($self, $url, $no_write) = @_;
883 $url =~ s!/+$!!; # strip trailing slash
884 my $r = read_all_remotes();
885 my $existing = find_existing_remote($url, $r);
886 if ($existing) {
887 unless ($no_write) {
888 print STDERR "Using existing ",
889 "[svn-remote \"$existing\"]\n";
891 $self->{repo_id} = $existing;
892 } else {
893 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
894 $existing = find_existing_remote($min_url, $r);
895 if ($existing) {
896 unless ($no_write) {
897 print STDERR "Using existing ",
898 "[svn-remote \"$existing\"]\n";
900 $self->{repo_id} = $existing;
902 if ($min_url ne $url) {
903 unless ($no_write) {
904 print STDERR "Using higher level of URL: ",
905 "$url => $min_url\n";
907 my $old_path = $self->{path};
908 $self->{path} = $url;
909 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
910 if (length $old_path) {
911 $self->{path} .= "/$old_path";
913 $url = $min_url;
916 my $orig_url;
917 if (!$existing) {
918 # verify that we aren't overwriting anything:
919 $orig_url = eval {
920 command_oneline('config', '--get',
921 "svn-remote.$self->{repo_id}.url")
923 if ($orig_url && ($orig_url ne $url)) {
924 die "svn-remote.$self->{repo_id}.url already set: ",
925 "$orig_url\nwanted to set to: $url\n";
928 my ($xrepo_id, $xpath) = find_ref($self->refname);
929 if (defined $xpath) {
930 die "svn-remote.$xrepo_id.fetch already set to track ",
931 "$xpath:refs/remotes/", $self->refname, "\n";
933 unless ($no_write) {
934 command_noisy('config',
935 "svn-remote.$self->{repo_id}.url", $url);
936 command_noisy('config', '--add',
937 "svn-remote.$self->{repo_id}.fetch",
938 "$self->{path}:".$self->refname);
940 $self->{url} = $url;
943 sub find_by_url { # repos_root and, path are optional
944 my ($class, $full_url, $repos_root, $path) = @_;
945 my $remotes = read_all_remotes();
946 if (defined $full_url && defined $repos_root && !defined $path) {
947 $path = $full_url;
948 $path =~ s#^\Q$repos_root\E(?:/|$)##;
950 foreach my $repo_id (keys %$remotes) {
951 my $u = $remotes->{$repo_id}->{url} or next;
952 next if defined $repos_root && $repos_root ne $u;
954 my $fetch = $remotes->{$repo_id}->{fetch} || {};
955 foreach (qw/branches tags/) {
956 resolve_local_globs($u, $fetch,
957 $remotes->{$repo_id}->{$_});
959 my $p = $path;
960 unless (defined $p) {
961 $p = $full_url;
962 $p =~ s#^\Q$u\E(?:/|$)## or next;
964 foreach my $f (keys %$fetch) {
965 next if $f ne $p;
966 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
969 undef;
972 sub init {
973 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
974 my $self = _new($class, $repo_id, $ref_id, $path);
975 if (defined $url) {
976 $self->init_remote_config($url, $no_write);
978 $self;
981 sub find_ref {
982 my ($ref_id) = @_;
983 foreach (command(qw/config -l/)) {
984 next unless m!^svn-remote\.(.+)\.fetch=
985 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
986 my ($repo_id, $path, $ref) = ($1, $2, $3);
987 if ($ref eq $ref_id) {
988 $path = '' if ($path =~ m#^\./?#);
989 return ($repo_id, $path);
992 (undef, undef, undef);
995 sub new {
996 my ($class, $ref_id, $repo_id, $path) = @_;
997 if (defined $ref_id && !defined $repo_id && !defined $path) {
998 ($repo_id, $path) = find_ref($ref_id);
999 if (!defined $repo_id) {
1000 die "Could not find a \"svn-remote.*.fetch\" key ",
1001 "in the repository configuration matching: ",
1002 "refs/remotes/$ref_id\n";
1005 my $self = _new($class, $repo_id, $ref_id, $path);
1006 if (!defined $self->{path} || !length $self->{path}) {
1007 my $fetch = command_oneline('config', '--get',
1008 "svn-remote.$repo_id.fetch",
1009 ":refs/remotes/$ref_id\$") or
1010 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1011 "\":refs/remotes/$ref_id\$\" in config\n";
1012 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1014 $self->{url} = command_oneline('config', '--get',
1015 "svn-remote.$repo_id.url") or
1016 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1017 if ((-z $self->db_path || ! -e $self->db_path) &&
1018 ::verify_ref($self->refname.'^0')) {
1019 $self->rebuild;
1021 $self;
1024 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1026 sub svm_uuid {
1027 my ($self) = @_;
1028 return $self->{svm}->{uuid} if $self->svm;
1029 $self->ra;
1030 unless ($self->{svm}) {
1031 die "SVM UUID not cached, and reading remotely failed\n";
1033 $self->{svm}->{uuid};
1036 sub svm {
1037 my ($self) = @_;
1038 return $self->{svm} if $self->{svm};
1039 my $svm;
1040 # see if we have it in our config, first:
1041 eval {
1042 my $section = "svn-remote.$self->{repo_id}";
1043 $svm = {
1044 source => tmp_config('--get', "$section.svm-source"),
1045 uuid => tmp_config('--get', "$section.svm-uuid"),
1048 $self->{svm} = $svm if ($svm && $svm->{source} && $svm->{uuid});
1049 $self->{svm};
1052 sub _set_svm_vars {
1053 my ($self, $ra) = @_;
1054 return $ra if $self->svm;
1056 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1057 "(svm:source, svm:mirror, svm:mirror) ",
1058 "from the following URLs:\n" );
1059 sub read_svm_props {
1060 my ($self, $props) = @_;
1061 my $src = $props->{'svm:source'};
1062 my $mirror = $props->{'svm:mirror'};
1063 my $uuid = $props->{'svm:uuid'};
1064 return undef if (!$src || !$mirror || !$uuid);
1066 chomp($src, $mirror, $uuid);
1068 $uuid =~ m{^[0-9a-f\-]{30,}$}
1069 or die "doesn't look right - svm:uuid is '$uuid'\n";
1070 # don't know what a '!' is there for, also the
1071 # username is of no interest
1072 $src =~ s{/?!$}{$mirror};
1073 $src =~ s{/+$}{}; # no trailing slashes please
1074 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1076 my $section = "svn-remote.$self->{repo_id}";
1077 tmp_config('--add', "$section.svm-source", $src);
1078 tmp_config('--add', "$section.svm-uuid", $uuid);
1079 $self->{svm} = { source => $src , uuid => $uuid };
1080 return 1;
1083 my $r = $ra->get_latest_revnum;
1084 my $path = $self->{path};
1085 my @tried_a = ($path);
1086 while (length $path) {
1087 if ($self->read_svm_props(($ra->get_dir($path, $r))[2])) {
1088 return $ra;
1090 $path =~ s#/?[^/]+$## && push @tried_a, $path;
1092 if ($self->read_svm_props(($ra->get_dir('', $r))[2])) {
1093 return $ra;
1096 if ($ra->{repos_root} eq $self->{url}) {
1097 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n";
1100 # nope, make sure we're connected to the repository root:
1101 my $ok;
1102 my @tried_b;
1103 $path = $ra->{svn_path};
1104 $path =~ s#/?[^/]+$##; # we already tried this one above
1105 $ra = Git::SVN::Ra->new($ra->{repos_root});
1106 while (length $path) {
1107 $ok = $self->read_svm_props(($ra->get_dir($path, $r))[2]);
1108 last if $ok;
1109 $path =~ s#/?[^/]+$## && push @tried_b, $path;
1111 $ok = $self->read_svm_props(($ra->get_dir('', $r))[2]) unless $ok;
1112 if (!$ok) {
1113 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n",
1114 map { " $ra->{url}/$_\n" } @tried_b, "\n"
1116 Git::SVN::Ra->new($self->{url});
1119 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1120 # remote lookup (useful for 'git svn log').
1121 sub ra_uuid {
1122 my ($self) = @_;
1123 unless ($self->{ra_uuid}) {
1124 my $key = "svn-remote.$self->{repo_id}.uuid";
1125 my $uuid = eval { tmp_config('--get', $key) };
1126 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1127 $self->{ra_uuid} = $uuid;
1128 } else {
1129 die "ra_uuid called without URL\n" unless $self->{url};
1130 $self->{ra_uuid} = $self->ra->get_uuid;
1131 tmp_config('--add', $key, $self->{ra_uuid});
1134 $self->{ra_uuid};
1137 sub ra {
1138 my ($self) = shift;
1139 my $ra = Git::SVN::Ra->new($self->{url});
1140 if ($self->use_svm_props && !$self->{svm}) {
1141 if ($self->no_metadata) {
1142 die "Can't have both 'noMetadata' and ",
1143 "'useSvmProps' options set!\n";
1145 $ra = $self->_set_svm_vars($ra);
1146 $self->{-want_revprops} = 1;
1148 $ra;
1151 sub rel_path {
1152 my ($self) = @_;
1153 my $repos_root = $self->ra->{repos_root};
1154 return $self->{path} if ($self->{url} eq $repos_root);
1155 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
1156 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
1159 sub traverse_ignore {
1160 my ($self, $fh, $path, $r) = @_;
1161 $path =~ s#^/+##g;
1162 my $ra = $self->ra;
1163 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1164 my $p = $path;
1165 $p =~ s#^\Q$ra->{svn_path}\E/##;
1166 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1167 if (my $s = $props->{'svn:ignore'}) {
1168 $s =~ s/[\r\n]+/\n/g;
1169 chomp $s;
1170 if (length $p == 0) {
1171 $s =~ s#\n#\n/$p#g;
1172 print $fh "/$s\n";
1173 } else {
1174 $s =~ s#\n#\n/$p/#g;
1175 print $fh "/$p/$s\n";
1178 foreach (sort keys %$dirent) {
1179 next if $dirent->{$_}->kind != $SVN::Node::dir;
1180 $self->traverse_ignore($fh, "$path/$_", $r);
1184 sub last_rev { ($_[0]->last_rev_commit)[0] }
1185 sub last_commit { ($_[0]->last_rev_commit)[1] }
1187 # returns the newest SVN revision number and newest commit SHA1
1188 sub last_rev_commit {
1189 my ($self) = @_;
1190 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1191 return ($self->{last_rev}, $self->{last_commit});
1193 my $c = ::verify_ref($self->refname.'^0');
1194 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1195 my $rev = (::cmt_metadata($c))[1];
1196 if (defined $rev) {
1197 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1198 return ($rev, $c);
1201 my $db_path = $self->db_path;
1202 unless (-e $db_path) {
1203 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1204 return (undef, undef);
1206 my $offset = -41; # from tail
1207 my $rl;
1208 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1209 sysseek($fh, $offset, 2); # don't care for errors
1210 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1211 chomp $rl;
1212 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1213 $offset -= 41;
1214 sysseek($fh, $offset, 2); # don't care for errors
1215 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1216 chomp $rl;
1218 if ($c && $c ne $rl) {
1219 die "$db_path and ", $self->refname,
1220 " inconsistent!:\n$c != $rl\n";
1222 my $rev = sysseek($fh, 0, 1) or croak $!;
1223 $rev = ($rev - 41) / 41;
1224 close $fh or croak $!;
1225 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1226 return ($rev, $c);
1229 sub get_fetch_range {
1230 my ($self, $min, $max) = @_;
1231 $max ||= $self->ra->get_latest_revnum;
1232 $min ||= $self->rev_db_max;
1233 (++$min, $max);
1236 sub tmp_config {
1237 my (@args) = @_;
1238 my $config = "$ENV{GIT_DIR}/svn/config";
1239 unless (-f $config) {
1240 open my $fh, '>', $config or
1241 die "Can't open $config: $!\n";
1242 print $fh "; This file is used internally by git-svn\n" or
1243 die "Couldn't write to $config: $!\n";
1244 print $fh "; You should not have to edit it\n" or
1245 die "Couldn't write to $config: $!\n";
1246 close $fh or die "Couldn't close $config: $!\n";
1248 my $old_config = $ENV{GIT_CONFIG};
1249 $ENV{GIT_CONFIG} = $config;
1250 $@ = undef;
1251 my @ret = eval { command('config', @args) };
1252 my $err = $@;
1253 if (defined $old_config) {
1254 $ENV{GIT_CONFIG} = $old_config;
1255 } else {
1256 delete $ENV{GIT_CONFIG};
1258 die $err if $err;
1259 wantarray ? @ret : $ret[0];
1262 sub tmp_index_do {
1263 my ($self, $sub) = @_;
1264 my $old_index = $ENV{GIT_INDEX_FILE};
1265 $ENV{GIT_INDEX_FILE} = $self->{index};
1266 $@ = undef;
1267 my @ret = eval { &$sub };
1268 my $err = $@;
1269 if (defined $old_index) {
1270 $ENV{GIT_INDEX_FILE} = $old_index;
1271 } else {
1272 delete $ENV{GIT_INDEX_FILE};
1274 die $err if $err;
1275 wantarray ? @ret : $ret[0];
1278 sub assert_index_clean {
1279 my ($self, $treeish) = @_;
1281 $self->tmp_index_do(sub {
1282 command_noisy('read-tree', $treeish) unless -e $self->{index};
1283 my $x = command_oneline('write-tree');
1284 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1285 /^tree ($::sha1)/mo);
1286 if ($y ne $x) {
1287 unlink $self->{index} or croak $!;
1288 command_noisy('read-tree', $treeish);
1290 $x = command_oneline('write-tree');
1291 if ($y ne $x) {
1292 ::fatal "trees ($treeish) $y != $x\n",
1293 "Something is seriously wrong...\n";
1298 sub get_commit_parents {
1299 my ($self, $log_entry) = @_;
1300 my (%seen, @ret, @tmp);
1301 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1302 if (my $ip = $self->{inject_parents}) {
1303 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1304 push @tmp, $commit;
1307 if (my $cur = ::verify_ref($self->refname.'^0')) {
1308 push @tmp, $cur;
1310 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1311 while (my $p = shift @tmp) {
1312 next if $seen{$p};
1313 $seen{$p} = 1;
1314 push @ret, $p;
1315 # MAXPARENT is defined to 16 in commit-tree.c:
1316 last if @ret >= 16;
1318 if (@tmp) {
1319 die "r$log_entry->{revision}: No room for parents:\n\t",
1320 join("\n\t", @tmp), "\n";
1322 @ret;
1325 sub full_url {
1326 my ($self) = @_;
1327 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1330 sub do_git_commit {
1331 my ($self, $log_entry) = @_;
1332 my $lr = $self->last_rev;
1333 if (defined $lr && $lr >= $log_entry->{revision}) {
1334 die "Last fetched revision of ", $self->refname,
1335 " was r$lr, but we are about to fetch: ",
1336 "r$log_entry->{revision}!\n";
1338 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1339 croak "$log_entry->{revision} = $c already exists! ",
1340 "Why are we refetching it?\n";
1342 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1343 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1344 $log_entry->{email};
1345 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1347 my $tree = $log_entry->{tree};
1348 if (!defined $tree) {
1349 $tree = $self->tmp_index_do(sub {
1350 command_oneline('write-tree') });
1352 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1354 my @exec = ('git-commit-tree', $tree);
1355 foreach ($self->get_commit_parents($log_entry)) {
1356 push @exec, '-p', $_;
1358 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1359 or croak $!;
1360 print $msg_fh $log_entry->{log} or croak $!;
1361 unless ($self->no_metadata) {
1362 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1363 or croak $!;
1365 $msg_fh->flush == 0 or croak $!;
1366 close $msg_fh or croak $!;
1367 chomp(my $commit = do { local $/; <$out_fh> });
1368 close $out_fh or croak $!;
1369 waitpid $pid, 0;
1370 croak $? if $?;
1371 if ($commit !~ /^$::sha1$/o) {
1372 die "Failed to commit, invalid sha1: $commit\n";
1375 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1377 $self->{last_rev} = $log_entry->{revision};
1378 $self->{last_commit} = $commit;
1379 print "r$log_entry->{revision}";
1380 if (defined $log_entry->{svm_revision}) {
1381 print " (\@$log_entry->{svm_revision})";
1382 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1383 0, $self->svm_uuid);
1385 print " = $commit ($self->{ref_id})\n";
1386 if (defined $_repack && (--$_repack_nr == 0)) {
1387 $_repack_nr = $_repack;
1388 # repack doesn't use any arguments with spaces in them, does it?
1389 print "Running git repack $_repack_flags ...\n";
1390 command_noisy('repack', split(/\s+/, $_repack_flags));
1391 print "Done repacking\n";
1393 return $commit;
1396 sub match_paths {
1397 my ($self, $paths, $r) = @_;
1398 return 1 if $self->{path} eq '';
1399 if (my $path = $paths->{"/$self->{path}"}) {
1400 return ($path->{action} eq 'D') ? 0 : 1;
1402 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1403 if (grep /$self->{path_regex}/, keys %$paths) {
1404 return 1;
1406 my $c = '';
1407 foreach (split m#/#, $self->{path}) {
1408 $c .= "/$_";
1409 next unless ($paths->{$c} &&
1410 ($paths->{$c}->{action} =~ /^[AR]$/));
1411 if ($self->ra->check_path($self->{path}, $r) ==
1412 $SVN::Node::dir) {
1413 return 1;
1416 return 0;
1419 sub find_parent_branch {
1420 my ($self, $paths, $rev) = @_;
1421 return undef unless $self->follow_parent;
1422 unless (defined $paths) {
1423 my $err_handler = $SVN::Error::handler;
1424 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1425 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1426 $paths =
1427 Git::SVN::Ra::dup_changed_paths($_[0]) });
1428 $SVN::Error::handler = $err_handler;
1430 return undef unless defined $paths;
1432 # look for a parent from another branch:
1433 my @b_path_components = split m#/#, $self->rel_path;
1434 my @a_path_components;
1435 my $i;
1436 while (@b_path_components) {
1437 $i = $paths->{'/'.join('/', @b_path_components)};
1438 last if $i && defined $i->{copyfrom_path};
1439 unshift(@a_path_components, pop(@b_path_components));
1441 return undef unless defined $i && defined $i->{copyfrom_path};
1442 my $branch_from = $i->{copyfrom_path};
1443 if (@a_path_components) {
1444 print STDERR "branch_from: $branch_from => ";
1445 $branch_from .= '/'.join('/', @a_path_components);
1446 print STDERR $branch_from, "\n";
1448 my $r = $i->{copyfrom_rev};
1449 my $repos_root = $self->ra->{repos_root};
1450 my $url = $self->ra->{url};
1451 my $new_url = $repos_root . $branch_from;
1452 print STDERR "Found possible branch point: ",
1453 "$new_url => ", $self->full_url, ", $r\n";
1454 $branch_from =~ s#^/##;
1455 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1456 unless ($gs) {
1457 my $ref_id = $self->{ref_id};
1458 $ref_id =~ s/\@\d+$//;
1459 $ref_id .= "\@$r";
1460 # just grow a tail if we're not unique enough :x
1461 $ref_id .= '-' while find_ref($ref_id);
1462 print STDERR "Initializing parent: $ref_id\n";
1463 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1465 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1466 if (!defined $r0 || !defined $parent) {
1467 $gs->fetch(0, $r);
1468 ($r0, $parent) = $gs->last_rev_commit;
1470 if (defined $r0 && defined $parent) {
1471 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1472 $self->assert_index_clean($parent);
1473 my $ed;
1474 if ($self->ra->can_do_switch) {
1475 print STDERR "Following parent with do_switch\n";
1476 # do_switch works with svn/trunk >= r22312, but that
1477 # is not included with SVN 1.4.3 (the latest version
1478 # at the moment), so we can't rely on it
1479 $self->{last_commit} = $parent;
1480 $ed = SVN::Git::Fetcher->new($self);
1481 $gs->ra->gs_do_switch($r0, $rev, $gs,
1482 $self->full_url, $ed)
1483 or die "SVN connection failed somewhere...\n";
1484 } else {
1485 print STDERR "Following parent with do_update\n";
1486 $ed = SVN::Git::Fetcher->new($self);
1487 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1488 or die "SVN connection failed somewhere...\n";
1490 print STDERR "Successfully followed parent\n";
1491 return $self->make_log_entry($rev, [$parent], $ed);
1493 return undef;
1496 sub do_fetch {
1497 my ($self, $paths, $rev) = @_;
1498 my $ed;
1499 my ($last_rev, @parents);
1500 if (my $lc = $self->last_commit) {
1501 # we can have a branch that was deleted, then re-added
1502 # under the same name but copied from another path, in
1503 # which case we'll have multiple parents (we don't
1504 # want to break the original ref, nor lose copypath info):
1505 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1506 push @{$log_entry->{parents}}, $lc;
1507 return $log_entry;
1509 $ed = SVN::Git::Fetcher->new($self);
1510 $last_rev = $self->{last_rev};
1511 $ed->{c} = $lc;
1512 @parents = ($lc);
1513 } else {
1514 $last_rev = $rev;
1515 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1516 return $log_entry;
1518 $ed = SVN::Git::Fetcher->new($self);
1520 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1521 die "SVN connection failed somewhere...\n";
1523 $self->make_log_entry($rev, \@parents, $ed);
1526 sub get_untracked {
1527 my ($self, $ed) = @_;
1528 my @out;
1529 my $h = $ed->{empty};
1530 foreach (sort keys %$h) {
1531 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1532 push @out, " $act: " . uri_encode($_);
1533 warn "W: $act: $_\n";
1535 foreach my $t (qw/dir_prop file_prop/) {
1536 $h = $ed->{$t} or next;
1537 foreach my $path (sort keys %$h) {
1538 my $ppath = $path eq '' ? '.' : $path;
1539 foreach my $prop (sort keys %{$h->{$path}}) {
1540 next if $SKIP_PROP{$prop};
1541 my $v = $h->{$path}->{$prop};
1542 my $t_ppath_prop = "$t: " .
1543 uri_encode($ppath) . ' ' .
1544 uri_encode($prop);
1545 if (defined $v) {
1546 push @out, " +$t_ppath_prop " .
1547 uri_encode($v);
1548 } else {
1549 push @out, " -$t_ppath_prop";
1554 foreach my $t (qw/absent_file absent_directory/) {
1555 $h = $ed->{$t} or next;
1556 foreach my $parent (sort keys %$h) {
1557 foreach my $path (sort @{$h->{$parent}}) {
1558 push @out, " $t: " .
1559 uri_encode("$parent/$path");
1560 warn "W: $t: $parent/$path ",
1561 "Insufficient permissions?\n";
1565 \@out;
1568 sub parse_svn_date {
1569 my $date = shift || return '+0000 1970-01-01 00:00:00';
1570 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1571 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1572 croak "Unable to parse date: $date\n";
1573 "+0000 $Y-$m-$d $H:$M:$S";
1576 sub check_author {
1577 my ($author) = @_;
1578 if (!defined $author || length $author == 0) {
1579 $author = '(no author)';
1581 if (defined $::_authors && ! defined $::users{$author}) {
1582 die "Author: $author not defined in $::_authors file\n";
1584 $author;
1587 sub make_log_entry {
1588 my ($self, $rev, $parents, $ed) = @_;
1589 my $untracked = $self->get_untracked($ed);
1591 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1592 print $un "r$rev\n" or croak $!;
1593 print $un $_, "\n" foreach @$untracked;
1594 my %log_entry = ( parents => $parents || [], revision => $rev,
1595 log => '');
1597 my $headrev;
1598 my $logged = delete $self->{logged_rev_props};
1599 if (!$logged || $self->{-want_revprops}) {
1600 my $rp = $self->ra->rev_proplist($rev);
1601 foreach (sort keys %$rp) {
1602 my $v = $rp->{$_};
1603 if (/^svn:(author|date|log)$/) {
1604 $log_entry{$1} = $v;
1605 } elsif ($_ eq 'svm:headrev') {
1606 $headrev = $v;
1607 } else {
1608 print $un " rev_prop: ", uri_encode($_), ' ',
1609 uri_encode($v), "\n";
1612 } else {
1613 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1615 close $un or croak $!;
1617 $log_entry{date} = parse_svn_date($log_entry{date});
1618 $log_entry{log} .= "\n";
1619 my $author = $log_entry{author} = check_author($log_entry{author});
1620 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1621 : ($author, undef);
1622 if (defined $headrev && $self->use_svm_props) {
1623 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1624 if ($uuid ne $self->{svm}->{uuid}) {
1625 die "UUID mismatch on SVM path:\n",
1626 "expected: $self->{svm}->{uuid}\n",
1627 " got: $uuid\n";
1629 my $full_url = $self->{svm}->{source};
1630 $full_url .= "/$self->{path}" if length $self->{path};
1631 $log_entry{metadata} = "$full_url\@$r $uuid";
1632 $log_entry{svm_revision} = $r;
1633 $email ||= "$author\@$uuid"
1634 } else {
1635 $log_entry{metadata} = $self->full_url . "\@$rev " .
1636 $self->ra->get_uuid;
1637 $email ||= "$author\@" . $self->ra->get_uuid;
1639 $log_entry{name} = $name;
1640 $log_entry{email} = $email;
1641 \%log_entry;
1644 sub fetch {
1645 my ($self, $min_rev, $max_rev, @parents) = @_;
1646 my ($last_rev, $last_commit) = $self->last_rev_commit;
1647 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1648 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1651 sub set_tree_cb {
1652 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1653 $self->{inject_parents} = { $rev => $tree };
1654 $self->fetch(undef, undef);
1657 sub set_tree {
1658 my ($self, $tree) = (shift, shift);
1659 my $log_entry = ::get_commit_entry($tree);
1660 unless ($self->{last_rev}) {
1661 fatal("Must have an existing revision to commit\n");
1663 my %ed_opts = ( r => $self->{last_rev},
1664 log => $log_entry->{log},
1665 ra => $self->ra,
1666 tree_a => $self->{last_commit},
1667 tree_b => $tree,
1668 editor_cb => sub {
1669 $self->set_tree_cb($log_entry, $tree, @_) },
1670 svn_path => $self->{path} );
1671 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1672 print "No changes\nr$self->{last_rev} = $tree\n";
1676 sub rebuild {
1677 my ($self) = @_;
1678 my $db_path = $self->db_path;
1679 if (-f $self->{db_root}) {
1680 rename $self->{db_root}, $db_path or die
1681 "rename $self->{db_root} => $db_path failed: $!\n";
1682 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1683 symlink $base, $self->{db_root} or die
1684 "symlink $base => $self->{db_root} failed: $!\n";
1685 return;
1687 print "Rebuilding $db_path ...\n";
1688 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1689 my $latest;
1690 my $full_url = $self->full_url;
1691 my $svn_uuid;
1692 while (<$rev_list>) {
1693 chomp;
1694 my $c = $_;
1695 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1696 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1698 # ignore merges (from set-tree)
1699 next if (!defined $rev || !$uuid);
1701 # if we merged or otherwise started elsewhere, this is
1702 # how we break out of it
1703 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1704 ($full_url && $url && ($url ne $full_url))) {
1705 next;
1707 $latest ||= $rev;
1708 $svn_uuid ||= $uuid;
1710 $self->rev_db_set($rev, $c);
1711 print "r$rev = $c\n";
1713 command_close_pipe($rev_list, $ctx);
1714 print "Done rebuilding $db_path\n";
1717 # rev_db:
1718 # Tie::File seems to be prone to offset errors if revisions get sparse,
1719 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1720 # one of my favorite modules is out :< Next up would be one of the DBM
1721 # modules, but I'm not sure which is most portable... So I'll just
1722 # go with something that's plain-text, but still capable of
1723 # being randomly accessed. So here's my ultra-simple fixed-width
1724 # database. All records are 40 characters + "\n", so it's easy to seek
1725 # to a revision: (41 * rev) is the byte offset.
1726 # A record of 40 0s denotes an empty revision.
1727 # And yes, it's still pretty fast (faster than Tie::File).
1728 # These files are disposable unless noMetadata or useSvmProps is set
1730 sub _rev_db_set {
1731 my ($fh, $rev, $commit) = @_;
1732 my $offset = $rev * 41;
1733 # assume that append is the common case:
1734 seek $fh, 0, 2 or croak $!;
1735 my $pos = tell $fh;
1736 if ($pos < $offset) {
1737 for (1 .. (($offset - $pos) / 41)) {
1738 print $fh (('0' x 40),"\n") or croak $!;
1741 seek $fh, $offset, 0 or croak $!;
1742 print $fh $commit,"\n" or croak $!;
1745 sub mkfile {
1746 my ($path) = @_;
1747 unless (-e $path) {
1748 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1749 mkpath([$dir]) unless -d $dir;
1750 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1751 close $fh or die "Couldn't close (create) $path: $!\n";
1755 sub rev_db_set {
1756 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1757 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1758 my $db = $self->db_path($uuid);
1759 my $db_lock = "$db.lock";
1760 my $sig;
1761 if ($update_ref) {
1762 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1763 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1765 mkfile($db);
1767 $LOCKFILES{$db_lock} = 1;
1768 my $sync;
1769 # both of these options make our .rev_db file very, very important
1770 # and we can't afford to lose it because rebuild() won't work
1771 if ($self->use_svm_props || $self->no_metadata) {
1772 $sync = 1;
1773 copy($db, $db_lock) or die "rev_db_set(@_): ",
1774 "Failed to copy: ",
1775 "$db => $db_lock ($!)\n";
1776 } else {
1777 rename $db, $db_lock or die "rev_db_set(@_): ",
1778 "Failed to rename: ",
1779 "$db => $db_lock ($!)\n";
1781 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
1782 _rev_db_set($fh, $rev, $commit);
1783 if ($sync) {
1784 $fh->flush or die "Couldn't flush $db_lock: $!\n";
1785 $fh->sync or die "Couldn't sync $db_lock: $!\n";
1787 close $fh or croak $!;
1788 if ($update_ref) {
1789 command_noisy('update-ref', '-m', "r$rev",
1790 $self->refname, $commit);
1792 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1793 "$db_lock => $db ($!)\n";
1794 delete $LOCKFILES{$db_lock};
1795 if ($update_ref) {
1796 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1797 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1798 kill $sig, $$ if defined $sig;
1802 sub rev_db_max {
1803 my ($self) = @_;
1804 my $db_path = $self->db_path;
1805 my @stat = stat $db_path or return 0;
1806 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
1807 my $max = $stat[7] / 41;
1808 (($max > 0) ? $max - 1 : 0);
1811 sub rev_db_get {
1812 my ($self, $rev, $uuid) = @_;
1813 my $ret;
1814 my $offset = $rev * 41;
1815 my $db_path = $self->db_path($uuid);
1816 return undef unless -e $db_path;
1817 open my $fh, '<', $db_path or croak $!;
1818 if (sysseek($fh, $offset, 0) == $offset) {
1819 my $read = sysread($fh, $ret, 40);
1820 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1822 close $fh or croak $!;
1823 $ret;
1826 sub find_rev_before {
1827 my ($self, $rev, $eq_ok) = @_;
1828 --$rev unless $eq_ok;
1829 while ($rev > 0) {
1830 if (my $c = $self->rev_db_get($rev)) {
1831 return ($rev, $c);
1833 --$rev;
1835 return (undef, undef);
1838 sub _new {
1839 my ($class, $repo_id, $ref_id, $path) = @_;
1840 unless (defined $repo_id && length $repo_id) {
1841 $repo_id = $Git::SVN::default_repo_id;
1843 unless (defined $ref_id && length $ref_id) {
1844 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1846 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1847 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1848 $_[3] = $path = '' unless (defined $path);
1849 mkpath([$dir]);
1850 bless {
1851 ref_id => $ref_id, dir => $dir, index => "$dir/index",
1852 path => $path, config => "$ENV{GIT_DIR}/svn/config",
1853 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
1856 sub db_path {
1857 my ($self, $uuid) = @_;
1858 $uuid ||= $self->ra_uuid;
1859 "$self->{db_root}.$uuid";
1862 sub uri_encode {
1863 my ($f) = @_;
1864 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1868 package Git::SVN::Prompt;
1869 use strict;
1870 use warnings;
1871 require SVN::Core;
1872 use vars qw/$_no_auth_cache $_username/;
1874 sub simple {
1875 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1876 $may_save = undef if $_no_auth_cache;
1877 $default_username = $_username if defined $_username;
1878 if (defined $default_username && length $default_username) {
1879 if (defined $realm && length $realm) {
1880 print STDERR "Authentication realm: $realm\n";
1881 STDERR->flush;
1883 $cred->username($default_username);
1884 } else {
1885 username($cred, $realm, $may_save, $pool);
1887 $cred->password(_read_password("Password for '" .
1888 $cred->username . "': ", $realm));
1889 $cred->may_save($may_save);
1890 $SVN::_Core::SVN_NO_ERROR;
1893 sub ssl_server_trust {
1894 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1895 $may_save = undef if $_no_auth_cache;
1896 print STDERR "Error validating server certificate for '$realm':\n";
1897 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1898 print STDERR " - The certificate is not issued by a trusted ",
1899 "authority. Use the\n",
1900 " fingerprint to validate the certificate manually!\n";
1902 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1903 print STDERR " - The certificate hostname does not match.\n";
1905 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1906 print STDERR " - The certificate is not yet valid.\n";
1908 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1909 print STDERR " - The certificate has expired.\n";
1911 if ($failures & $SVN::Auth::SSL::OTHER) {
1912 print STDERR " - The certificate has an unknown error.\n";
1914 printf STDERR
1915 "Certificate information:\n".
1916 " - Hostname: %s\n".
1917 " - Valid: from %s until %s\n".
1918 " - Issuer: %s\n".
1919 " - Fingerprint: %s\n",
1920 map $cert_info->$_, qw(hostname valid_from valid_until
1921 issuer_dname fingerprint);
1922 my $choice;
1923 prompt:
1924 print STDERR $may_save ?
1925 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1926 "(R)eject or accept (t)emporarily? ";
1927 STDERR->flush;
1928 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1929 if ($choice =~ /^t$/i) {
1930 $cred->may_save(undef);
1931 } elsif ($choice =~ /^r$/i) {
1932 return -1;
1933 } elsif ($may_save && $choice =~ /^p$/i) {
1934 $cred->may_save($may_save);
1935 } else {
1936 goto prompt;
1938 $cred->accepted_failures($failures);
1939 $SVN::_Core::SVN_NO_ERROR;
1942 sub ssl_client_cert {
1943 my ($cred, $realm, $may_save, $pool) = @_;
1944 $may_save = undef if $_no_auth_cache;
1945 print STDERR "Client certificate filename: ";
1946 STDERR->flush;
1947 chomp(my $filename = <STDIN>);
1948 $cred->cert_file($filename);
1949 $cred->may_save($may_save);
1950 $SVN::_Core::SVN_NO_ERROR;
1953 sub ssl_client_cert_pw {
1954 my ($cred, $realm, $may_save, $pool) = @_;
1955 $may_save = undef if $_no_auth_cache;
1956 $cred->password(_read_password("Password: ", $realm));
1957 $cred->may_save($may_save);
1958 $SVN::_Core::SVN_NO_ERROR;
1961 sub username {
1962 my ($cred, $realm, $may_save, $pool) = @_;
1963 $may_save = undef if $_no_auth_cache;
1964 if (defined $realm && length $realm) {
1965 print STDERR "Authentication realm: $realm\n";
1967 my $username;
1968 if (defined $_username) {
1969 $username = $_username;
1970 } else {
1971 print STDERR "Username: ";
1972 STDERR->flush;
1973 chomp($username = <STDIN>);
1975 $cred->username($username);
1976 $cred->may_save($may_save);
1977 $SVN::_Core::SVN_NO_ERROR;
1980 sub _read_password {
1981 my ($prompt, $realm) = @_;
1982 print STDERR $prompt;
1983 STDERR->flush;
1984 require Term::ReadKey;
1985 Term::ReadKey::ReadMode('noecho');
1986 my $password = '';
1987 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1988 last if $key =~ /[\012\015]/; # \n\r
1989 $password .= $key;
1991 Term::ReadKey::ReadMode('restore');
1992 print STDERR "\n";
1993 STDERR->flush;
1994 $password;
1997 package main;
2000 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2001 $SVN::Node::dir.$SVN::Node::unknown.
2002 $SVN::Node::none.$SVN::Node::file.
2003 $SVN::Node::dir.$SVN::Node::unknown.
2004 $SVN::Auth::SSL::CNMISMATCH.
2005 $SVN::Auth::SSL::NOTYETVALID.
2006 $SVN::Auth::SSL::EXPIRED.
2007 $SVN::Auth::SSL::UNKNOWNCA.
2008 $SVN::Auth::SSL::OTHER;
2011 package SVN::Git::Fetcher;
2012 use vars qw/@ISA/;
2013 use strict;
2014 use warnings;
2015 use Carp qw/croak/;
2016 use IO::File qw//;
2017 use Digest::MD5;
2019 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2020 sub new {
2021 my ($class, $git_svn) = @_;
2022 my $self = SVN::Delta::Editor->new;
2023 bless $self, $class;
2024 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2025 $self->{empty} = {};
2026 $self->{dir_prop} = {};
2027 $self->{file_prop} = {};
2028 $self->{absent_dir} = {};
2029 $self->{absent_file} = {};
2030 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2031 $self;
2034 sub set_path_strip {
2035 my ($self, $path) = @_;
2036 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2039 sub open_root {
2040 { path => '' };
2043 sub open_directory {
2044 my ($self, $path, $pb, $rev) = @_;
2045 { path => $path };
2048 sub git_path {
2049 my ($self, $path) = @_;
2050 if ($self->{path_strip}) {
2051 $path =~ s!$self->{path_strip}!! or
2052 die "Failed to strip path '$path' ($self->{path_strip})\n";
2054 $path;
2057 sub delete_entry {
2058 my ($self, $path, $rev, $pb) = @_;
2060 my $gpath = $self->git_path($path);
2061 return undef if ($gpath eq '');
2063 # remove entire directories.
2064 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2065 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2066 -r --name-only -z/,
2067 $self->{c}, '--', $gpath);
2068 local $/ = "\0";
2069 while (<$ls>) {
2070 chomp;
2071 $self->{gii}->remove($_);
2072 print "\tD\t$_\n" unless $::_q;
2074 print "\tD\t$gpath/\n" unless $::_q;
2075 command_close_pipe($ls, $ctx);
2076 $self->{empty}->{$path} = 0
2077 } else {
2078 $self->{gii}->remove($gpath);
2079 print "\tD\t$gpath\n" unless $::_q;
2081 undef;
2084 sub open_file {
2085 my ($self, $path, $pb, $rev) = @_;
2086 my $gpath = $self->git_path($path);
2087 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2088 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2089 unless (defined $mode && defined $blob) {
2090 die "$path was not found in commit $self->{c} (r$rev)\n";
2092 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2093 pool => SVN::Pool->new, action => 'M' };
2096 sub add_file {
2097 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2098 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2099 delete $self->{empty}->{$dir};
2100 { path => $path, mode_a => 100644, mode_b => 100644,
2101 pool => SVN::Pool->new, action => 'A' };
2104 sub add_directory {
2105 my ($self, $path, $cp_path, $cp_rev) = @_;
2106 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2107 delete $self->{empty}->{$dir};
2108 $self->{empty}->{$path} = 1;
2109 { path => $path };
2112 sub change_dir_prop {
2113 my ($self, $db, $prop, $value) = @_;
2114 $self->{dir_prop}->{$db->{path}} ||= {};
2115 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2116 undef;
2119 sub absent_directory {
2120 my ($self, $path, $pb) = @_;
2121 $self->{absent_dir}->{$pb->{path}} ||= [];
2122 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2123 undef;
2126 sub absent_file {
2127 my ($self, $path, $pb) = @_;
2128 $self->{absent_file}->{$pb->{path}} ||= [];
2129 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2130 undef;
2133 sub change_file_prop {
2134 my ($self, $fb, $prop, $value) = @_;
2135 if ($prop eq 'svn:executable') {
2136 if ($fb->{mode_b} != 120000) {
2137 $fb->{mode_b} = defined $value ? 100755 : 100644;
2139 } elsif ($prop eq 'svn:special') {
2140 $fb->{mode_b} = defined $value ? 120000 : 100644;
2141 } else {
2142 $self->{file_prop}->{$fb->{path}} ||= {};
2143 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2145 undef;
2148 sub apply_textdelta {
2149 my ($self, $fb, $exp) = @_;
2150 my $fh = IO::File->new_tmpfile;
2151 $fh->autoflush(1);
2152 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2153 # (but $base does not,) so dup() it for reading in close_file
2154 open my $dup, '<&', $fh or croak $!;
2155 my $base = IO::File->new_tmpfile;
2156 $base->autoflush(1);
2157 if ($fb->{blob}) {
2158 defined (my $pid = fork) or croak $!;
2159 if (!$pid) {
2160 open STDOUT, '>&', $base or croak $!;
2161 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2162 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2164 waitpid $pid, 0;
2165 croak $? if $?;
2167 if (defined $exp) {
2168 seek $base, 0, 0 or croak $!;
2169 my $md5 = Digest::MD5->new;
2170 $md5->addfile($base);
2171 my $got = $md5->hexdigest;
2172 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2173 "expected: $exp\n",
2174 " got: $got\n" if ($got ne $exp);
2177 seek $base, 0, 0 or croak $!;
2178 $fb->{fh} = $dup;
2179 $fb->{base} = $base;
2180 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2183 sub close_file {
2184 my ($self, $fb, $exp) = @_;
2185 my $hash;
2186 my $path = $self->git_path($fb->{path});
2187 if (my $fh = $fb->{fh}) {
2188 seek($fh, 0, 0) or croak $!;
2189 my $md5 = Digest::MD5->new;
2190 $md5->addfile($fh);
2191 my $got = $md5->hexdigest;
2192 die "Checksum mismatch: $path\n",
2193 "expected: $exp\n got: $got\n" if ($got ne $exp);
2194 seek($fh, 0, 0) or croak $!;
2195 if ($fb->{mode_b} == 120000) {
2196 read($fh, my $buf, 5) == 5 or croak $!;
2197 $buf eq 'link ' or die "$path has mode 120000",
2198 "but is not a link\n";
2200 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2201 if (!$pid) {
2202 open STDIN, '<&', $fh or croak $!;
2203 exec qw/git-hash-object -w --stdin/ or croak $!;
2205 chomp($hash = do { local $/; <$out> });
2206 close $out or croak $!;
2207 close $fh or croak $!;
2208 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2209 close $fb->{base} or croak $!;
2210 } else {
2211 $hash = $fb->{blob} or die "no blob information\n";
2213 $fb->{pool}->clear;
2214 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2215 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2216 undef;
2219 sub abort_edit {
2220 my $self = shift;
2221 $self->{nr} = $self->{gii}->{nr};
2222 delete $self->{gii};
2223 $self->SUPER::abort_edit(@_);
2226 sub close_edit {
2227 my $self = shift;
2228 $self->{git_commit_ok} = 1;
2229 $self->{nr} = $self->{gii}->{nr};
2230 delete $self->{gii};
2231 $self->SUPER::close_edit(@_);
2234 package SVN::Git::Editor;
2235 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2236 use strict;
2237 use warnings;
2238 use Carp qw/croak/;
2239 use IO::File;
2240 use Digest::MD5;
2242 sub new {
2243 my ($class, $opts) = @_;
2244 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2245 die "$_ required!\n" unless (defined $opts->{$_});
2248 my $pool = SVN::Pool->new;
2249 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2250 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2251 $opts->{r}, $mods);
2253 # $opts->{ra} functions should not be used after this:
2254 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2255 $opts->{editor_cb}, $pool);
2256 my $self = SVN::Delta::Editor->new(@ce, $pool);
2257 bless $self, $class;
2258 foreach (qw/svn_path r tree_a tree_b/) {
2259 $self->{$_} = $opts->{$_};
2261 $self->{url} = $opts->{ra}->{url};
2262 $self->{mods} = $mods;
2263 $self->{types} = $types;
2264 $self->{pool} = $pool;
2265 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2266 $self->{rm} = { };
2267 $self->{path_prefix} = length $self->{svn_path} ?
2268 "$self->{svn_path}/" : '';
2269 return $self;
2272 sub generate_diff {
2273 my ($tree_a, $tree_b) = @_;
2274 my @diff_tree = qw(diff-tree -z -r);
2275 if ($_cp_similarity) {
2276 push @diff_tree, "-C$_cp_similarity";
2277 } else {
2278 push @diff_tree, '-C';
2280 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2281 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2282 push @diff_tree, $tree_a, $tree_b;
2283 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2284 local $/ = "\0";
2285 my $state = 'meta';
2286 my @mods;
2287 while (<$diff_fh>) {
2288 chomp $_; # this gets rid of the trailing "\0"
2289 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2290 $::sha1\s($::sha1)\s
2291 ([MTCRAD])\d*$/xo) {
2292 push @mods, { mode_a => $1, mode_b => $2,
2293 sha1_b => $3, chg => $4 };
2294 if ($4 =~ /^(?:C|R)$/) {
2295 $state = 'file_a';
2296 } else {
2297 $state = 'file_b';
2299 } elsif ($state eq 'file_a') {
2300 my $x = $mods[$#mods] or croak "Empty array\n";
2301 if ($x->{chg} !~ /^(?:C|R)$/) {
2302 croak "Error parsing $_, $x->{chg}\n";
2304 $x->{file_a} = $_;
2305 $state = 'file_b';
2306 } elsif ($state eq 'file_b') {
2307 my $x = $mods[$#mods] or croak "Empty array\n";
2308 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2309 croak "Error parsing $_, $x->{chg}\n";
2311 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2312 croak "Error parsing $_, $x->{chg}\n";
2314 $x->{file_b} = $_;
2315 $state = 'meta';
2316 } else {
2317 croak "Error parsing $_\n";
2320 command_close_pipe($diff_fh, $ctx);
2321 \@mods;
2324 sub check_diff_paths {
2325 my ($ra, $pfx, $rev, $mods) = @_;
2326 my %types;
2327 $pfx .= '/' if length $pfx;
2329 sub type_diff_paths {
2330 my ($ra, $types, $path, $rev) = @_;
2331 my @p = split m#/+#, $path;
2332 my $c = shift @p;
2333 unless (defined $types->{$c}) {
2334 $types->{$c} = $ra->check_path($c, $rev);
2336 while (@p) {
2337 $c .= '/' . shift @p;
2338 next if defined $types->{$c};
2339 $types->{$c} = $ra->check_path($c, $rev);
2343 foreach my $m (@$mods) {
2344 foreach my $f (qw/file_a file_b/) {
2345 next unless defined $m->{$f};
2346 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2347 if (length $pfx.$dir && ! defined $types{$dir}) {
2348 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2352 \%types;
2355 sub split_path {
2356 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2359 sub repo_path {
2360 my ($self, $path) = @_;
2361 $self->{path_prefix}.(defined $path ? $path : '');
2364 sub url_path {
2365 my ($self, $path) = @_;
2366 $self->{url} . '/' . $self->repo_path($path);
2369 sub rmdirs {
2370 my ($self) = @_;
2371 my $rm = $self->{rm};
2372 delete $rm->{''}; # we never delete the url we're tracking
2373 return unless %$rm;
2375 foreach (keys %$rm) {
2376 my @d = split m#/#, $_;
2377 my $c = shift @d;
2378 $rm->{$c} = 1;
2379 while (@d) {
2380 $c .= '/' . shift @d;
2381 $rm->{$c} = 1;
2384 delete $rm->{$self->{svn_path}};
2385 delete $rm->{''}; # we never delete the url we're tracking
2386 return unless %$rm;
2388 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2389 $self->{tree_b});
2390 local $/ = "\0";
2391 while (<$fh>) {
2392 chomp;
2393 my @dn = split m#/#, $_;
2394 while (pop @dn) {
2395 delete $rm->{join '/', @dn};
2397 unless (%$rm) {
2398 close $fh;
2399 return;
2402 command_close_pipe($fh, $ctx);
2404 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2405 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2406 $self->close_directory($bat->{$d}, $p);
2407 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2408 print "\tD+\t$d/\n" unless $::_q;
2409 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2410 delete $bat->{$d};
2414 sub open_or_add_dir {
2415 my ($self, $full_path, $baton) = @_;
2416 my $t = $self->{types}->{$full_path};
2417 if (!defined $t) {
2418 die "$full_path not known in r$self->{r} or we have a bug!\n";
2420 if ($t == $SVN::Node::none) {
2421 return $self->add_directory($full_path, $baton,
2422 undef, -1, $self->{pool});
2423 } elsif ($t == $SVN::Node::dir) {
2424 return $self->open_directory($full_path, $baton,
2425 $self->{r}, $self->{pool});
2427 print STDERR "$full_path already exists in repository at ",
2428 "r$self->{r} and it is not a directory (",
2429 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2430 exit 1;
2433 sub ensure_path {
2434 my ($self, $path) = @_;
2435 my $bat = $self->{bat};
2436 my $repo_path = $self->repo_path($path);
2437 return $bat->{''} unless (length $repo_path);
2438 my @p = split m#/+#, $repo_path;
2439 my $c = shift @p;
2440 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2441 while (@p) {
2442 my $c0 = $c;
2443 $c .= '/' . shift @p;
2444 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2446 return $bat->{$c};
2449 sub A {
2450 my ($self, $m) = @_;
2451 my ($dir, $file) = split_path($m->{file_b});
2452 my $pbat = $self->ensure_path($dir);
2453 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2454 undef, -1);
2455 print "\tA\t$m->{file_b}\n" unless $::_q;
2456 $self->chg_file($fbat, $m);
2457 $self->close_file($fbat,undef,$self->{pool});
2460 sub C {
2461 my ($self, $m) = @_;
2462 my ($dir, $file) = split_path($m->{file_b});
2463 my $pbat = $self->ensure_path($dir);
2464 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2465 $self->url_path($m->{file_a}), $self->{r});
2466 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2467 $self->chg_file($fbat, $m);
2468 $self->close_file($fbat,undef,$self->{pool});
2471 sub delete_entry {
2472 my ($self, $path, $pbat) = @_;
2473 my $rpath = $self->repo_path($path);
2474 my ($dir, $file) = split_path($rpath);
2475 $self->{rm}->{$dir} = 1;
2476 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2479 sub R {
2480 my ($self, $m) = @_;
2481 my ($dir, $file) = split_path($m->{file_b});
2482 my $pbat = $self->ensure_path($dir);
2483 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2484 $self->url_path($m->{file_a}), $self->{r});
2485 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2486 $self->chg_file($fbat, $m);
2487 $self->close_file($fbat,undef,$self->{pool});
2489 ($dir, $file) = split_path($m->{file_a});
2490 $pbat = $self->ensure_path($dir);
2491 $self->delete_entry($m->{file_a}, $pbat);
2494 sub M {
2495 my ($self, $m) = @_;
2496 my ($dir, $file) = split_path($m->{file_b});
2497 my $pbat = $self->ensure_path($dir);
2498 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2499 $pbat,$self->{r},$self->{pool});
2500 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2501 $self->chg_file($fbat, $m);
2502 $self->close_file($fbat,undef,$self->{pool});
2505 sub T { shift->M(@_) }
2507 sub change_file_prop {
2508 my ($self, $fbat, $pname, $pval) = @_;
2509 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2512 sub chg_file {
2513 my ($self, $fbat, $m) = @_;
2514 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2515 $self->change_file_prop($fbat,'svn:executable','*');
2516 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2517 $self->change_file_prop($fbat,'svn:executable',undef);
2519 my $fh = IO::File->new_tmpfile or croak $!;
2520 if ($m->{mode_b} =~ /^120/) {
2521 print $fh 'link ' or croak $!;
2522 $self->change_file_prop($fbat,'svn:special','*');
2523 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2524 $self->change_file_prop($fbat,'svn:special',undef);
2526 defined(my $pid = fork) or croak $!;
2527 if (!$pid) {
2528 open STDOUT, '>&', $fh or croak $!;
2529 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2531 waitpid $pid, 0;
2532 croak $? if $?;
2533 $fh->flush == 0 or croak $!;
2534 seek $fh, 0, 0 or croak $!;
2536 my $md5 = Digest::MD5->new;
2537 $md5->addfile($fh) or croak $!;
2538 seek $fh, 0, 0 or croak $!;
2540 my $exp = $md5->hexdigest;
2541 my $pool = SVN::Pool->new;
2542 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2543 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2544 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2545 $pool->clear;
2547 close $fh or croak $!;
2550 sub D {
2551 my ($self, $m) = @_;
2552 my ($dir, $file) = split_path($m->{file_b});
2553 my $pbat = $self->ensure_path($dir);
2554 print "\tD\t$m->{file_b}\n" unless $::_q;
2555 $self->delete_entry($m->{file_b}, $pbat);
2558 sub close_edit {
2559 my ($self) = @_;
2560 my ($p,$bat) = ($self->{pool}, $self->{bat});
2561 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2562 $self->close_directory($bat->{$_}, $p);
2564 $self->SUPER::close_edit($p);
2565 $p->clear;
2568 sub abort_edit {
2569 my ($self) = @_;
2570 $self->SUPER::abort_edit($self->{pool});
2573 sub DESTROY {
2574 my $self = shift;
2575 $self->SUPER::DESTROY(@_);
2576 $self->{pool}->clear;
2579 # this drives the editor
2580 sub apply_diff {
2581 my ($self) = @_;
2582 my $mods = $self->{mods};
2583 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2584 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2585 my $f = $m->{chg};
2586 if (defined $o{$f}) {
2587 $self->$f($m);
2588 } else {
2589 fatal("Invalid change type: $f\n");
2592 $self->rmdirs if $_rmdir;
2593 if (@$mods == 0) {
2594 $self->abort_edit;
2595 } else {
2596 $self->close_edit;
2598 return scalar @$mods;
2601 package Git::SVN::Ra;
2602 use vars qw/@ISA $config_dir/;
2603 use strict;
2604 use warnings;
2605 my ($can_do_switch);
2606 my $RA;
2608 BEGIN {
2609 # enforce temporary pool usage for some simple functions
2610 my $e;
2611 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2612 $e .= "sub $_ {
2613 my \$self = shift;
2614 my \$pool = SVN::Pool->new;
2615 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2616 \$pool->clear;
2617 wantarray ? \@ret : \$ret[0]; }\n";
2620 # get_dir needs $pool held in cache for dirents to work,
2621 # check_path is cacheable and rev_proplist is close enough
2622 # for our purposes.
2623 foreach (qw/check_path get_dir rev_proplist/) {
2624 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2625 my \$self = shift;
2626 my \$r = pop;
2627 my \$k = join(\"\\0\", \@_);
2628 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2629 return wantarray ? \@\$x : \$x->[0];
2631 my \$pool = SVN::Pool->new;
2632 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2633 if (\$r != \$${_}_rev) {
2634 \%${_}_cache = ( pool => [] );
2635 \$${_}_rev = \$r;
2637 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2638 push \@{\$${_}_cache{pool}}, \$pool;
2639 wantarray ? \@ret : \$ret[0]; }\n";
2641 $e .= "\n1;";
2642 eval $e or die $@;
2645 sub new {
2646 my ($class, $url) = @_;
2647 $url =~ s!/+$!!;
2648 return $RA if ($RA && $RA->{url} eq $url);
2650 SVN::_Core::svn_config_ensure($config_dir, undef);
2651 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2652 SVN::Client::get_simple_provider(),
2653 SVN::Client::get_ssl_server_trust_file_provider(),
2654 SVN::Client::get_simple_prompt_provider(
2655 \&Git::SVN::Prompt::simple, 2),
2656 SVN::Client::get_ssl_client_cert_prompt_provider(
2657 \&Git::SVN::Prompt::ssl_client_cert, 2),
2658 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2659 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2660 SVN::Client::get_username_provider(),
2661 SVN::Client::get_ssl_server_trust_prompt_provider(
2662 \&Git::SVN::Prompt::ssl_server_trust),
2663 SVN::Client::get_username_prompt_provider(
2664 \&Git::SVN::Prompt::username, 2),
2666 my $config = SVN::Core::config_get_config($config_dir);
2667 my $self = SVN::Ra->new(url => $url, auth => $baton,
2668 config => $config,
2669 pool => SVN::Pool->new,
2670 auth_provider_callbacks => $callbacks);
2671 $self->{svn_path} = $url;
2672 $self->{repos_root} = $self->get_repos_root;
2673 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2674 $RA = bless $self, $class;
2677 sub DESTROY {
2678 # do not call the real DESTROY since we store ourselves in $RA
2681 sub get_log {
2682 my ($self, @args) = @_;
2683 my $pool = SVN::Pool->new;
2684 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2685 my $ret = $self->SUPER::get_log(@args, $pool);
2686 $pool->clear;
2687 $ret;
2690 sub get_commit_editor {
2691 my ($self, $log, $cb, $pool) = @_;
2692 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2693 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2696 sub gs_do_update {
2697 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2698 my $new = ($rev_a == $rev_b);
2699 my $path = $gs->{path};
2701 my $pool = SVN::Pool->new;
2702 $editor->set_path_strip($path);
2703 my (@pc) = split m#/#, $path;
2704 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2705 1, $editor, $pool);
2706 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2708 # Since we can't rely on svn_ra_reparent being available, we'll
2709 # just have to do some magic with set_path to make it so
2710 # we only want a partial path.
2711 my $sp = '';
2712 my $final = join('/', @pc);
2713 while (@pc) {
2714 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2715 $sp .= '/' if length $sp;
2716 $sp .= shift @pc;
2718 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2720 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2722 $reporter->finish_report($pool);
2723 $pool->clear;
2724 $editor->{git_commit_ok};
2727 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2728 # svn_ra_reparent didn't work before 1.4)
2729 sub gs_do_switch {
2730 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2731 my $path = $gs->{path};
2732 my $pool = SVN::Pool->new;
2734 my $full_url = $self->{url};
2735 my $old_url = $full_url;
2736 $full_url .= "/$path" if length $path;
2737 my ($ra, $reparented);
2738 if ($old_url ne $full_url) {
2739 if ($old_url !~ m#^svn(\+ssh)?://#) {
2740 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2741 $pool);
2742 $self->{url} = $full_url;
2743 $reparented = 1;
2744 } else {
2745 $ra = Git::SVN::Ra->new($full_url);
2748 $ra ||= $self;
2749 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2750 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2751 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2752 $reporter->finish_report($pool);
2754 if ($reparented) {
2755 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2756 $self->{url} = $old_url;
2759 $pool->clear;
2760 $editor->{git_commit_ok};
2763 sub gs_fetch_loop_common {
2764 my ($self, $base, $head, $gsv, $globs) = @_;
2765 return if ($base > $head);
2766 my $inc = 1000;
2767 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2768 my %common;
2769 my $common_max = scalar @$gsv;
2771 foreach my $gs (@$gsv) {
2772 if (my $last_commit = $gs->last_commit) {
2773 $gs->assert_index_clean($last_commit);
2775 my @tmp = split m#/#, $gs->{path};
2776 my $p = '';
2777 foreach (@tmp) {
2778 $p .= length($p) ? "/$_" : $_;
2779 $common{$p} ||= 0;
2780 $common{$p}++;
2783 $globs ||= [];
2784 $common_max += scalar @$globs;
2785 foreach my $glob (@$globs) {
2786 my @tmp = split m#/#, $glob->{path}->{left};
2787 my $p = '';
2788 foreach (@tmp) {
2789 $p .= length($p) ? "/$_" : $_;
2790 $common{$p} ||= 0;
2791 $common{$p}++;
2795 my $longest_path = '';
2796 foreach (sort {length $b <=> length $a} keys %common) {
2797 if ($common{$_} == $common_max) {
2798 $longest_path = $_;
2799 last;
2802 while (1) {
2803 my %revs;
2804 my $err;
2805 my $err_handler = $SVN::Error::handler;
2806 $SVN::Error::handler = sub {
2807 ($err) = @_;
2808 skip_unknown_revs($err);
2810 sub _cb {
2811 my ($paths, $r, $author, $date, $log) = @_;
2812 [ dup_changed_paths($paths),
2813 { author => $author, date => $date, log => $log } ];
2815 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2816 sub { $revs{$_[1]} = _cb(@_) });
2817 if ($err && $max >= $head) {
2818 print STDERR "Path '$longest_path' ",
2819 "was probably deleted:\n",
2820 $err->expanded_message,
2821 "\nWill attempt to follow ",
2822 "revisions r$min .. r$max ",
2823 "committed before the deletion\n";
2824 my $hi = $max;
2825 while (--$hi >= $min) {
2826 my $ok;
2827 $self->get_log([$longest_path], $min, $hi,
2828 0, 1, 1, sub {
2829 $ok ||= $_[1];
2830 $revs{$_[1]} = _cb(@_) });
2831 if ($ok) {
2832 print STDERR "r$min .. r$ok OK\n";
2833 last;
2837 $SVN::Error::handler = $err_handler;
2839 my %exists = map { $_->{path} => $_ } @$gsv;
2840 foreach my $r (sort {$a <=> $b} keys %revs) {
2841 my ($paths, $logged) = @{$revs{$r}};
2843 foreach my $gs ($self->match_globs(\%exists, $paths,
2844 $globs, $r)) {
2845 if ($gs->rev_db_max >= $r) {
2846 next;
2848 next unless $gs->match_paths($paths, $r);
2849 $gs->{logged_rev_props} = $logged;
2850 my $log_entry = $gs->do_fetch($paths, $r);
2851 if ($log_entry) {
2852 $gs->do_git_commit($log_entry);
2855 foreach my $g (@$globs) {
2856 my $k = "svn-remote.$g->{remote}." .
2857 "$g->{t}-maxRev";
2858 Git::SVN::tmp_config($k, $r);
2861 # pre-fill the .rev_db since it'll eventually get filled in
2862 # with '0' x40 if something new gets committed
2863 foreach my $gs (@$gsv) {
2864 next if defined $gs->rev_db_get($max);
2865 $gs->rev_db_set($max, 0 x40);
2867 foreach my $g (@$globs) {
2868 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
2869 Git::SVN::tmp_config($k, $max);
2871 last if $max >= $head;
2872 $min = $max + 1;
2873 $max += $inc;
2874 $max = $head if ($max > $head);
2878 sub match_globs {
2879 my ($self, $exists, $paths, $globs, $r) = @_;
2881 sub get_dir_check {
2882 my ($self, $exists, $g, $r) = @_;
2883 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2884 return unless scalar @x == 3;
2885 my $dirents = $x[0];
2886 foreach my $de (keys %$dirents) {
2887 next if $dirents->{$de}->kind != $SVN::Node::dir;
2888 my $p = $g->{path}->full_path($de);
2889 next if $exists->{$p};
2890 next if (length $g->{path}->{right} &&
2891 ($self->check_path($p, $r) !=
2892 $SVN::Node::dir));
2893 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
2894 $g->{ref}->full_path($de), 1);
2897 foreach my $g (@$globs) {
2898 if (my $path = $paths->{"/$g->{path}->{left}"}) {
2899 if ($path->{action} =~ /^[AR]$/) {
2900 get_dir_check($self, $exists, $g, $r);
2903 foreach (keys %$paths) {
2904 if (/$g->{path}->{left_regex}/ &&
2905 !/$g->{path}->{regex}/) {
2906 next if $paths->{$_}->{action} !~ /^[AR]$/;
2907 get_dir_check($self, $exists, $g, $r);
2909 next unless /$g->{path}->{regex}/;
2910 my $p = $1;
2911 my $pathname = $g->{path}->full_path($p);
2912 next if $exists->{$pathname};
2913 $exists->{$pathname} = Git::SVN->init(
2914 $self->{url}, $pathname, undef,
2915 $g->{ref}->full_path($p), 1);
2917 my $c = '';
2918 foreach (split m#/#, $g->{path}->{left}) {
2919 $c .= "/$_";
2920 next unless ($paths->{$c} &&
2921 ($paths->{$c}->{action} =~ /^[AR]$/));
2922 get_dir_check($self, $exists, $g, $r);
2925 values %$exists;
2928 sub minimize_url {
2929 my ($self) = @_;
2930 return $self->{url} if ($self->{url} eq $self->{repos_root});
2931 my $url = $self->{repos_root};
2932 my @components = split(m!/!, $self->{svn_path});
2933 my $c = '';
2934 do {
2935 $url .= "/$c" if length $c;
2936 eval { (ref $self)->new($url)->get_latest_revnum };
2937 } while ($@ && ($c = shift @components));
2938 $url;
2941 sub can_do_switch {
2942 my $self = shift;
2943 unless (defined $can_do_switch) {
2944 my $pool = SVN::Pool->new;
2945 my $rep = eval {
2946 $self->do_switch(1, '', 0, $self->{url},
2947 SVN::Delta::Editor->new, $pool);
2949 if ($@) {
2950 $can_do_switch = 0;
2951 } else {
2952 $rep->abort_report($pool);
2953 $can_do_switch = 1;
2955 $pool->clear;
2957 $can_do_switch;
2960 sub skip_unknown_revs {
2961 my ($err) = @_;
2962 my $errno = $err->apr_err();
2963 # Maybe the branch we're tracking didn't
2964 # exist when the repo started, so it's
2965 # not an error if it doesn't, just continue
2967 # Wonderfully consistent library, eh?
2968 # 160013 - svn:// and file://
2969 # 175002 - http(s)://
2970 # 175007 - http(s):// (this repo required authorization, too...)
2971 # More codes may be discovered later...
2972 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2973 return;
2975 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2978 # svn_log_changed_path_t objects passed to get_log are likely to be
2979 # overwritten even if only the refs are copied to an external variable,
2980 # so we should dup the structures in their entirety. Using an externally
2981 # passed pool (instead of our temporary and quickly cleared pool in
2982 # Git::SVN::Ra) does not help matters at all...
2983 sub dup_changed_paths {
2984 my ($paths) = @_;
2985 return undef unless $paths;
2986 my %ret;
2987 foreach my $p (keys %$paths) {
2988 my $i = $paths->{$p};
2989 my %s = map { $_ => $i->$_ }
2990 qw/copyfrom_path copyfrom_rev action/;
2991 $ret{$p} = \%s;
2993 \%ret;
2996 package Git::SVN::Log;
2997 use strict;
2998 use warnings;
2999 use POSIX qw/strftime/;
3000 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3001 %rusers $show_commit $incremental/;
3002 my $l_fmt;
3004 sub cmt_showable {
3005 my ($c) = @_;
3006 return 1 if defined $c->{r};
3007 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3008 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3009 my @log = command(qw/cat-file commit/, $c->{c});
3010 shift @log while ($log[0] ne "\n");
3011 shift @log;
3012 @{$c->{l}} = grep !/^git-svn-id: /, @log;
3014 (undef, $c->{r}, undef) = ::extract_metadata(
3015 (grep(/^git-svn-id: /, @log))[-1]);
3017 return defined $c->{r};
3020 sub log_use_color {
3021 return 1 if $color;
3022 my ($dc, $dcvar);
3023 $dcvar = 'color.diff';
3024 $dc = `git-config --get $dcvar`;
3025 if ($dc eq '') {
3026 # nothing at all; fallback to "diff.color"
3027 $dcvar = 'diff.color';
3028 $dc = `git-config --get $dcvar`;
3030 chomp($dc);
3031 if ($dc eq 'auto') {
3032 my $pc;
3033 $pc = `git-config --get color.pager`;
3034 if ($pc eq '') {
3035 # does not have it -- fallback to pager.color
3036 $pc = `git-config --bool --get pager.color`;
3038 else {
3039 $pc = `git-config --bool --get color.pager`;
3040 if ($?) {
3041 $pc = 'false';
3044 chomp($pc);
3045 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3046 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3048 return 0;
3050 return 0 if $dc eq 'never';
3051 return 1 if $dc eq 'always';
3052 chomp($dc = `git-config --bool --get $dcvar`);
3053 return ($dc eq 'true');
3056 sub git_svn_log_cmd {
3057 my ($r_min, $r_max, @args) = @_;
3058 my $head = 'HEAD';
3059 foreach my $x (@args) {
3060 last if $x eq '--';
3061 next unless ::verify_ref("$x^0");
3062 $head = $x;
3063 last;
3066 my $url;
3067 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
3068 while (<$fh>) {
3069 chomp;
3070 $url = (::cmt_metadata($_))[0];
3071 last if defined $url;
3073 close $fh; # break the pipe
3075 my $gs = Git::SVN->find_by_url($url) || Git::SVN->_new;
3076 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3077 $gs->refname);
3078 push @cmd, '-r' unless $non_recursive;
3079 push @cmd, qw/--raw --name-status/ if $verbose;
3080 push @cmd, '--color' if log_use_color();
3081 return @cmd unless defined $r_max;
3082 if ($r_max == $r_min) {
3083 push @cmd, '--max-count=1';
3084 if (my $c = $gs->rev_db_get($r_max)) {
3085 push @cmd, $c;
3087 } else {
3088 my ($c_min, $c_max);
3089 $c_max = $gs->rev_db_get($r_max);
3090 $c_min = $gs->rev_db_get($r_min);
3091 if (defined $c_min && defined $c_max) {
3092 if ($r_max > $r_max) {
3093 push @cmd, "$c_min..$c_max";
3094 } else {
3095 push @cmd, "$c_max..$c_min";
3097 } elsif ($r_max > $r_min) {
3098 push @cmd, $c_max;
3099 } else {
3100 push @cmd, $c_min;
3103 return @cmd;
3106 # adapted from pager.c
3107 sub config_pager {
3108 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3109 if (!defined $pager) {
3110 $pager = 'less';
3111 } elsif (length $pager == 0 || $pager eq 'cat') {
3112 $pager = undef;
3116 sub run_pager {
3117 return unless -t *STDOUT;
3118 pipe my $rfd, my $wfd or return;
3119 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3120 if (!$pid) {
3121 open STDOUT, '>&', $wfd or
3122 ::fatal "Can't redirect to stdout: $!\n";
3123 return;
3125 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3126 $ENV{LESS} ||= 'FRSX';
3127 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3130 sub tz_to_s_offset {
3131 my ($tz) = @_;
3132 $tz =~ s/(\d\d)$//;
3133 return ($1 * 60) + ($tz * 3600);
3136 sub get_author_info {
3137 my ($dest, $author, $t, $tz) = @_;
3138 $author =~ s/(?:^\s*|\s*$)//g;
3139 $dest->{a_raw} = $author;
3140 my $au;
3141 if ($::_authors) {
3142 $au = $rusers{$author} || undef;
3144 if (!$au) {
3145 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3147 $dest->{t} = $t;
3148 $dest->{tz} = $tz;
3149 $dest->{a} = $au;
3150 # Date::Parse isn't in the standard Perl distro :(
3151 if ($tz =~ s/^\+//) {
3152 $t += tz_to_s_offset($tz);
3153 } elsif ($tz =~ s/^\-//) {
3154 $t -= tz_to_s_offset($tz);
3156 $dest->{t_utc} = $t;
3159 sub process_commit {
3160 my ($c, $r_min, $r_max, $defer) = @_;
3161 if (defined $r_min && defined $r_max) {
3162 if ($r_min == $c->{r} && $r_min == $r_max) {
3163 show_commit($c);
3164 return 0;
3166 return 1 if $r_min == $r_max;
3167 if ($r_min < $r_max) {
3168 # we need to reverse the print order
3169 return 0 if (defined $limit && --$limit < 0);
3170 push @$defer, $c;
3171 return 1;
3173 if ($r_min != $r_max) {
3174 return 1 if ($r_min < $c->{r});
3175 return 1 if ($r_max > $c->{r});
3178 return 0 if (defined $limit && --$limit < 0);
3179 show_commit($c);
3180 return 1;
3183 sub show_commit {
3184 my $c = shift;
3185 if ($oneline) {
3186 my $x = "\n";
3187 if (my $l = $c->{l}) {
3188 while ($l->[0] =~ /^\s*$/) { shift @$l }
3189 $x = $l->[0];
3191 $l_fmt ||= 'A' . length($c->{r});
3192 print 'r',pack($l_fmt, $c->{r}),' | ';
3193 print "$c->{c} | " if $show_commit;
3194 print $x;
3195 } else {
3196 show_commit_normal($c);
3200 sub show_commit_changed_paths {
3201 my ($c) = @_;
3202 return unless $c->{changed};
3203 print "Changed paths:\n", @{$c->{changed}};
3206 sub show_commit_normal {
3207 my ($c) = @_;
3208 print '-' x72, "\nr$c->{r} | ";
3209 print "$c->{c} | " if $show_commit;
3210 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3211 localtime($c->{t_utc})), ' | ';
3212 my $nr_line = 0;
3214 if (my $l = $c->{l}) {
3215 while ($l->[$#$l] eq "\n" && $#$l > 0
3216 && $l->[($#$l - 1)] eq "\n") {
3217 pop @$l;
3219 $nr_line = scalar @$l;
3220 if (!$nr_line) {
3221 print "1 line\n\n\n";
3222 } else {
3223 if ($nr_line == 1) {
3224 $nr_line = '1 line';
3225 } else {
3226 $nr_line .= ' lines';
3228 print $nr_line, "\n";
3229 show_commit_changed_paths($c);
3230 print "\n";
3231 print $_ foreach @$l;
3233 } else {
3234 print "1 line\n";
3235 show_commit_changed_paths($c);
3236 print "\n";
3239 foreach my $x (qw/raw diff/) {
3240 if ($c->{$x}) {
3241 print "\n";
3242 print $_ foreach @{$c->{$x}}
3247 sub cmd_show_log {
3248 my (@args) = @_;
3249 my ($r_min, $r_max);
3250 my $r_last = -1; # prevent dupes
3251 if (defined $TZ) {
3252 $ENV{TZ} = $TZ;
3253 } else {
3254 delete $ENV{TZ};
3256 if (defined $::_revision) {
3257 if ($::_revision =~ /^(\d+):(\d+)$/) {
3258 ($r_min, $r_max) = ($1, $2);
3259 } elsif ($::_revision =~ /^\d+$/) {
3260 $r_min = $r_max = $::_revision;
3261 } else {
3262 ::fatal "-r$::_revision is not supported, use ",
3263 "standard \'git log\' arguments instead\n";
3267 config_pager();
3268 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3269 my $log = command_output_pipe(@args);
3270 run_pager();
3271 my (@k, $c, $d);
3272 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3273 while (<$log>) {
3274 if (/^${esc_color}commit ($::sha1_short)/o) {
3275 my $cmt = $1;
3276 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3277 $r_last = $c->{r};
3278 process_commit($c, $r_min, $r_max, \@k) or
3279 goto out;
3281 $d = undef;
3282 $c = { c => $cmt };
3283 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3284 get_author_info($c, $1, $2, $3);
3285 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3286 # ignore
3287 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3288 push @{$c->{raw}}, $_;
3289 } elsif (/^${esc_color}[ACRMDT]\t/) {
3290 # we could add $SVN->{svn_path} here, but that requires
3291 # remote access at the moment (repo_path_split)...
3292 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3293 push @{$c->{changed}}, $_;
3294 } elsif (/^${esc_color}diff /o) {
3295 $d = 1;
3296 push @{$c->{diff}}, $_;
3297 } elsif ($d) {
3298 push @{$c->{diff}}, $_;
3299 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3300 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3301 } elsif (s/^${esc_color} //o) {
3302 push @{$c->{l}}, $_;
3305 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3306 $r_last = $c->{r};
3307 process_commit($c, $r_min, $r_max, \@k);
3309 if (@k) {
3310 my $swap = $r_max;
3311 $r_max = $r_min;
3312 $r_min = $swap;
3313 process_commit($_, $r_min, $r_max) foreach reverse @k;
3315 out:
3316 close $log;
3317 print '-' x72,"\n" unless $incremental || $oneline;
3320 package Git::SVN::Migration;
3321 # these version numbers do NOT correspond to actual version numbers
3322 # of git nor git-svn. They are just relative.
3324 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3326 # v1 layout: .git/$id/info/url, refs/remotes/$id
3328 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3330 # v3 layout: .git/svn/$id, refs/remotes/$id
3331 # - info/url may remain for backwards compatibility
3332 # - this is what we migrate up to this layout automatically,
3333 # - this will be used by git svn init on single branches
3334 # v3.1 layout (auto migrated):
3335 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3336 # for backwards compatibility
3338 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3339 # - this is only created for newly multi-init-ed
3340 # repositories. Similar in spirit to the
3341 # --use-separate-remotes option in git-clone (now default)
3342 # - we do not automatically migrate to this (following
3343 # the example set by core git)
3344 use strict;
3345 use warnings;
3346 use Carp qw/croak/;
3347 use File::Path qw/mkpath/;
3348 use File::Basename qw/dirname basename/;
3349 use vars qw/$_minimize/;
3351 sub migrate_from_v0 {
3352 my $git_dir = $ENV{GIT_DIR};
3353 return undef unless -d $git_dir;
3354 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3355 my $migrated = 0;
3356 while (<$fh>) {
3357 chomp;
3358 my ($id, $orig_ref) = ($_, $_);
3359 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3360 next unless -f "$git_dir/$id/info/url";
3361 my $new_ref = "refs/remotes/$id";
3362 if (::verify_ref("$new_ref^0")) {
3363 print STDERR "W: $orig_ref is probably an old ",
3364 "branch used by an ancient version of ",
3365 "git-svn.\n",
3366 "However, $new_ref also exists.\n",
3367 "We will not be able ",
3368 "to use this branch until this ",
3369 "ambiguity is resolved.\n";
3370 next;
3372 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3373 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3374 command_noisy('update-ref', $new_ref, $orig_ref);
3375 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3376 $migrated++;
3378 command_close_pipe($fh, $ctx);
3379 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3380 $migrated;
3383 sub migrate_from_v1 {
3384 my $git_dir = $ENV{GIT_DIR};
3385 my $migrated = 0;
3386 return $migrated unless -d $git_dir;
3387 my $svn_dir = "$git_dir/svn";
3389 # just in case somebody used 'svn' as their $id at some point...
3390 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3392 print STDERR "Migrating from a git-svn v1 layout...\n";
3393 mkpath([$svn_dir]);
3394 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3395 "$svn_dir\n\t(required for this version ",
3396 "($::VERSION) of git-svn) does not. exist\n";
3397 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3398 while (<$fh>) {
3399 my $x = $_;
3400 next unless $x =~ s#^refs/remotes/##;
3401 chomp $x;
3402 next unless -f "$git_dir/$x/info/url";
3403 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3404 next unless $u;
3405 my $dn = dirname("$git_dir/svn/$x");
3406 mkpath([$dn]) unless -d $dn;
3407 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3408 mkpath(["$git_dir/svn/svn"]);
3409 print STDERR " - $git_dir/$x/info => ",
3410 "$git_dir/svn/$x/info\n";
3411 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3412 croak "$!: $x";
3413 # don't worry too much about these, they probably
3414 # don't exist with repos this old (save for index,
3415 # and we can easily regenerate that)
3416 foreach my $f (qw/unhandled.log index .rev_db/) {
3417 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3419 } else {
3420 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3421 rename "$git_dir/$x", "$git_dir/svn/$x" or
3422 croak "$!: $x";
3424 $migrated++;
3426 command_close_pipe($fh, $ctx);
3427 print STDERR "Done migrating from a git-svn v1 layout\n";
3428 $migrated;
3431 sub read_old_urls {
3432 my ($l_map, $pfx, $path) = @_;
3433 my @dir;
3434 foreach (<$path/*>) {
3435 if (-r "$_/info/url") {
3436 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3437 my $ref_id = $pfx . basename $_;
3438 my $url = ::file_to_s("$_/info/url");
3439 $l_map->{$ref_id} = $url;
3440 } elsif (-d $_) {
3441 push @dir, $_;
3444 foreach (@dir) {
3445 my $x = $_;
3446 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3447 read_old_urls($l_map, $x, $_);
3451 sub migrate_from_v2 {
3452 my @cfg = command(qw/config -l/);
3453 return if grep /^svn-remote\..+\.url=/, @cfg;
3454 my %l_map;
3455 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3456 my $migrated = 0;
3458 foreach my $ref_id (sort keys %l_map) {
3459 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3460 if ($@) {
3461 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3463 $migrated++;
3465 $migrated;
3468 sub minimize_connections {
3469 my $r = Git::SVN::read_all_remotes();
3470 my $new_urls = {};
3471 my $root_repos = {};
3472 foreach my $repo_id (keys %$r) {
3473 my $url = $r->{$repo_id}->{url} or next;
3474 my $fetch = $r->{$repo_id}->{fetch} or next;
3475 my $ra = Git::SVN::Ra->new($url);
3477 # skip existing cases where we already connect to the root
3478 if (($ra->{url} eq $ra->{repos_root}) ||
3479 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3480 $repo_id)) {
3481 $root_repos->{$ra->{url}} = $repo_id;
3482 next;
3485 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3486 my $root_path = $ra->{url};
3487 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3488 foreach my $path (keys %$fetch) {
3489 my $ref_id = $fetch->{$path};
3490 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3492 # make sure we can read when connecting to
3493 # a higher level of a repository
3494 my ($last_rev, undef) = $gs->last_rev_commit;
3495 if (!defined $last_rev) {
3496 $last_rev = eval {
3497 $root_ra->get_latest_revnum;
3499 next if $@;
3501 my $new = $root_path;
3502 $new .= length $path ? "/$path" : '';
3503 eval {
3504 $root_ra->get_log([$new], $last_rev, $last_rev,
3505 0, 0, 1, sub { });
3507 next if $@;
3508 $new_urls->{$ra->{repos_root}}->{$new} =
3509 { ref_id => $ref_id,
3510 old_repo_id => $repo_id,
3511 old_path => $path };
3515 my @emptied;
3516 foreach my $url (keys %$new_urls) {
3517 # see if we can re-use an existing [svn-remote "repo_id"]
3518 # instead of creating a(n ugly) new section:
3519 my $repo_id = $root_repos->{$url} ||
3520 Git::SVN::sanitize_remote_name($url);
3522 my $fetch = $new_urls->{$url};
3523 foreach my $path (keys %$fetch) {
3524 my $x = $fetch->{$path};
3525 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3526 my $pfx = "svn-remote.$x->{old_repo_id}";
3528 my $old_fetch = quotemeta("$x->{old_path}:".
3529 "refs/remotes/$x->{ref_id}");
3530 command_noisy(qw/config --unset/,
3531 "$pfx.fetch", '^'. $old_fetch . '$');
3532 delete $r->{$x->{old_repo_id}}->
3533 {fetch}->{$x->{old_path}};
3534 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3535 command_noisy(qw/config --unset/,
3536 "$pfx.url");
3537 push @emptied, $x->{old_repo_id}
3541 if (@emptied) {
3542 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3543 "$ENV{GIT_DIR}/config";
3544 print STDERR <<EOF;
3545 The following [svn-remote] sections in your config file ($file) are empty
3546 and can be safely removed:
3548 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3552 sub migration_check {
3553 migrate_from_v0();
3554 migrate_from_v1();
3555 migrate_from_v2();
3556 minimize_connections() if $_minimize;
3559 package Git::IndexInfo;
3560 use strict;
3561 use warnings;
3562 use Git qw/command_input_pipe command_close_pipe/;
3564 sub new {
3565 my ($class) = @_;
3566 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3567 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3570 sub remove {
3571 my ($self, $path) = @_;
3572 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3573 return ++$self->{nr};
3575 undef;
3578 sub update {
3579 my ($self, $mode, $hash, $path) = @_;
3580 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3581 return ++$self->{nr};
3583 undef;
3586 sub DESTROY {
3587 my ($self) = @_;
3588 command_close_pipe($self->{gui}, $self->{ctx});
3591 package Git::SVN::GlobSpec;
3592 use strict;
3593 use warnings;
3595 sub new {
3596 my ($class, $glob) = @_;
3597 my $re = $glob;
3598 $re =~ s!/+$!!g; # no need for trailing slashes
3599 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3600 my ($left, $right) = ($1, $2);
3601 if ($nr > 1) {
3602 die "Only one '*' wildcard expansion ",
3603 "is supported (got $nr): '$glob'\n";
3604 } elsif ($nr == 0) {
3605 die "One '*' is needed for glob: '$glob'\n";
3607 $re = quotemeta($left) . $re . quotemeta($right);
3608 if (length $left && !($left =~ s!/+$!!g)) {
3609 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3611 if (length $right && !($right =~ s!^/+!!g)) {
3612 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3614 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3615 bless { left => $left, right => $right, left_regex => $left_re,
3616 regex => qr/$re/, glob => $glob }, $class;
3619 sub full_path {
3620 my ($self, $path) = @_;
3621 return (length $self->{left} ? "$self->{left}/" : '') .
3622 $path . (length $self->{right} ? "/$self->{right}" : '');
3625 __END__
3627 Data structures:
3630 $remotes = { # returned by read_all_remotes()
3631 'svn' => {
3632 # svn-remote.svn.url=https://svn.musicpd.org
3633 url => 'https://svn.musicpd.org',
3634 # svn-remote.svn.fetch=mpd/trunk:trunk
3635 fetch => {
3636 'mpd/trunk' => 'trunk',
3638 # svn-remote.svn.tags=mpd/tags/*:tags/*
3639 tags => {
3640 path => {
3641 left => 'mpd/tags',
3642 right => '',
3643 regex => qr!mpd/tags/([^/]+)$!,
3644 glob => 'tags/*',
3646 ref => {
3647 left => 'tags',
3648 right => '',
3649 regex => qr!tags/([^/]+)$!,
3650 glob => 'tags/*',
3656 $log_entry hashref as returned by libsvn_log_entry()
3658 log => 'whitespace-formatted log entry
3659 ', # trailing newline is preserved
3660 revision => '8', # integer
3661 date => '2004-02-24T17:01:44.108345Z', # commit date
3662 author => 'committer name'
3666 # this is generated by generate_diff();
3667 @mods = array of diff-index line hashes, each element represents one line
3668 of diff-index output
3670 diff-index line ($m hash)
3672 mode_a => first column of diff-index output, no leading ':',
3673 mode_b => second column of diff-index output,
3674 sha1_b => sha1sum of the final blob,
3675 chg => change type [MCRADT],
3676 file_a => original file name of a file (iff chg is 'C' or 'R')
3677 file_b => new/current file name of a file (any chg)
3681 # retval of read_url_paths{,_all}();
3682 $l_map = {
3683 # repository root url
3684 'https://svn.musicpd.org' => {
3685 # repository path # GIT_SVN_ID
3686 'mpd/trunk' => 'trunk',
3687 'mpd/tags/0.11.5' => 'tags/0.11.5',
3691 Notes:
3692 I don't trust the each() function on unless I created %hash myself
3693 because the internal iterator may not have started at base.