git-svn: add support for SVN::Mirror/svk using revprops for metadata
[alt-git.git] / git-svn.perl
blob23e1d42cf74d8994cfbd6083be3a033bec3497be
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 $ENV{GIT_DIR} ||= '.git';
13 $Git::SVN::default_repo_id = 'svn';
14 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Log::TZ = $ENV{TZ};
17 $ENV{TZ} = 'UTC';
18 $| = 1; # unbuffer STDOUT
20 sub fatal (@) { print STDERR @_; exit 1 }
21 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
22 require SVN::Ra;
23 require SVN::Delta;
24 if ($SVN::Core::VERSION lt '1.1.0') {
25 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
27 push @Git::SVN::Ra::ISA, 'SVN::Ra';
28 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
29 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
30 use Carp qw/croak/;
31 use IO::File qw//;
32 use File::Basename qw/dirname basename/;
33 use File::Path qw/mkpath/;
34 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
35 use IPC::Open3;
36 use Git;
38 BEGIN {
39 my $s;
40 foreach (qw/command command_oneline command_noisy command_output_pipe
41 command_input_pipe command_close_pipe/) {
42 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
43 "*Git::SVN::Migration::$_ = ".
44 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
46 eval $s;
49 my ($SVN);
51 $sha1 = qr/[a-f\d]{40}/;
52 $sha1_short = qr/[a-f\d]{4,40}/;
53 my ($_stdin, $_help, $_edit,
54 $_message, $_file,
55 $_template, $_shared,
56 $_version,
57 $_merge, $_strategy, $_dry_run,
58 $_prefix);
59 $Git::SVN::_follow_parent = 1;
60 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
61 'config-dir=s' => \$Git::SVN::Ra::config_dir,
62 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
63 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
64 'authors-file|A=s' => \$_authors,
65 'repack:i' => \$Git::SVN::_repack,
66 'no-metadata' => \$Git::SVN::_no_metadata,
67 'use-svm-props|svm-props' => \$Git::SVN::_use_svm_props,
68 'quiet|q' => \$_q,
69 'repack-flags|repack-args|repack-opts=s' =>
70 \$Git::SVN::_repack_flags,
71 %remote_opts );
73 my ($_trunk, $_tags, $_branches);
74 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
75 'tags|t=s' => \$_tags,
76 'branches|b=s' => \$_branches );
77 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
78 my %cmt_opts = ( 'edit|e' => \$_edit,
79 'rmdir' => \$SVN::Git::Editor::_rmdir,
80 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
81 'l=i' => \$SVN::Git::Editor::_rename_limit,
82 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
85 my %cmd = (
86 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
87 { 'revision|r=s' => \$_revision, %fc_opts } ],
88 init => [ \&cmd_init, "Initialize a repo for tracking" .
89 " (requires URL argument)",
90 \%init_opts ],
91 dcommit => [ \&cmd_dcommit,
92 'Commit several diffs to merge with upstream',
93 { 'merge|m|M' => \$_merge,
94 'strategy|s=s' => \$_strategy,
95 'dry-run|n' => \$_dry_run,
96 %cmt_opts, %fc_opts } ],
97 'set-tree' => [ \&cmd_set_tree,
98 "Set an SVN repository to a git tree-ish",
99 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
100 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
101 { 'revision|r=i' => \$_revision } ],
102 'multi-init' => [ \&cmd_multi_init,
103 'Initialize multiple trees (like git-svnimport)',
104 { %multi_opts, %init_opts, %remote_opts,
105 'revision|r=i' => \$_revision,
106 'prefix=s' => \$_prefix,
107 } ],
108 'multi-fetch' => [ \&cmd_multi_fetch,
109 'Fetch multiple trees (like git-svnimport)',
110 \%fc_opts ],
111 'migrate' => [ sub { },
112 # no-op, we automatically run this anyways,
113 'Migrate configuration/metadata/layout from
114 previous versions of git-svn',
115 \%remote_opts ],
116 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
117 { 'limit=i' => \$Git::SVN::Log::limit,
118 'revision|r=s' => \$_revision,
119 'verbose|v' => \$Git::SVN::Log::verbose,
120 'incremental' => \$Git::SVN::Log::incremental,
121 'oneline' => \$Git::SVN::Log::oneline,
122 'show-commit' => \$Git::SVN::Log::show_commit,
123 'non-recursive' => \$Git::SVN::Log::non_recursive,
124 'authors-file|A=s' => \$_authors,
125 'color' => \$Git::SVN::Log::color,
126 'pager=s' => \$Git::SVN::Log::pager,
127 } ],
128 'commit-diff' => [ \&cmd_commit_diff,
129 'Commit a diff between two trees',
130 { 'message|m=s' => \$_message,
131 'file|F=s' => \$_file,
132 'revision|r=s' => \$_revision,
133 %cmt_opts } ],
136 my $cmd;
137 for (my $i = 0; $i < @ARGV; $i++) {
138 if (defined $cmd{$ARGV[$i]}) {
139 $cmd = $ARGV[$i];
140 splice @ARGV, $i, 1;
141 last;
145 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
147 read_repo_config(\%opts);
148 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
149 'minimize-connections' => \$Git::SVN::Migration::_minimize,
150 'id|i=s' => \$Git::SVN::default_ref_id,
151 'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
152 exit 1 if (!$rv && $cmd ne 'log');
154 usage(0) if $_help;
155 version() if $_version;
156 usage(1) unless defined $cmd;
157 load_authors() if $_authors;
158 unless ($cmd =~ /^(?:init|multi-init|commit-diff)$/) {
159 Git::SVN::Migration::migration_check();
161 Git::SVN::init_vars();
162 eval {
163 Git::SVN::verify_remotes_sanity();
164 $cmd{$cmd}->[0]->(@ARGV);
166 fatal $@ if $@;
167 exit 0;
169 ####################### primary functions ######################
170 sub usage {
171 my $exit = shift || 0;
172 my $fd = $exit ? \*STDERR : \*STDOUT;
173 print $fd <<"";
174 git-svn - bidirectional operations between a single Subversion tree and git
175 Usage: $0 <command> [options] [arguments]\n
177 print $fd "Available commands:\n" unless $cmd;
179 foreach (sort keys %cmd) {
180 next if $cmd && $cmd ne $_;
181 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
182 foreach (keys %{$cmd{$_}->[2]}) {
183 # prints out arguments as they should be passed:
184 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
185 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
186 "--$_" : "-$_" }
187 split /\|/,$_)," $x\n";
190 print $fd <<"";
191 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
192 arbitrary identifier if you're tracking multiple SVN branches/repositories in
193 one git repository and want to keep them separate. See git-svn(1) for more
194 information.
196 exit $exit;
199 sub version {
200 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
201 exit 0;
204 sub do_git_init_db {
205 unless (-d $ENV{GIT_DIR}) {
206 my @init_db = ('init');
207 push @init_db, "--template=$_template" if defined $_template;
208 push @init_db, "--shared" if defined $_shared;
209 command_noisy(@init_db);
213 sub cmd_init {
214 my $url = shift or die "SVN repository location required " .
215 "as a command-line argument\n";
216 if (my $repo_path = shift) {
217 unless (-d $repo_path) {
218 mkpath([$repo_path]);
220 chdir $repo_path or croak $!;
221 $ENV{GIT_DIR} = $repo_path . "/.git";
223 do_git_init_db();
225 Git::SVN->init($url);
228 sub cmd_fetch {
229 if (@_) {
230 die "Additional fetch arguments are no longer supported.\n",
231 "Use --follow-parent if you have moved/copied directories
232 instead.\n";
234 my $gs = Git::SVN->new;
235 $gs->fetch(parse_revision_argument());
236 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
237 command_noisy(qw(update-ref refs/heads/master),
238 $gs->{last_commit});
242 sub cmd_set_tree {
243 my (@commits) = @_;
244 if ($_stdin || !@commits) {
245 print "Reading from stdin...\n";
246 @commits = ();
247 while (<STDIN>) {
248 if (/\b($sha1_short)\b/o) {
249 unshift @commits, $1;
253 my @revs;
254 foreach my $c (@commits) {
255 my @tmp = command('rev-parse',$c);
256 if (scalar @tmp == 1) {
257 push @revs, $tmp[0];
258 } elsif (scalar @tmp > 1) {
259 push @revs, reverse(command('rev-list',@tmp));
260 } else {
261 fatal "Failed to rev-parse $c\n";
264 my $gs = Git::SVN->new;
265 my ($r_last, $cmt_last) = $gs->last_rev_commit;
266 $gs->fetch;
267 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
268 fatal "There are new revisions that were fetched ",
269 "and need to be merged (or acknowledged) ",
270 "before committing.\nlast rev: $r_last\n",
271 " current: $gs->{last_rev}\n";
273 $gs->set_tree($_) foreach @revs;
274 print "Done committing ",scalar @revs," revisions to SVN\n";
277 sub cmd_dcommit {
278 my $head = shift;
279 my $gs = Git::SVN->new;
280 $head ||= 'HEAD';
281 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
282 my $last_rev;
283 foreach my $d (reverse @refs) {
284 if (!verify_ref("$d~1")) {
285 fatal "Commit $d\n",
286 "has no parent commit, and therefore ",
287 "nothing to diff against.\n",
288 "You should be working from a repository ",
289 "originally created by git-svn\n";
291 unless (defined $last_rev) {
292 (undef, $last_rev, undef) = cmt_metadata("$d~1");
293 unless (defined $last_rev) {
294 fatal "Unable to extract revision information ",
295 "from commit $d~1\n";
298 if ($_dry_run) {
299 print "diff-tree $d~1 $d\n";
300 } else {
301 my %ed_opts = ( r => $last_rev,
302 log => get_commit_entry($d)->{log},
303 ra => $gs->ra,
304 tree_a => "$d~1",
305 tree_b => $d,
306 editor_cb => sub {
307 print "Committed r$_[0]\n";
308 $last_rev = $_[0]; },
309 svn_path => $gs->{path} );
310 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
311 print "No changes\n$d~1 == $d\n";
315 return if $_dry_run;
316 $gs->fetch;
317 # we always want to rebase against the current HEAD, not any
318 # head that was passed to us
319 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
320 my @finish;
321 if (@diff) {
322 @finish = qw/rebase/;
323 push @finish, qw/--merge/ if $_merge;
324 push @finish, "--strategy=$_strategy" if $_strategy;
325 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
326 "using @finish:\n", "@diff";
327 } else {
328 print "No changes between current HEAD and ",
329 $gs->refname, "\nResetting to the latest ",
330 $gs->refname, "\n";
331 @finish = qw/reset --mixed/;
333 command_noisy(@finish, $gs->refname);
336 sub cmd_show_ignore {
337 my $gs = Git::SVN->new;
338 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
339 $gs->traverse_ignore(\*STDOUT, '', $r);
342 sub cmd_multi_init {
343 my $url = shift;
344 unless (defined $_trunk || defined $_branches || defined $_tags) {
345 usage(1);
347 do_git_init_db();
348 $_prefix = '' unless defined $_prefix;
349 $url =~ s#/+$## if defined $url;
350 if (defined $_trunk) {
351 my $trunk_ref = $_prefix . 'trunk';
352 # try both old-style and new-style lookups:
353 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
354 unless ($gs_trunk) {
355 my ($trunk_url, $trunk_path) =
356 complete_svn_url($url, $_trunk);
357 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
358 undef, $trunk_ref);
361 return unless defined $_branches || defined $_tags;
362 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
363 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
364 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
367 sub cmd_multi_fetch {
368 my $remotes = Git::SVN::read_all_remotes();
369 foreach my $repo_id (sort keys %$remotes) {
370 if ($remotes->{$repo_id}->{url} &&
371 $remotes->{$repo_id}->{fetch}) {
372 Git::SVN::fetch_all($repo_id, $remotes);
377 # this command is special because it requires no metadata
378 sub cmd_commit_diff {
379 my ($ta, $tb, $url) = @_;
380 my $usage = "Usage: $0 commit-diff -r<revision> ".
381 "<tree-ish> <tree-ish> [<URL>]\n";
382 fatal($usage) if (!defined $ta || !defined $tb);
383 my $svn_path;
384 if (!defined $url) {
385 my $gs = eval { Git::SVN->new };
386 if (!$gs) {
387 fatal("Needed URL or usable git-svn --id in ",
388 "the command-line\n", $usage);
390 $url = $gs->{url};
391 $svn_path = $gs->{path};
393 unless (defined $_revision) {
394 fatal("-r|--revision is a required argument\n", $usage);
396 if (defined $_message && defined $_file) {
397 fatal("Both --message/-m and --file/-F specified ",
398 "for the commit message.\n",
399 "I have no idea what you mean\n");
401 if (defined $_file) {
402 $_message = file_to_s($_file);
403 } else {
404 $_message ||= get_commit_entry($tb)->{log};
406 my $ra ||= Git::SVN::Ra->new($url);
407 $svn_path ||= $ra->{svn_path};
408 my $r = $_revision;
409 if ($r eq 'HEAD') {
410 $r = $ra->get_latest_revnum;
411 } elsif ($r !~ /^\d+$/) {
412 die "revision argument: $r not understood by git-svn\n";
414 my %ed_opts = ( r => $r,
415 log => $_message,
416 ra => $ra,
417 tree_a => $ta,
418 tree_b => $tb,
419 editor_cb => sub { print "Committed r$_[0]\n" },
420 svn_path => $svn_path );
421 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
422 print "No changes\n$ta == $tb\n";
426 ########################### utility functions #########################
428 sub parse_revision_argument {
429 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
430 return (undef, undef);
432 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
433 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
434 return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
435 return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
436 die "revision argument: $_revision not understood by git-svn\n",
437 "Try using the command-line svn client instead\n";
440 sub complete_svn_url {
441 my ($url, $path) = @_;
442 $path =~ s#/+$##;
443 if ($path !~ m#^[a-z\+]+://#) {
444 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
445 fatal("E: '$path' is not a complete URL ",
446 "and a separate URL is not specified\n");
448 return ($url, $path);
450 return ($path, '');
453 sub complete_url_ls_init {
454 my ($ra, $repo_path, $switch, $pfx) = @_;
455 unless ($repo_path) {
456 print STDERR "W: $switch not specified\n";
457 return;
459 $repo_path =~ s#/+$##;
460 if ($repo_path =~ m#^[a-z\+]+://#) {
461 $ra = Git::SVN::Ra->new($repo_path);
462 $repo_path = '';
463 } else {
464 $repo_path =~ s#^/+##;
465 unless ($ra) {
466 fatal("E: '$repo_path' is not a complete URL ",
467 "and a separate URL is not specified\n");
470 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
471 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
472 my $url = $ra->{url};
473 my $remote_id;
474 my $remote_path;
475 foreach my $d (sort keys %$dirent) {
476 next if ($dirent->{$d}->kind != $SVN::Node::dir);
477 my $path = "$repo_path/$d";
478 my $ref = "$pfx$d";
479 my $gs = eval { Git::SVN->new($ref) };
480 # don't try to init already existing refs
481 unless ($gs) {
482 print "init $url/$path => $ref\n";
483 $gs = Git::SVN->init($url, $path, undef, $ref, 1);
485 if ($gs) {
486 $remote_id = $gs->{repo_id};
487 last;
490 if (defined $remote_id) {
491 $remote_path = "$ra->{svn_path}/$repo_path/*";
492 $remote_path =~ s#/+#/#g;
493 $remote_path =~ s#^/##g;
494 my ($n) = ($switch =~ /^--(\w+)/);
495 if (length $pfx && $pfx !~ m#/$#) {
496 die "--prefix='$pfx' must have a trailing slash '/'\n";
498 command_noisy('config', "svn-remote.$remote_id.$n",
499 "$remote_path:refs/remotes/$pfx*");
503 sub verify_ref {
504 my ($ref) = @_;
505 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
506 { STDERR => 0 }); };
509 sub get_tree_from_treeish {
510 my ($treeish) = @_;
511 # $treeish can be a symbolic ref, too:
512 my $type = command_oneline(qw/cat-file -t/, $treeish);
513 my $expected;
514 while ($type eq 'tag') {
515 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
517 if ($type eq 'commit') {
518 $expected = (grep /^tree /, command(qw/cat-file commit/,
519 $treeish))[0];
520 ($expected) = ($expected =~ /^tree ($sha1)$/o);
521 die "Unable to get tree from $treeish\n" unless $expected;
522 } elsif ($type eq 'tree') {
523 $expected = $treeish;
524 } else {
525 die "$treeish is a $type, expected tree, tag or commit\n";
527 return $expected;
530 sub get_commit_entry {
531 my ($treeish) = shift;
532 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
533 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
534 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
535 open my $log_fh, '>', $commit_editmsg or croak $!;
537 my $type = command_oneline(qw/cat-file -t/, $treeish);
538 if ($type eq 'commit' || $type eq 'tag') {
539 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
540 $type, $treeish);
541 my $in_msg = 0;
542 while (<$msg_fh>) {
543 if (!$in_msg) {
544 $in_msg = 1 if (/^\s*$/);
545 } elsif (/^git-svn-id: /) {
546 # skip this for now, we regenerate the
547 # correct one on re-fetch anyways
548 # TODO: set *:merge properties or like...
549 } else {
550 print $log_fh $_ or croak $!;
553 command_close_pipe($msg_fh, $ctx);
555 close $log_fh or croak $!;
557 if ($_edit || ($type eq 'tree')) {
558 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
559 # TODO: strip out spaces, comments, like git-commit.sh
560 system($editor, $commit_editmsg);
562 rename $commit_editmsg, $commit_msg or croak $!;
563 open $log_fh, '<', $commit_msg or croak $!;
564 { local $/; chomp($log_entry{log} = <$log_fh>); }
565 close $log_fh or croak $!;
566 unlink $commit_msg;
567 \%log_entry;
570 sub s_to_file {
571 my ($str, $file, $mode) = @_;
572 open my $fd,'>',$file or croak $!;
573 print $fd $str,"\n" or croak $!;
574 close $fd or croak $!;
575 chmod ($mode &~ umask, $file) if (defined $mode);
578 sub file_to_s {
579 my $file = shift;
580 open my $fd,'<',$file or croak "$!: file: $file\n";
581 local $/;
582 my $ret = <$fd>;
583 close $fd or croak $!;
584 $ret =~ s/\s*$//s;
585 return $ret;
588 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
589 sub load_authors {
590 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
591 my $log = $cmd eq 'log';
592 while (<$authors>) {
593 chomp;
594 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
595 my ($user, $name, $email) = ($1, $2, $3);
596 if ($log) {
597 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
598 } else {
599 $users{$user} = [$name, $email];
602 close $authors or croak $!;
605 # convert GetOpt::Long specs for use by git-config
606 sub read_repo_config {
607 return unless -d $ENV{GIT_DIR};
608 my $opts = shift;
609 foreach my $o (keys %$opts) {
610 my $v = $opts->{$o};
611 my ($key) = ($o =~ /^([a-z\-]+)/);
612 $key =~ s/-//g;
613 my $arg = 'git-config';
614 $arg .= ' --int' if ($o =~ /[:=]i$/);
615 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
616 if (ref $v eq 'ARRAY') {
617 chomp(my @tmp = `$arg --get-all svn.$key`);
618 @$v = @tmp if @tmp;
619 } else {
620 chomp(my $tmp = `$arg --get svn.$key`);
621 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
622 $$v = $tmp;
628 sub extract_metadata {
629 my $id = shift or return (undef, undef, undef);
630 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
631 \s([a-f\d\-]+)$/x);
632 if (!defined $rev || !$uuid || !$url) {
633 # some of the original repositories I made had
634 # identifiers like this:
635 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
637 return ($url, $rev, $uuid);
640 sub cmt_metadata {
641 return extract_metadata((grep(/^git-svn-id: /,
642 command(qw/cat-file commit/, shift)))[-1]);
645 package Git::SVN;
646 use strict;
647 use warnings;
648 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
649 $_repack $_repack_flags $_use_svm_props/;
650 use Carp qw/croak/;
651 use File::Path qw/mkpath/;
652 use File::Copy qw/copy/;
653 use IPC::Open3;
655 my $_repack_nr;
656 # properties that we do not log:
657 my %SKIP_PROP;
658 BEGIN {
659 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
660 svn:special svn:executable
661 svn:entry:committed-rev
662 svn:entry:last-author
663 svn:entry:uuid
664 svn:entry:committed-date/;
667 my %LOCKFILES;
668 END { unlink keys %LOCKFILES if %LOCKFILES }
670 sub resolve_local_globs {
671 my ($url, $fetch, $glob_spec) = @_;
672 return unless defined $glob_spec;
673 my $ref = $glob_spec->{ref};
674 my $path = $glob_spec->{path};
675 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
676 next unless m#^refs/remotes/$ref->{regex}$#;
677 my $p = $1;
678 my $pathname = $path->full_path($p);
679 my $refname = $ref->full_path($p);
680 if (my $existing = $fetch->{$pathname}) {
681 if ($existing ne $refname) {
682 die "Refspec conflict:\n",
683 "existing: refs/remotes/$existing\n",
684 " globbed: refs/remotes/$refname\n";
686 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
687 $u =~ s!^\Q$url\E(/|$)!! or die
688 "refs/remotes/$refname: '$url' not found in '$u'\n";
689 if ($pathname ne $u) {
690 warn "W: Refspec glob conflict ",
691 "(ref: refs/remotes/$refname):\n",
692 "expected path: $pathname\n",
693 " real path: $u\n",
694 "Continuing ahead with $u\n";
695 next;
697 } else {
698 $fetch->{$pathname} = $refname;
703 sub fetch_all {
704 my ($repo_id, $remotes) = @_;
705 my $remote = $remotes->{$repo_id};
706 my $fetch = $remote->{fetch};
707 my $url = $remote->{url};
708 my (@gs, @globs);
709 my $ra = Git::SVN::Ra->new($url);
710 my $uuid = $ra->uuid;
711 my $head = $ra->get_latest_revnum;
712 my $base = $head;
714 # read the max revs for wildcard expansion (branches/*, tags/*)
715 foreach my $t (qw/branches tags/) {
716 defined $remote->{$t} or next;
717 push @globs, $remote->{$t};
718 my $f = "$ENV{GIT_DIR}/svn/.$uuid.$t";
719 if (open my $fh, '<', $f) {
720 chomp(my $max_rev = <$fh>);
721 close $fh or die "Error closing $f: $!\n";
723 if ($max_rev !~ /^\d+$/) {
724 die "$max_rev (in $f) is not an integer!\n";
726 $remote->{$t}->{max_rev} = $max_rev;
727 $base = $max_rev if ($max_rev < $base);
731 foreach my $p (sort keys %$fetch) {
732 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
733 my $lr = $gs->rev_db_max;
734 if (defined $lr) {
735 $base = $lr if ($lr < $base);
737 push @gs, $gs;
739 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
742 sub read_all_remotes {
743 my $r = {};
744 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
745 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
746 $r->{$1}->{fetch}->{$2} = $3;
747 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
748 $r->{$1}->{url} = $2;
749 } elsif (m!^(.+)\.(branches|tags)=
750 (.*):refs/remotes/(.+)\s*$/!x) {
751 my ($p, $g) = ($3, $4);
752 my $rs = $r->{$1}->{$2} = {
753 t => $2,
754 path => Git::SVN::GlobSpec->new($p),
755 ref => Git::SVN::GlobSpec->new($g) };
756 if (length($rs->{ref}->{right}) != 0) {
757 die "The '*' glob character must be the last ",
758 "character of '$g'\n";
765 sub init_vars {
766 if (defined $_repack) {
767 $_repack = 1000 if ($_repack <= 0);
768 $_repack_nr = $_repack;
769 $_repack_flags ||= '-d';
773 sub verify_remotes_sanity {
774 return unless -d $ENV{GIT_DIR};
775 my %seen;
776 foreach (command(qw/config -l/)) {
777 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
778 if ($seen{$1}) {
779 die "Remote ref refs/remote/$1 is tracked by",
780 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
781 "Please resolve this ambiguity in ",
782 "your git configuration file before ",
783 "continuing\n";
785 $seen{$1} = $_;
790 # we allow more chars than remotes2config.sh...
791 sub sanitize_remote_name {
792 my ($name) = @_;
793 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
794 $name;
797 sub find_existing_remote {
798 my ($url, $remotes) = @_;
799 my $existing;
800 foreach my $repo_id (keys %$remotes) {
801 my $u = $remotes->{$repo_id}->{url} or next;
802 next if $u ne $url;
803 $existing = $repo_id;
804 last;
806 $existing;
809 sub init_remote_config {
810 my ($self, $url, $no_write) = @_;
811 $url =~ s!/+$!!; # strip trailing slash
812 my $r = read_all_remotes();
813 my $existing = find_existing_remote($url, $r);
814 if ($existing) {
815 unless ($no_write) {
816 print STDERR "Using existing ",
817 "[svn-remote \"$existing\"]\n";
819 $self->{repo_id} = $existing;
820 } else {
821 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
822 $existing = find_existing_remote($min_url, $r);
823 if ($existing) {
824 unless ($no_write) {
825 print STDERR "Using existing ",
826 "[svn-remote \"$existing\"]\n";
828 $self->{repo_id} = $existing;
830 if ($min_url ne $url) {
831 unless ($no_write) {
832 print STDERR "Using higher level of URL: ",
833 "$url => $min_url\n";
835 my $old_path = $self->{path};
836 $self->{path} = $url;
837 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
838 if (length $old_path) {
839 $self->{path} .= "/$old_path";
841 $url = $min_url;
844 my $orig_url;
845 if (!$existing) {
846 # verify that we aren't overwriting anything:
847 $orig_url = eval {
848 command_oneline('config', '--get',
849 "svn-remote.$self->{repo_id}.url")
851 if ($orig_url && ($orig_url ne $url)) {
852 die "svn-remote.$self->{repo_id}.url already set: ",
853 "$orig_url\nwanted to set to: $url\n";
856 my ($xrepo_id, $xpath) = find_ref($self->refname);
857 if (defined $xpath) {
858 die "svn-remote.$xrepo_id.fetch already set to track ",
859 "$xpath:refs/remotes/", $self->refname, "\n";
861 unless ($no_write) {
862 command_noisy('config',
863 "svn-remote.$self->{repo_id}.url", $url);
864 command_noisy('config', '--add',
865 "svn-remote.$self->{repo_id}.fetch",
866 "$self->{path}:".$self->refname);
868 $self->{url} = $url;
871 sub init {
872 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
873 my $self = _new($class, $repo_id, $ref_id, $path);
874 if (defined $url) {
875 $self->init_remote_config($url, $no_write);
877 $self;
880 sub find_ref {
881 my ($ref_id) = @_;
882 foreach (command(qw/config -l/)) {
883 next unless m!^svn-remote\.(.+)\.fetch=
884 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
885 my ($repo_id, $path, $ref) = ($1, $2, $3);
886 if ($ref eq $ref_id) {
887 $path = '' if ($path =~ m#^\./?#);
888 return ($repo_id, $path);
891 (undef, undef, undef);
894 sub new {
895 my ($class, $ref_id, $repo_id, $path) = @_;
896 if (defined $ref_id && !defined $repo_id && !defined $path) {
897 ($repo_id, $path) = find_ref($ref_id);
898 if (!defined $repo_id) {
899 die "Could not find a \"svn-remote.*.fetch\" key ",
900 "in the repository configuration matching: ",
901 "refs/remotes/$ref_id\n";
904 my $self = _new($class, $repo_id, $ref_id, $path);
905 if (!defined $self->{path} || !length $self->{path}) {
906 my $fetch = command_oneline('config', '--get',
907 "svn-remote.$repo_id.fetch",
908 ":refs/remotes/$ref_id\$") or
909 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
910 "\":refs/remotes/$ref_id\$\" in config\n";
911 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
913 $self->{url} = command_oneline('config', '--get',
914 "svn-remote.$repo_id.url") or
915 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
916 if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
917 $self->rebuild;
919 $self;
922 sub refname { "refs/remotes/$_[0]->{ref_id}" }
924 sub set_svm_vars {
925 my ($self, $ra) = @_;
926 my $section = "svn-remote.$self->{repo_id}";
928 # see if we have it in our config, first:
929 eval {
930 $self->{svm} = {
931 source => $self->tmp_config('--get', "$section.svm-source"),
932 uuid => $self->tmp_config('--get', "$section.svm-uuid"),
935 return $ra if ($self->{svm}->{source} && $self->{svm}->{uuid});
937 # nope, make sure we're connected to the repository root:
938 if ($ra->{repos_root} ne $self->{url}) {
939 $ra = Git::SVN::Ra->new($ra->{repos_root});
941 my $r = $ra->get_latest_revnum;
942 my ($props) = ($ra->get_dir('', $r))[2];
943 if (my $src = $props->{'svm:source'}) {
944 # don't know what a '!' is there for, also the
945 # username is of no interest
946 $src =~ s{!$}{};
947 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
948 $self->tmp_config('--add', "$section.svm-source", $src);
950 my $uuid = $props->{'svm:uuid'};
951 $uuid =~ m{^[0-9a-f\-]{30,}$}
952 or die "doesn't look right - svm:uuid is '$uuid'\n";
953 $self->tmp_config('--add', "$section.svm-uuid", $uuid);
955 $self->{svm} = { source => $src , uuid => $uuid };
957 if ($ra->{repos_root} ne $self->{url}) {
958 $ra = Git::SVN::Ra->new($self->{url});
960 $ra;
963 sub ra {
964 my ($self) = shift;
965 my $ra = Git::SVN::Ra->new($self->{url});
966 $self->{-use_svm_props} = $Git::SVN::_use_svm_props;
967 if ($self->{-use_svm_props} && !$self->{svm}) {
968 $ra = $self->set_svm_vars($ra);
969 $self->{-want_revprops} = 1;
971 $ra;
974 sub rel_path {
975 my ($self) = @_;
976 my $repos_root = $self->ra->{repos_root};
977 return $self->{path} if ($self->{url} eq $repos_root);
978 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
979 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
982 sub traverse_ignore {
983 my ($self, $fh, $path, $r) = @_;
984 $path =~ s#^/+##g;
985 my $ra = $self->ra;
986 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
987 my $p = $path;
988 $p =~ s#^\Q$ra->{svn_path}\E/##;
989 print $fh length $p ? "\n# $p\n" : "\n# /\n";
990 if (my $s = $props->{'svn:ignore'}) {
991 $s =~ s/[\r\n]+/\n/g;
992 chomp $s;
993 if (length $p == 0) {
994 $s =~ s#\n#\n/$p#g;
995 print $fh "/$s\n";
996 } else {
997 $s =~ s#\n#\n/$p/#g;
998 print $fh "/$p/$s\n";
1001 foreach (sort keys %$dirent) {
1002 next if $dirent->{$_}->kind != $SVN::Node::dir;
1003 $self->traverse_ignore($fh, "$path/$_", $r);
1007 sub last_rev { ($_[0]->last_rev_commit)[0] }
1008 sub last_commit { ($_[0]->last_rev_commit)[1] }
1010 # returns the newest SVN revision number and newest commit SHA1
1011 sub last_rev_commit {
1012 my ($self) = @_;
1013 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1014 return ($self->{last_rev}, $self->{last_commit});
1016 my $c = ::verify_ref($self->refname.'^0');
1017 if ($c) {
1018 my $rev = (::cmt_metadata($c))[1];
1019 if (defined $rev) {
1020 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1021 return ($rev, $c);
1024 my $offset = -41; # from tail
1025 my $rl;
1026 open my $fh, '<', $self->{db_path} or
1027 croak "$self->{db_path} not readable: $!\n";
1028 sysseek($fh, $offset, 2); # don't care for errors
1029 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1030 chomp $rl;
1031 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1032 $offset -= 41;
1033 sysseek($fh, $offset, 2); # don't care for errors
1034 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1035 chomp $rl;
1037 if ($c) {
1038 die "$self->{db_path} and ", $self->refname,
1039 " inconsistent!:\n$c != $rl\n";
1041 my $rev = sysseek($fh, 0, 1) or croak $!;
1042 $rev = ($rev - 41) / 41;
1043 close $fh or croak $!;
1044 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1045 return ($rev, $c);
1048 sub get_fetch_range {
1049 my ($self, $min, $max) = @_;
1050 $max ||= $self->ra->get_latest_revnum;
1051 $min ||= $self->rev_db_max;
1052 (++$min, $max);
1055 sub tmp_config {
1056 my ($self, @args) = @_;
1057 unless (-f $self->{config}) {
1058 open my $fh, '>', $self->{config} or
1059 die "Can't open $self->{config}: $!\n";
1060 print $fh "; This file is used internally by git-svn\n" or
1061 die "Couldn't write to $self->{config}: $!\n";
1062 print $fh "; You should not have to edit it\n" or
1063 die "Couldn't write to $self->{config}: $!\n";
1064 close $fh or die "Couldn't close $self->{config}: $!\n";
1066 my $old_config = $ENV{GIT_CONFIG};
1067 $ENV{GIT_CONFIG} = $self->{config};
1068 $@ = undef;
1069 my @ret = eval { command('config', @args) };
1070 my $err = $@;
1071 if (defined $old_config) {
1072 $ENV{GIT_CONFIG} = $old_config;
1073 } else {
1074 delete $ENV{GIT_CONFIG};
1076 die $err if $err;
1077 wantarray ? @ret : $ret[0];
1080 sub tmp_index_do {
1081 my ($self, $sub) = @_;
1082 my $old_index = $ENV{GIT_INDEX_FILE};
1083 $ENV{GIT_INDEX_FILE} = $self->{index};
1084 $@ = undef;
1085 my @ret = eval { &$sub };
1086 my $err = $@;
1087 if (defined $old_index) {
1088 $ENV{GIT_INDEX_FILE} = $old_index;
1089 } else {
1090 delete $ENV{GIT_INDEX_FILE};
1092 die $err if $err;
1093 wantarray ? @ret : $ret[0];
1096 sub assert_index_clean {
1097 my ($self, $treeish) = @_;
1099 $self->tmp_index_do(sub {
1100 command_noisy('read-tree', $treeish) unless -e $self->{index};
1101 my $x = command_oneline('write-tree');
1102 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1103 /^tree ($::sha1)/mo);
1104 if ($y ne $x) {
1105 unlink $self->{index} or croak $!;
1106 command_noisy('read-tree', $treeish);
1108 $x = command_oneline('write-tree');
1109 if ($y ne $x) {
1110 ::fatal "trees ($treeish) $y != $x\n",
1111 "Something is seriously wrong...\n";
1116 sub get_commit_parents {
1117 my ($self, $log_entry) = @_;
1118 my (%seen, @ret, @tmp);
1119 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1120 if (my $ip = $self->{inject_parents}) {
1121 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1122 push @tmp, $commit;
1125 if (my $cur = ::verify_ref($self->refname.'^0')) {
1126 push @tmp, $cur;
1128 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1129 while (my $p = shift @tmp) {
1130 next if $seen{$p};
1131 $seen{$p} = 1;
1132 push @ret, $p;
1133 # MAXPARENT is defined to 16 in commit-tree.c:
1134 last if @ret >= 16;
1136 if (@tmp) {
1137 die "r$log_entry->{revision}: No room for parents:\n\t",
1138 join("\n\t", @tmp), "\n";
1140 @ret;
1143 sub full_url {
1144 my ($self) = @_;
1145 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1148 sub do_git_commit {
1149 my ($self, $log_entry) = @_;
1150 my $lr = $self->last_rev;
1151 if (defined $lr && $lr >= $log_entry->{revision}) {
1152 die "Last fetched revision of ", $self->refname,
1153 " was r$lr, but we are about to fetch: ",
1154 "r$log_entry->{revision}!\n";
1156 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1157 croak "$log_entry->{revision} = $c already exists! ",
1158 "Why are we refetching it?\n";
1160 my $author = $log_entry->{author};
1161 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1162 : ($author, "$author\@".$self->ra->uuid));
1163 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1164 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1165 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1167 my $tree = $log_entry->{tree};
1168 if (!defined $tree) {
1169 $tree = $self->tmp_index_do(sub {
1170 command_oneline('write-tree') });
1172 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1174 my @exec = ('git-commit-tree', $tree);
1175 foreach ($self->get_commit_parents($log_entry)) {
1176 push @exec, '-p', $_;
1178 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1179 or croak $!;
1180 print $msg_fh $log_entry->{log} or croak $!;
1181 unless ($_no_metadata) {
1182 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1183 or croak $!;
1185 $msg_fh->flush == 0 or croak $!;
1186 close $msg_fh or croak $!;
1187 chomp(my $commit = do { local $/; <$out_fh> });
1188 close $out_fh or croak $!;
1189 waitpid $pid, 0;
1190 croak $? if $?;
1191 if ($commit !~ /^$::sha1$/o) {
1192 die "Failed to commit, invalid sha1: $commit\n";
1195 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1197 $self->{last_rev} = $log_entry->{revision};
1198 $self->{last_commit} = $commit;
1199 print "r$log_entry->{revision}";
1200 if (defined $log_entry->{svm_revision}) {
1201 print " (\@$log_entry->{svm_revision})";
1203 print " = $commit ($self->{ref_id})\n";
1204 if (defined $_repack && (--$_repack_nr == 0)) {
1205 $_repack_nr = $_repack;
1206 # repack doesn't use any arguments with spaces in them, does it?
1207 print "Running git repack $_repack_flags ...\n";
1208 command_noisy('repack', split(/\s+/, $_repack_flags));
1209 print "Done repacking\n";
1211 return $commit;
1214 sub match_paths {
1215 my ($self, $paths, $r) = @_;
1216 return 1 if $self->{path} eq '';
1217 if (my $path = $paths->{"/$self->{path}"}) {
1218 return ($path->{action} eq 'D') ? 0 : 1;
1220 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1221 if (grep /$self->{path_regex}/, keys %$paths) {
1222 return 1;
1224 my $c = '';
1225 foreach (split m#/#, $self->{path}) {
1226 $c .= "/$_";
1227 next unless ($paths->{$c} &&
1228 ($paths->{$c}->{action} =~ /^[AR]$/));
1229 if ($self->ra->check_path($self->{path}, $r) ==
1230 $SVN::Node::dir) {
1231 return 1;
1234 return 0;
1237 sub find_parent_branch {
1238 my ($self, $paths, $rev) = @_;
1239 return undef unless $_follow_parent;
1240 unless (defined $paths) {
1241 my $err_handler = $SVN::Error::handler;
1242 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1243 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1244 $paths =
1245 Git::SVN::Ra::dup_changed_paths($_[0]) });
1246 $SVN::Error::handler = $err_handler;
1248 return undef unless defined $paths;
1250 # look for a parent from another branch:
1251 my @b_path_components = split m#/#, $self->rel_path;
1252 my @a_path_components;
1253 my $i;
1254 while (@b_path_components) {
1255 $i = $paths->{'/'.join('/', @b_path_components)};
1256 last if $i && defined $i->{copyfrom_path};
1257 unshift(@a_path_components, pop(@b_path_components));
1259 return undef unless defined $i && defined $i->{copyfrom_path};
1260 my $branch_from = $i->{copyfrom_path};
1261 if (@a_path_components) {
1262 print STDERR "branch_from: $branch_from => ";
1263 $branch_from .= '/'.join('/', @a_path_components);
1264 print STDERR $branch_from, "\n";
1266 my $r = $i->{copyfrom_rev};
1267 my $repos_root = $self->ra->{repos_root};
1268 my $url = $self->ra->{url};
1269 my $new_url = $repos_root . $branch_from;
1270 print STDERR "Found possible branch point: ",
1271 "$new_url => ", $self->full_url, ", $r\n";
1272 $branch_from =~ s#^/##;
1273 my $remotes = read_all_remotes();
1274 my $gs;
1275 foreach my $repo_id (keys %$remotes) {
1276 my $u = $remotes->{$repo_id}->{url} or next;
1277 next if $url ne $u;
1278 my $fetch = $remotes->{$repo_id}->{fetch};
1279 foreach (qw/branches tags/) {
1280 resolve_local_globs($url, $fetch,
1281 $remotes->{$repo_id}->{$_});
1283 foreach my $f (keys %$fetch) {
1284 next if $f ne $branch_from;
1285 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1286 last;
1288 last if $gs;
1290 unless ($gs) {
1291 my $ref_id = $self->{ref_id};
1292 $ref_id =~ s/\@\d+$//;
1293 $ref_id .= "\@$r";
1294 # just grow a tail if we're not unique enough :x
1295 $ref_id .= '-' while find_ref($ref_id);
1296 print STDERR "Initializing parent: $ref_id\n";
1297 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1299 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1300 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1301 $gs->fetch(0, $r);
1302 ($r0, $parent) = $gs->last_rev_commit;
1304 if (defined $r0 && defined $parent) {
1305 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1306 $self->assert_index_clean($parent);
1307 my $ed;
1308 if ($self->ra->can_do_switch) {
1309 print STDERR "Following parent with do_switch\n";
1310 # do_switch works with svn/trunk >= r22312, but that
1311 # is not included with SVN 1.4.3 (the latest version
1312 # at the moment), so we can't rely on it
1313 $self->{last_commit} = $parent;
1314 $ed = SVN::Git::Fetcher->new($self);
1315 $gs->ra->gs_do_switch($r0, $rev, $gs,
1316 $self->full_url, $ed)
1317 or die "SVN connection failed somewhere...\n";
1318 } else {
1319 print STDERR "Following parent with do_update\n";
1320 $ed = SVN::Git::Fetcher->new($self);
1321 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1322 or die "SVN connection failed somewhere...\n";
1324 print STDERR "Successfully followed parent\n";
1325 return $self->make_log_entry($rev, [$parent], $ed);
1327 return undef;
1330 sub do_fetch {
1331 my ($self, $paths, $rev) = @_;
1332 my $ed;
1333 my ($last_rev, @parents);
1334 if (my $lc = $self->last_commit) {
1335 # we can have a branch that was deleted, then re-added
1336 # under the same name but copied from another path, in
1337 # which case we'll have multiple parents (we don't
1338 # want to break the original ref, nor lose copypath info):
1339 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1340 push @{$log_entry->{parents}}, $lc;
1341 return $log_entry;
1343 $ed = SVN::Git::Fetcher->new($self);
1344 $last_rev = $self->{last_rev};
1345 $ed->{c} = $lc;
1346 @parents = ($lc);
1347 } else {
1348 $last_rev = $rev;
1349 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1350 return $log_entry;
1352 $ed = SVN::Git::Fetcher->new($self);
1354 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1355 die "SVN connection failed somewhere...\n";
1357 $self->make_log_entry($rev, \@parents, $ed);
1360 sub get_untracked {
1361 my ($self, $ed) = @_;
1362 my @out;
1363 my $h = $ed->{empty};
1364 foreach (sort keys %$h) {
1365 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1366 push @out, " $act: " . uri_encode($_);
1367 warn "W: $act: $_\n";
1369 foreach my $t (qw/dir_prop file_prop/) {
1370 $h = $ed->{$t} or next;
1371 foreach my $path (sort keys %$h) {
1372 my $ppath = $path eq '' ? '.' : $path;
1373 foreach my $prop (sort keys %{$h->{$path}}) {
1374 next if $SKIP_PROP{$prop};
1375 my $v = $h->{$path}->{$prop};
1376 my $t_ppath_prop = "$t: " .
1377 uri_encode($ppath) . ' ' .
1378 uri_encode($prop);
1379 if (defined $v) {
1380 push @out, " +$t_ppath_prop " .
1381 uri_encode($v);
1382 } else {
1383 push @out, " -$t_ppath_prop";
1388 foreach my $t (qw/absent_file absent_directory/) {
1389 $h = $ed->{$t} or next;
1390 foreach my $parent (sort keys %$h) {
1391 foreach my $path (sort @{$h->{$parent}}) {
1392 push @out, " $t: " .
1393 uri_encode("$parent/$path");
1394 warn "W: $t: $parent/$path ",
1395 "Insufficient permissions?\n";
1399 \@out;
1402 sub parse_svn_date {
1403 my $date = shift || return '+0000 1970-01-01 00:00:00';
1404 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1405 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1406 croak "Unable to parse date: $date\n";
1407 "+0000 $Y-$m-$d $H:$M:$S";
1410 sub check_author {
1411 my ($author) = @_;
1412 if (!defined $author || length $author == 0) {
1413 $author = '(no author)';
1415 if (defined $::_authors && ! defined $::users{$author}) {
1416 die "Author: $author not defined in $::_authors file\n";
1418 $author;
1421 sub make_log_entry {
1422 my ($self, $rev, $parents, $ed) = @_;
1423 my $untracked = $self->get_untracked($ed);
1425 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1426 print $un "r$rev\n" or croak $!;
1427 print $un $_, "\n" foreach @$untracked;
1428 my %log_entry = ( parents => $parents || [], revision => $rev,
1429 log => '');
1431 my $headrev;
1432 my $logged = delete $self->{logged_rev_props};
1433 if (!$logged || $self->{-want_revprops}) {
1434 my $rp = $self->ra->rev_proplist($rev);
1435 foreach (sort keys %$rp) {
1436 my $v = $rp->{$_};
1437 if (/^svn:(author|date|log)$/) {
1438 $log_entry{$1} = $v;
1439 } elsif ($_ eq 'svm:headrev') {
1440 $headrev = $v;
1441 } else {
1442 print $un " rev_prop: ", uri_encode($_), ' ',
1443 uri_encode($v), "\n";
1446 } else {
1447 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1449 close $un or croak $!;
1451 $log_entry{date} = parse_svn_date($log_entry{date});
1452 $log_entry{author} = check_author($log_entry{author});
1453 $log_entry{log} .= "\n";
1454 if (defined $headrev && $self->{-use_svm_props}) {
1455 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1456 if ($uuid ne $self->{svm}->{uuid}) {
1457 die "UUID mismatch on SVM path:\n",
1458 "expected: $self->{svm}->{uuid}\n",
1459 " got: $uuid\n";
1461 my $full_url = $self->{svm}->{source};
1462 $full_url .= "/$self->{path}" if length $self->{path};
1463 $log_entry{metadata} = "$full_url\@$r $uuid";
1464 $log_entry{svm_revision} = $r;
1465 } else {
1466 $log_entry{metadata} = $self->full_url . "\@$rev " .
1467 $self->ra->uuid;
1469 \%log_entry;
1472 sub fetch {
1473 my ($self, $min_rev, $max_rev, @parents) = @_;
1474 my ($last_rev, $last_commit) = $self->last_rev_commit;
1475 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1476 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1479 sub set_tree_cb {
1480 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1481 $self->{inject_parents} = { $rev => $tree };
1482 $self->fetch(undef, undef);
1485 sub set_tree {
1486 my ($self, $tree) = (shift, shift);
1487 my $log_entry = ::get_commit_entry($tree);
1488 unless ($self->{last_rev}) {
1489 fatal("Must have an existing revision to commit\n");
1491 my %ed_opts = ( r => $self->{last_rev},
1492 log => $log_entry->{log},
1493 ra => $self->ra,
1494 tree_a => $self->{last_commit},
1495 tree_b => $tree,
1496 editor_cb => sub {
1497 $self->set_tree_cb($log_entry, $tree, @_) },
1498 svn_path => $self->{path} );
1499 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1500 print "No changes\nr$self->{last_rev} = $tree\n";
1504 sub rebuild {
1505 my ($self) = @_;
1506 print "Rebuilding $self->{db_path} ...\n";
1507 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1508 my $latest;
1509 my $full_url = $self->full_url;
1510 my $svn_uuid;
1511 while (<$rev_list>) {
1512 chomp;
1513 my $c = $_;
1514 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1515 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1517 # ignore merges (from set-tree)
1518 next if (!defined $rev || !$uuid);
1520 # if we merged or otherwise started elsewhere, this is
1521 # how we break out of it
1522 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1523 ($full_url && $url && ($url ne $full_url))) {
1524 next;
1526 $latest ||= $rev;
1527 $svn_uuid ||= $uuid;
1529 $self->rev_db_set($rev, $c);
1530 print "r$rev = $c\n";
1532 command_close_pipe($rev_list, $ctx);
1533 print "Done rebuilding $self->{db_path}\n";
1536 # rev_db:
1537 # Tie::File seems to be prone to offset errors if revisions get sparse,
1538 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1539 # one of my favorite modules is out :< Next up would be one of the DBM
1540 # modules, but I'm not sure which is most portable... So I'll just
1541 # go with something that's plain-text, but still capable of
1542 # being randomly accessed. So here's my ultra-simple fixed-width
1543 # database. All records are 40 characters + "\n", so it's easy to seek
1544 # to a revision: (41 * rev) is the byte offset.
1545 # A record of 40 0s denotes an empty revision.
1546 # And yes, it's still pretty fast (faster than Tie::File).
1547 # These files are disposable unless --no-metadata is set
1549 sub rev_db_set {
1550 my ($self, $rev, $commit, $update_ref) = @_;
1551 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1552 my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1553 my $sig;
1554 if ($update_ref) {
1555 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1556 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1558 $LOCKFILES{$db_lock} = 1;
1559 if ($_no_metadata) {
1560 copy($db, $db_lock) or die "rev_db_set(@_): ",
1561 "Failed to copy: ",
1562 "$db => $db_lock ($!)\n";
1563 } else {
1564 rename $db, $db_lock or die "rev_db_set(@_): ",
1565 "Failed to rename: ",
1566 "$db => $db_lock ($!)\n";
1568 open my $fh, '+<', $db_lock or croak $!;
1569 my $offset = $rev * 41;
1570 # assume that append is the common case:
1571 seek $fh, 0, 2 or croak $!;
1572 my $pos = tell $fh;
1573 if ($pos < $offset) {
1574 for (1 .. (($offset - $pos) / 41)) {
1575 print $fh (('0' x 40),"\n") or croak $!;
1578 seek $fh, $offset, 0 or croak $!;
1579 print $fh $commit,"\n" or croak $!;
1580 close $fh or croak $!;
1581 if ($update_ref) {
1582 command_noisy('update-ref', '-m', "r$rev",
1583 $self->refname, $commit);
1585 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1586 "$db_lock => $db ($!)\n";
1587 delete $LOCKFILES{$db_lock};
1588 if ($update_ref) {
1589 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1590 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1591 kill $sig, $$ if defined $sig;
1595 sub rev_db_max {
1596 my ($self) = @_;
1597 my @stat = stat $self->{db_path} or
1598 die "Couldn't stat $self->{db_path}: $!\n";
1599 ($stat[7] % 41) == 0 or
1600 die "$self->{db_path} inconsistent size:$stat[7]\n";
1601 my $max = $stat[7] / 41;
1602 (($max > 0) ? $max - 1 : 0);
1605 sub rev_db_get {
1606 my ($self, $rev) = @_;
1607 my $ret;
1608 my $offset = $rev * 41;
1609 open my $fh, '<', $self->{db_path} or croak $!;
1610 if (sysseek($fh, $offset, 0) == $offset) {
1611 my $read = sysread($fh, $ret, 40);
1612 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1614 close $fh or croak $!;
1615 $ret;
1618 sub find_rev_before {
1619 my ($self, $rev, $eq_ok) = @_;
1620 --$rev unless $eq_ok;
1621 while ($rev > 0) {
1622 if (my $c = $self->rev_db_get($rev)) {
1623 return ($rev, $c);
1625 --$rev;
1627 return (undef, undef);
1630 sub _new {
1631 my ($class, $repo_id, $ref_id, $path) = @_;
1632 unless (defined $repo_id && length $repo_id) {
1633 $repo_id = $Git::SVN::default_repo_id;
1635 unless (defined $ref_id && length $ref_id) {
1636 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1638 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1639 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1640 $_[3] = $path = '' unless (defined $path);
1641 mkpath([$dir]);
1642 unless (-f "$dir/.rev_db") {
1643 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1644 close $fh or croak $!;
1646 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1647 path => $path, config => "$ENV{GIT_DIR}/svn/config",
1648 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1651 sub uri_encode {
1652 my ($f) = @_;
1653 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1657 package Git::SVN::Prompt;
1658 use strict;
1659 use warnings;
1660 require SVN::Core;
1661 use vars qw/$_no_auth_cache $_username/;
1663 sub simple {
1664 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1665 $may_save = undef if $_no_auth_cache;
1666 $default_username = $_username if defined $_username;
1667 if (defined $default_username && length $default_username) {
1668 if (defined $realm && length $realm) {
1669 print STDERR "Authentication realm: $realm\n";
1670 STDERR->flush;
1672 $cred->username($default_username);
1673 } else {
1674 username($cred, $realm, $may_save, $pool);
1676 $cred->password(_read_password("Password for '" .
1677 $cred->username . "': ", $realm));
1678 $cred->may_save($may_save);
1679 $SVN::_Core::SVN_NO_ERROR;
1682 sub ssl_server_trust {
1683 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1684 $may_save = undef if $_no_auth_cache;
1685 print STDERR "Error validating server certificate for '$realm':\n";
1686 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1687 print STDERR " - The certificate is not issued by a trusted ",
1688 "authority. Use the\n",
1689 " fingerprint to validate the certificate manually!\n";
1691 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1692 print STDERR " - The certificate hostname does not match.\n";
1694 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1695 print STDERR " - The certificate is not yet valid.\n";
1697 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1698 print STDERR " - The certificate has expired.\n";
1700 if ($failures & $SVN::Auth::SSL::OTHER) {
1701 print STDERR " - The certificate has an unknown error.\n";
1703 printf STDERR
1704 "Certificate information:\n".
1705 " - Hostname: %s\n".
1706 " - Valid: from %s until %s\n".
1707 " - Issuer: %s\n".
1708 " - Fingerprint: %s\n",
1709 map $cert_info->$_, qw(hostname valid_from valid_until
1710 issuer_dname fingerprint);
1711 my $choice;
1712 prompt:
1713 print STDERR $may_save ?
1714 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1715 "(R)eject or accept (t)emporarily? ";
1716 STDERR->flush;
1717 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1718 if ($choice =~ /^t$/i) {
1719 $cred->may_save(undef);
1720 } elsif ($choice =~ /^r$/i) {
1721 return -1;
1722 } elsif ($may_save && $choice =~ /^p$/i) {
1723 $cred->may_save($may_save);
1724 } else {
1725 goto prompt;
1727 $cred->accepted_failures($failures);
1728 $SVN::_Core::SVN_NO_ERROR;
1731 sub ssl_client_cert {
1732 my ($cred, $realm, $may_save, $pool) = @_;
1733 $may_save = undef if $_no_auth_cache;
1734 print STDERR "Client certificate filename: ";
1735 STDERR->flush;
1736 chomp(my $filename = <STDIN>);
1737 $cred->cert_file($filename);
1738 $cred->may_save($may_save);
1739 $SVN::_Core::SVN_NO_ERROR;
1742 sub ssl_client_cert_pw {
1743 my ($cred, $realm, $may_save, $pool) = @_;
1744 $may_save = undef if $_no_auth_cache;
1745 $cred->password(_read_password("Password: ", $realm));
1746 $cred->may_save($may_save);
1747 $SVN::_Core::SVN_NO_ERROR;
1750 sub username {
1751 my ($cred, $realm, $may_save, $pool) = @_;
1752 $may_save = undef if $_no_auth_cache;
1753 if (defined $realm && length $realm) {
1754 print STDERR "Authentication realm: $realm\n";
1756 my $username;
1757 if (defined $_username) {
1758 $username = $_username;
1759 } else {
1760 print STDERR "Username: ";
1761 STDERR->flush;
1762 chomp($username = <STDIN>);
1764 $cred->username($username);
1765 $cred->may_save($may_save);
1766 $SVN::_Core::SVN_NO_ERROR;
1769 sub _read_password {
1770 my ($prompt, $realm) = @_;
1771 print STDERR $prompt;
1772 STDERR->flush;
1773 require Term::ReadKey;
1774 Term::ReadKey::ReadMode('noecho');
1775 my $password = '';
1776 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1777 last if $key =~ /[\012\015]/; # \n\r
1778 $password .= $key;
1780 Term::ReadKey::ReadMode('restore');
1781 print STDERR "\n";
1782 STDERR->flush;
1783 $password;
1786 package main;
1789 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1790 $SVN::Node::dir.$SVN::Node::unknown.
1791 $SVN::Node::none.$SVN::Node::file.
1792 $SVN::Node::dir.$SVN::Node::unknown.
1793 $SVN::Auth::SSL::CNMISMATCH.
1794 $SVN::Auth::SSL::NOTYETVALID.
1795 $SVN::Auth::SSL::EXPIRED.
1796 $SVN::Auth::SSL::UNKNOWNCA.
1797 $SVN::Auth::SSL::OTHER;
1800 package SVN::Git::Fetcher;
1801 use vars qw/@ISA/;
1802 use strict;
1803 use warnings;
1804 use Carp qw/croak/;
1805 use IO::File qw//;
1806 use Digest::MD5;
1808 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1809 sub new {
1810 my ($class, $git_svn) = @_;
1811 my $self = SVN::Delta::Editor->new;
1812 bless $self, $class;
1813 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1814 $self->{empty} = {};
1815 $self->{dir_prop} = {};
1816 $self->{file_prop} = {};
1817 $self->{absent_dir} = {};
1818 $self->{absent_file} = {};
1819 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1820 $self;
1823 sub set_path_strip {
1824 my ($self, $path) = @_;
1825 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
1828 sub open_root {
1829 { path => '' };
1832 sub open_directory {
1833 my ($self, $path, $pb, $rev) = @_;
1834 { path => $path };
1837 sub git_path {
1838 my ($self, $path) = @_;
1839 if ($self->{path_strip}) {
1840 $path =~ s!$self->{path_strip}!! or
1841 die "Failed to strip path '$path' ($self->{path_strip})\n";
1843 $path;
1846 sub delete_entry {
1847 my ($self, $path, $rev, $pb) = @_;
1849 my $gpath = $self->git_path($path);
1850 return undef if ($gpath eq '');
1852 # remove entire directories.
1853 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1854 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1855 -r --name-only -z/,
1856 $self->{c}, '--', $gpath);
1857 local $/ = "\0";
1858 while (<$ls>) {
1859 chomp;
1860 $self->{gii}->remove($_);
1861 print "\tD\t$_\n" unless $::_q;
1863 print "\tD\t$gpath/\n" unless $::_q;
1864 command_close_pipe($ls, $ctx);
1865 $self->{empty}->{$path} = 0
1866 } else {
1867 $self->{gii}->remove($gpath);
1868 print "\tD\t$gpath\n" unless $::_q;
1870 undef;
1873 sub open_file {
1874 my ($self, $path, $pb, $rev) = @_;
1875 my $gpath = $self->git_path($path);
1876 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1877 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1878 unless (defined $mode && defined $blob) {
1879 die "$path was not found in commit $self->{c} (r$rev)\n";
1881 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1882 pool => SVN::Pool->new, action => 'M' };
1885 sub add_file {
1886 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1887 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1888 delete $self->{empty}->{$dir};
1889 { path => $path, mode_a => 100644, mode_b => 100644,
1890 pool => SVN::Pool->new, action => 'A' };
1893 sub add_directory {
1894 my ($self, $path, $cp_path, $cp_rev) = @_;
1895 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1896 delete $self->{empty}->{$dir};
1897 $self->{empty}->{$path} = 1;
1898 { path => $path };
1901 sub change_dir_prop {
1902 my ($self, $db, $prop, $value) = @_;
1903 $self->{dir_prop}->{$db->{path}} ||= {};
1904 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1905 undef;
1908 sub absent_directory {
1909 my ($self, $path, $pb) = @_;
1910 $self->{absent_dir}->{$pb->{path}} ||= [];
1911 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1912 undef;
1915 sub absent_file {
1916 my ($self, $path, $pb) = @_;
1917 $self->{absent_file}->{$pb->{path}} ||= [];
1918 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1919 undef;
1922 sub change_file_prop {
1923 my ($self, $fb, $prop, $value) = @_;
1924 if ($prop eq 'svn:executable') {
1925 if ($fb->{mode_b} != 120000) {
1926 $fb->{mode_b} = defined $value ? 100755 : 100644;
1928 } elsif ($prop eq 'svn:special') {
1929 $fb->{mode_b} = defined $value ? 120000 : 100644;
1930 } else {
1931 $self->{file_prop}->{$fb->{path}} ||= {};
1932 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1934 undef;
1937 sub apply_textdelta {
1938 my ($self, $fb, $exp) = @_;
1939 my $fh = IO::File->new_tmpfile;
1940 $fh->autoflush(1);
1941 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1942 # (but $base does not,) so dup() it for reading in close_file
1943 open my $dup, '<&', $fh or croak $!;
1944 my $base = IO::File->new_tmpfile;
1945 $base->autoflush(1);
1946 if ($fb->{blob}) {
1947 defined (my $pid = fork) or croak $!;
1948 if (!$pid) {
1949 open STDOUT, '>&', $base or croak $!;
1950 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1951 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1953 waitpid $pid, 0;
1954 croak $? if $?;
1956 if (defined $exp) {
1957 seek $base, 0, 0 or croak $!;
1958 my $md5 = Digest::MD5->new;
1959 $md5->addfile($base);
1960 my $got = $md5->hexdigest;
1961 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1962 "expected: $exp\n",
1963 " got: $got\n" if ($got ne $exp);
1966 seek $base, 0, 0 or croak $!;
1967 $fb->{fh} = $dup;
1968 $fb->{base} = $base;
1969 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1972 sub close_file {
1973 my ($self, $fb, $exp) = @_;
1974 my $hash;
1975 my $path = $self->git_path($fb->{path});
1976 if (my $fh = $fb->{fh}) {
1977 seek($fh, 0, 0) or croak $!;
1978 my $md5 = Digest::MD5->new;
1979 $md5->addfile($fh);
1980 my $got = $md5->hexdigest;
1981 die "Checksum mismatch: $path\n",
1982 "expected: $exp\n got: $got\n" if ($got ne $exp);
1983 seek($fh, 0, 0) or croak $!;
1984 if ($fb->{mode_b} == 120000) {
1985 read($fh, my $buf, 5) == 5 or croak $!;
1986 $buf eq 'link ' or die "$path has mode 120000",
1987 "but is not a link\n";
1989 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1990 if (!$pid) {
1991 open STDIN, '<&', $fh or croak $!;
1992 exec qw/git-hash-object -w --stdin/ or croak $!;
1994 chomp($hash = do { local $/; <$out> });
1995 close $out or croak $!;
1996 close $fh or croak $!;
1997 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1998 close $fb->{base} or croak $!;
1999 } else {
2000 $hash = $fb->{blob} or die "no blob information\n";
2002 $fb->{pool}->clear;
2003 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2004 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2005 undef;
2008 sub abort_edit {
2009 my $self = shift;
2010 $self->{nr} = $self->{gii}->{nr};
2011 delete $self->{gii};
2012 $self->SUPER::abort_edit(@_);
2015 sub close_edit {
2016 my $self = shift;
2017 $self->{git_commit_ok} = 1;
2018 $self->{nr} = $self->{gii}->{nr};
2019 delete $self->{gii};
2020 $self->SUPER::close_edit(@_);
2023 package SVN::Git::Editor;
2024 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2025 use strict;
2026 use warnings;
2027 use Carp qw/croak/;
2028 use IO::File;
2029 use Digest::MD5;
2031 sub new {
2032 my ($class, $opts) = @_;
2033 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2034 die "$_ required!\n" unless (defined $opts->{$_});
2037 my $pool = SVN::Pool->new;
2038 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2039 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2040 $opts->{r}, $mods);
2042 # $opts->{ra} functions should not be used after this:
2043 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2044 $opts->{editor_cb}, $pool);
2045 my $self = SVN::Delta::Editor->new(@ce, $pool);
2046 bless $self, $class;
2047 foreach (qw/svn_path r tree_a tree_b/) {
2048 $self->{$_} = $opts->{$_};
2050 $self->{url} = $opts->{ra}->{url};
2051 $self->{mods} = $mods;
2052 $self->{types} = $types;
2053 $self->{pool} = $pool;
2054 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2055 $self->{rm} = { };
2056 $self->{path_prefix} = length $self->{svn_path} ?
2057 "$self->{svn_path}/" : '';
2058 return $self;
2061 sub generate_diff {
2062 my ($tree_a, $tree_b) = @_;
2063 my @diff_tree = qw(diff-tree -z -r);
2064 if ($_cp_similarity) {
2065 push @diff_tree, "-C$_cp_similarity";
2066 } else {
2067 push @diff_tree, '-C';
2069 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2070 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2071 push @diff_tree, $tree_a, $tree_b;
2072 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2073 local $/ = "\0";
2074 my $state = 'meta';
2075 my @mods;
2076 while (<$diff_fh>) {
2077 chomp $_; # this gets rid of the trailing "\0"
2078 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2079 $::sha1\s($::sha1)\s
2080 ([MTCRAD])\d*$/xo) {
2081 push @mods, { mode_a => $1, mode_b => $2,
2082 sha1_b => $3, chg => $4 };
2083 if ($4 =~ /^(?:C|R)$/) {
2084 $state = 'file_a';
2085 } else {
2086 $state = 'file_b';
2088 } elsif ($state eq 'file_a') {
2089 my $x = $mods[$#mods] or croak "Empty array\n";
2090 if ($x->{chg} !~ /^(?:C|R)$/) {
2091 croak "Error parsing $_, $x->{chg}\n";
2093 $x->{file_a} = $_;
2094 $state = 'file_b';
2095 } elsif ($state eq 'file_b') {
2096 my $x = $mods[$#mods] or croak "Empty array\n";
2097 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2098 croak "Error parsing $_, $x->{chg}\n";
2100 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2101 croak "Error parsing $_, $x->{chg}\n";
2103 $x->{file_b} = $_;
2104 $state = 'meta';
2105 } else {
2106 croak "Error parsing $_\n";
2109 command_close_pipe($diff_fh, $ctx);
2110 \@mods;
2113 sub check_diff_paths {
2114 my ($ra, $pfx, $rev, $mods) = @_;
2115 my %types;
2116 $pfx .= '/' if length $pfx;
2118 sub type_diff_paths {
2119 my ($ra, $types, $path, $rev) = @_;
2120 my @p = split m#/+#, $path;
2121 my $c = shift @p;
2122 unless (defined $types->{$c}) {
2123 $types->{$c} = $ra->check_path($c, $rev);
2125 while (@p) {
2126 $c .= '/' . shift @p;
2127 next if defined $types->{$c};
2128 $types->{$c} = $ra->check_path($c, $rev);
2132 foreach my $m (@$mods) {
2133 foreach my $f (qw/file_a file_b/) {
2134 next unless defined $m->{$f};
2135 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2136 if (length $pfx.$dir && ! defined $types{$dir}) {
2137 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2141 \%types;
2144 sub split_path {
2145 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2148 sub repo_path {
2149 my ($self, $path) = @_;
2150 $self->{path_prefix}.(defined $path ? $path : '');
2153 sub url_path {
2154 my ($self, $path) = @_;
2155 $self->{url} . '/' . $self->repo_path($path);
2158 sub rmdirs {
2159 my ($self) = @_;
2160 my $rm = $self->{rm};
2161 delete $rm->{''}; # we never delete the url we're tracking
2162 return unless %$rm;
2164 foreach (keys %$rm) {
2165 my @d = split m#/#, $_;
2166 my $c = shift @d;
2167 $rm->{$c} = 1;
2168 while (@d) {
2169 $c .= '/' . shift @d;
2170 $rm->{$c} = 1;
2173 delete $rm->{$self->{svn_path}};
2174 delete $rm->{''}; # we never delete the url we're tracking
2175 return unless %$rm;
2177 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2178 $self->{tree_b});
2179 local $/ = "\0";
2180 while (<$fh>) {
2181 chomp;
2182 my @dn = split m#/#, $_;
2183 while (pop @dn) {
2184 delete $rm->{join '/', @dn};
2186 unless (%$rm) {
2187 close $fh;
2188 return;
2191 command_close_pipe($fh, $ctx);
2193 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2194 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2195 $self->close_directory($bat->{$d}, $p);
2196 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2197 print "\tD+\t$d/\n" unless $::_q;
2198 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2199 delete $bat->{$d};
2203 sub open_or_add_dir {
2204 my ($self, $full_path, $baton) = @_;
2205 my $t = $self->{types}->{$full_path};
2206 if (!defined $t) {
2207 die "$full_path not known in r$self->{r} or we have a bug!\n";
2209 if ($t == $SVN::Node::none) {
2210 return $self->add_directory($full_path, $baton,
2211 undef, -1, $self->{pool});
2212 } elsif ($t == $SVN::Node::dir) {
2213 return $self->open_directory($full_path, $baton,
2214 $self->{r}, $self->{pool});
2216 print STDERR "$full_path already exists in repository at ",
2217 "r$self->{r} and it is not a directory (",
2218 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2219 exit 1;
2222 sub ensure_path {
2223 my ($self, $path) = @_;
2224 my $bat = $self->{bat};
2225 my $repo_path = $self->repo_path($path);
2226 return $bat->{''} unless (length $repo_path);
2227 my @p = split m#/+#, $repo_path;
2228 my $c = shift @p;
2229 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2230 while (@p) {
2231 my $c0 = $c;
2232 $c .= '/' . shift @p;
2233 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2235 return $bat->{$c};
2238 sub A {
2239 my ($self, $m) = @_;
2240 my ($dir, $file) = split_path($m->{file_b});
2241 my $pbat = $self->ensure_path($dir);
2242 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2243 undef, -1);
2244 print "\tA\t$m->{file_b}\n" unless $::_q;
2245 $self->chg_file($fbat, $m);
2246 $self->close_file($fbat,undef,$self->{pool});
2249 sub C {
2250 my ($self, $m) = @_;
2251 my ($dir, $file) = split_path($m->{file_b});
2252 my $pbat = $self->ensure_path($dir);
2253 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2254 $self->url_path($m->{file_a}), $self->{r});
2255 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2256 $self->chg_file($fbat, $m);
2257 $self->close_file($fbat,undef,$self->{pool});
2260 sub delete_entry {
2261 my ($self, $path, $pbat) = @_;
2262 my $rpath = $self->repo_path($path);
2263 my ($dir, $file) = split_path($rpath);
2264 $self->{rm}->{$dir} = 1;
2265 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2268 sub R {
2269 my ($self, $m) = @_;
2270 my ($dir, $file) = split_path($m->{file_b});
2271 my $pbat = $self->ensure_path($dir);
2272 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2273 $self->url_path($m->{file_a}), $self->{r});
2274 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2275 $self->chg_file($fbat, $m);
2276 $self->close_file($fbat,undef,$self->{pool});
2278 ($dir, $file) = split_path($m->{file_a});
2279 $pbat = $self->ensure_path($dir);
2280 $self->delete_entry($m->{file_a}, $pbat);
2283 sub M {
2284 my ($self, $m) = @_;
2285 my ($dir, $file) = split_path($m->{file_b});
2286 my $pbat = $self->ensure_path($dir);
2287 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2288 $pbat,$self->{r},$self->{pool});
2289 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2290 $self->chg_file($fbat, $m);
2291 $self->close_file($fbat,undef,$self->{pool});
2294 sub T { shift->M(@_) }
2296 sub change_file_prop {
2297 my ($self, $fbat, $pname, $pval) = @_;
2298 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2301 sub chg_file {
2302 my ($self, $fbat, $m) = @_;
2303 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2304 $self->change_file_prop($fbat,'svn:executable','*');
2305 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2306 $self->change_file_prop($fbat,'svn:executable',undef);
2308 my $fh = IO::File->new_tmpfile or croak $!;
2309 if ($m->{mode_b} =~ /^120/) {
2310 print $fh 'link ' or croak $!;
2311 $self->change_file_prop($fbat,'svn:special','*');
2312 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2313 $self->change_file_prop($fbat,'svn:special',undef);
2315 defined(my $pid = fork) or croak $!;
2316 if (!$pid) {
2317 open STDOUT, '>&', $fh or croak $!;
2318 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2320 waitpid $pid, 0;
2321 croak $? if $?;
2322 $fh->flush == 0 or croak $!;
2323 seek $fh, 0, 0 or croak $!;
2325 my $md5 = Digest::MD5->new;
2326 $md5->addfile($fh) or croak $!;
2327 seek $fh, 0, 0 or croak $!;
2329 my $exp = $md5->hexdigest;
2330 my $pool = SVN::Pool->new;
2331 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2332 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2333 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2334 $pool->clear;
2336 close $fh or croak $!;
2339 sub D {
2340 my ($self, $m) = @_;
2341 my ($dir, $file) = split_path($m->{file_b});
2342 my $pbat = $self->ensure_path($dir);
2343 print "\tD\t$m->{file_b}\n" unless $::_q;
2344 $self->delete_entry($m->{file_b}, $pbat);
2347 sub close_edit {
2348 my ($self) = @_;
2349 my ($p,$bat) = ($self->{pool}, $self->{bat});
2350 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2351 $self->close_directory($bat->{$_}, $p);
2353 $self->SUPER::close_edit($p);
2354 $p->clear;
2357 sub abort_edit {
2358 my ($self) = @_;
2359 $self->SUPER::abort_edit($self->{pool});
2362 sub DESTROY {
2363 my $self = shift;
2364 $self->SUPER::DESTROY(@_);
2365 $self->{pool}->clear;
2368 # this drives the editor
2369 sub apply_diff {
2370 my ($self) = @_;
2371 my $mods = $self->{mods};
2372 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2373 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2374 my $f = $m->{chg};
2375 if (defined $o{$f}) {
2376 $self->$f($m);
2377 } else {
2378 fatal("Invalid change type: $f\n");
2381 $self->rmdirs if $_rmdir;
2382 if (@$mods == 0) {
2383 $self->abort_edit;
2384 } else {
2385 $self->close_edit;
2387 return scalar @$mods;
2390 package Git::SVN::Ra;
2391 use vars qw/@ISA $config_dir/;
2392 use strict;
2393 use warnings;
2394 my ($can_do_switch);
2395 my $RA;
2397 BEGIN {
2398 # enforce temporary pool usage for some simple functions
2399 my $e;
2400 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2401 $e .= "sub $_ {
2402 my \$self = shift;
2403 my \$pool = SVN::Pool->new;
2404 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2405 \$pool->clear;
2406 wantarray ? \@ret : \$ret[0]; }\n";
2409 # get_dir needs $pool held in cache for dirents to work,
2410 # check_path is cacheable and rev_proplist is close enough
2411 # for our purposes.
2412 foreach (qw/check_path get_dir rev_proplist/) {
2413 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2414 my \$self = shift;
2415 my \$r = pop;
2416 my \$k = join(\"\\0\", \@_);
2417 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2418 return wantarray ? \@\$x : \$x->[0];
2420 my \$pool = SVN::Pool->new;
2421 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2422 if (\$r != \$${_}_rev) {
2423 \%${_}_cache = ( pool => [] );
2424 \$${_}_rev = \$r;
2426 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2427 push \@{\$${_}_cache{pool}}, \$pool;
2428 wantarray ? \@ret : \$ret[0]; }\n";
2430 $e .= "\n1;";
2431 eval $e or die $@;
2434 sub new {
2435 my ($class, $url) = @_;
2436 $url =~ s!/+$!!;
2437 return $RA if ($RA && $RA->{url} eq $url);
2439 SVN::_Core::svn_config_ensure($config_dir, undef);
2440 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2441 SVN::Client::get_simple_provider(),
2442 SVN::Client::get_ssl_server_trust_file_provider(),
2443 SVN::Client::get_simple_prompt_provider(
2444 \&Git::SVN::Prompt::simple, 2),
2445 SVN::Client::get_ssl_client_cert_prompt_provider(
2446 \&Git::SVN::Prompt::ssl_client_cert, 2),
2447 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2448 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2449 SVN::Client::get_username_provider(),
2450 SVN::Client::get_ssl_server_trust_prompt_provider(
2451 \&Git::SVN::Prompt::ssl_server_trust),
2452 SVN::Client::get_username_prompt_provider(
2453 \&Git::SVN::Prompt::username, 2),
2455 my $config = SVN::Core::config_get_config($config_dir);
2456 my $self = SVN::Ra->new(url => $url, auth => $baton,
2457 config => $config,
2458 pool => SVN::Pool->new,
2459 auth_provider_callbacks => $callbacks);
2460 $self->{svn_path} = $url;
2461 $self->{repos_root} = $self->get_repos_root;
2462 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2463 $RA = bless $self, $class;
2466 sub DESTROY {
2467 # do not call the real DESTROY since we store ourselves in $RA
2470 sub get_log {
2471 my ($self, @args) = @_;
2472 my $pool = SVN::Pool->new;
2473 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2474 my $ret = $self->SUPER::get_log(@args, $pool);
2475 $pool->clear;
2476 $ret;
2479 sub get_commit_editor {
2480 my ($self, $log, $cb, $pool) = @_;
2481 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2482 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2485 sub uuid {
2486 my ($self) = @_;
2487 $self->{uuid} ||= $self->get_uuid;
2490 sub gs_do_update {
2491 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2492 my $new = ($rev_a == $rev_b);
2493 my $path = $gs->{path};
2495 my $pool = SVN::Pool->new;
2496 $editor->set_path_strip($path);
2497 my (@pc) = split m#/#, $path;
2498 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2499 1, $editor, $pool);
2500 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2502 # Since we can't rely on svn_ra_reparent being available, we'll
2503 # just have to do some magic with set_path to make it so
2504 # we only want a partial path.
2505 my $sp = '';
2506 my $final = join('/', @pc);
2507 while (@pc) {
2508 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2509 $sp .= '/' if length $sp;
2510 $sp .= shift @pc;
2512 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2514 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2516 $reporter->finish_report($pool);
2517 $pool->clear;
2518 $editor->{git_commit_ok};
2521 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2522 # svn_ra_reparent didn't work before 1.4)
2523 sub gs_do_switch {
2524 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2525 my $path = $gs->{path};
2526 my $pool = SVN::Pool->new;
2528 my $full_url = $self->{url};
2529 my $old_url = $full_url;
2530 $full_url .= "/$path" if length $path;
2531 my ($ra, $reparented);
2532 if ($old_url ne $full_url) {
2533 if ($old_url !~ m#^svn(\+ssh)?://#) {
2534 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2535 $pool);
2536 $self->{url} = $full_url;
2537 $reparented = 1;
2538 } else {
2539 $ra = Git::SVN::Ra->new($full_url);
2542 $ra ||= $self;
2543 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2544 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2545 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2546 $reporter->finish_report($pool);
2548 if ($reparented) {
2549 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2550 $self->{url} = $old_url;
2553 $pool->clear;
2554 $editor->{git_commit_ok};
2557 sub gs_fetch_loop_common {
2558 my ($self, $base, $head, $gsv, $globs) = @_;
2559 return if ($base > $head);
2560 my $inc = 1000;
2561 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2562 my %common;
2563 my $common_max = scalar @$gsv;
2565 foreach my $gs (@$gsv) {
2566 if (my $last_commit = $gs->last_commit) {
2567 $gs->assert_index_clean($last_commit);
2569 my @tmp = split m#/#, $gs->{path};
2570 my $p = '';
2571 foreach (@tmp) {
2572 $p .= length($p) ? "/$_" : $_;
2573 $common{$p} ||= 0;
2574 $common{$p}++;
2577 $globs ||= [];
2578 $common_max += scalar @$globs;
2579 foreach my $glob (@$globs) {
2580 my @tmp = split m#/#, $glob->{path}->{left};
2581 my $p = '';
2582 foreach (@tmp) {
2583 $p .= length($p) ? "/$_" : $_;
2584 $common{$p} ||= 0;
2585 $common{$p}++;
2589 my $longest_path = '';
2590 foreach (sort {length $b <=> length $a} keys %common) {
2591 if ($common{$_} == $common_max) {
2592 $longest_path = $_;
2593 last;
2596 while (1) {
2597 my %revs;
2598 my $err;
2599 my $err_handler = $SVN::Error::handler;
2600 $SVN::Error::handler = sub {
2601 ($err) = @_;
2602 skip_unknown_revs($err);
2604 sub _cb {
2605 my ($paths, $r, $author, $date, $log) = @_;
2606 [ dup_changed_paths($paths),
2607 { author => $author, date => $date, log => $log } ];
2609 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2610 sub { $revs{$_[1]} = _cb(@_) });
2611 if ($err && $max >= $head) {
2612 print STDERR "Path '$longest_path' ",
2613 "was probably deleted:\n",
2614 $err->expanded_message,
2615 "\nWill attempt to follow ",
2616 "revisions r$min .. r$max ",
2617 "committed before the deletion\n";
2618 my $hi = $max;
2619 while (--$hi >= $min) {
2620 my $ok;
2621 $self->get_log([$longest_path], $min, $hi,
2622 0, 1, 1, sub {
2623 $ok ||= $_[1];
2624 $revs{$_[1]} = _cb(@_) });
2625 if ($ok) {
2626 print STDERR "r$min .. r$ok OK\n";
2627 last;
2631 $SVN::Error::handler = $err_handler;
2633 my %exists = map { $_->{path} => $_ } @$gsv;
2634 foreach my $r (sort {$a <=> $b} keys %revs) {
2635 my ($paths, $logged) = @{$revs{$r}};
2637 foreach my $gs ($self->match_globs(\%exists, $paths,
2638 $globs, $r)) {
2639 if ($gs->rev_db_max >= $r) {
2640 next;
2642 next unless $gs->match_paths($paths, $r);
2643 $gs->{logged_rev_props} = $logged;
2644 my $log_entry = $gs->do_fetch($paths, $r);
2645 if ($log_entry) {
2646 $gs->do_git_commit($log_entry);
2649 foreach my $g (@$globs) {
2650 my $f = "$ENV{GIT_DIR}/svn/." .
2651 $self->uuid . ".$g->{t}";
2652 open my $fh, '>', "$f.tmp" or
2653 die "Can't open $f.tmp for writing: $!";
2654 print $fh "$r\n" or
2655 die "Couldn't write to $f: $!\n";
2656 close $fh or die "Error closing $f: $!\n";
2657 rename "$f.tmp", $f or
2658 die "Couldn't rename ",
2659 "$f.tmp => $f: $!\n";
2662 # pre-fill the .rev_db since it'll eventually get filled in
2663 # with '0' x40 if something new gets committed
2664 foreach my $gs (@$gsv) {
2665 next if defined $gs->rev_db_get($max);
2666 $gs->rev_db_set($max, 0 x40);
2668 last if $max >= $head;
2669 $min = $max + 1;
2670 $max += $inc;
2671 $max = $head if ($max > $head);
2675 sub match_globs {
2676 my ($self, $exists, $paths, $globs, $r) = @_;
2678 sub get_dir_check {
2679 my ($self, $exists, $g, $r) = @_;
2680 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2681 return unless scalar @x == 3;
2682 my $dirents = $x[0];
2683 foreach my $de (keys %$dirents) {
2684 next if $dirents->{$de}->kind != $SVN::Node::dir;
2685 my $p = $g->{path}->full_path($de);
2686 next if $exists->{$p};
2687 next if (length $g->{path}->{right} &&
2688 ($self->check_path($p, $r) !=
2689 $SVN::Node::dir));
2690 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
2691 $g->{ref}->full_path($de), 1);
2694 foreach my $g (@$globs) {
2695 if (my $path = $paths->{"/$g->{path}->{left}"}) {
2696 if ($path->{action} =~ /^[AR]$/) {
2697 get_dir_check($self, $exists, $g, $r);
2700 foreach (keys %$paths) {
2701 if (/$g->{path}->{left_regex}/) {
2702 next if $paths->{$_}->{action} !~ /^[AR]$/;
2703 get_dir_check($self, $exists, $g, $r);
2705 next unless /$g->{path}->{regex}/;
2706 my $p = $1;
2707 my $pathname = $g->{path}->full_path($p);
2708 next if $exists->{$pathname};
2709 $exists->{$pathname} = Git::SVN->init(
2710 $self->{url}, $pathname, undef,
2711 $g->{ref}->full_path($p), 1);
2713 my $c = '';
2714 foreach (split m#/#, $g->{path}->{left}) {
2715 $c .= "/$_";
2716 next unless ($paths->{$c} &&
2717 ($paths->{$c}->{action} =~ /^[AR]$/));
2718 get_dir_check($self, $exists, $g, $r);
2721 values %$exists;
2724 sub minimize_url {
2725 my ($self) = @_;
2726 return $self->{url} if ($self->{url} eq $self->{repos_root});
2727 my $url = $self->{repos_root};
2728 my @components = split(m!/!, $self->{svn_path});
2729 my $c = '';
2730 do {
2731 $url .= "/$c" if length $c;
2732 eval { (ref $self)->new($url)->get_latest_revnum };
2733 } while ($@ && ($c = shift @components));
2734 $url;
2737 sub can_do_switch {
2738 my $self = shift;
2739 unless (defined $can_do_switch) {
2740 my $pool = SVN::Pool->new;
2741 my $rep = eval {
2742 $self->do_switch(1, '', 0, $self->{url},
2743 SVN::Delta::Editor->new, $pool);
2745 if ($@) {
2746 $can_do_switch = 0;
2747 } else {
2748 $rep->abort_report($pool);
2749 $can_do_switch = 1;
2751 $pool->clear;
2753 $can_do_switch;
2756 sub skip_unknown_revs {
2757 my ($err) = @_;
2758 my $errno = $err->apr_err();
2759 # Maybe the branch we're tracking didn't
2760 # exist when the repo started, so it's
2761 # not an error if it doesn't, just continue
2763 # Wonderfully consistent library, eh?
2764 # 160013 - svn:// and file://
2765 # 175002 - http(s)://
2766 # 175007 - http(s):// (this repo required authorization, too...)
2767 # More codes may be discovered later...
2768 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2769 return;
2771 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2774 # svn_log_changed_path_t objects passed to get_log are likely to be
2775 # overwritten even if only the refs are copied to an external variable,
2776 # so we should dup the structures in their entirety. Using an externally
2777 # passed pool (instead of our temporary and quickly cleared pool in
2778 # Git::SVN::Ra) does not help matters at all...
2779 sub dup_changed_paths {
2780 my ($paths) = @_;
2781 return undef unless $paths;
2782 my %ret;
2783 foreach my $p (keys %$paths) {
2784 my $i = $paths->{$p};
2785 my %s = map { $_ => $i->$_ }
2786 qw/copyfrom_path copyfrom_rev action/;
2787 $ret{$p} = \%s;
2789 \%ret;
2792 package Git::SVN::Log;
2793 use strict;
2794 use warnings;
2795 use POSIX qw/strftime/;
2796 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2797 %rusers $show_commit $incremental/;
2798 my $l_fmt;
2800 sub cmt_showable {
2801 my ($c) = @_;
2802 return 1 if defined $c->{r};
2803 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2804 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2805 my @log = command(qw/cat-file commit/, $c->{c});
2806 shift @log while ($log[0] ne "\n");
2807 shift @log;
2808 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2810 (undef, $c->{r}, undef) = ::extract_metadata(
2811 (grep(/^git-svn-id: /, @log))[-1]);
2813 return defined $c->{r};
2816 sub log_use_color {
2817 return 1 if $color;
2818 my ($dc, $dcvar);
2819 $dcvar = 'color.diff';
2820 $dc = `git-config --get $dcvar`;
2821 if ($dc eq '') {
2822 # nothing at all; fallback to "diff.color"
2823 $dcvar = 'diff.color';
2824 $dc = `git-config --get $dcvar`;
2826 chomp($dc);
2827 if ($dc eq 'auto') {
2828 my $pc;
2829 $pc = `git-config --get color.pager`;
2830 if ($pc eq '') {
2831 # does not have it -- fallback to pager.color
2832 $pc = `git-config --bool --get pager.color`;
2834 else {
2835 $pc = `git-config --bool --get color.pager`;
2836 if ($?) {
2837 $pc = 'false';
2840 chomp($pc);
2841 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2842 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2844 return 0;
2846 return 0 if $dc eq 'never';
2847 return 1 if $dc eq 'always';
2848 chomp($dc = `git-config --bool --get $dcvar`);
2849 return ($dc eq 'true');
2852 sub git_svn_log_cmd {
2853 my ($r_min, $r_max) = @_;
2854 my $gs = Git::SVN->_new;
2855 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2856 $gs->refname);
2857 push @cmd, '-r' unless $non_recursive;
2858 push @cmd, qw/--raw --name-status/ if $verbose;
2859 push @cmd, '--color' if log_use_color();
2860 return @cmd unless defined $r_max;
2861 if ($r_max == $r_min) {
2862 push @cmd, '--max-count=1';
2863 if (my $c = $gs->rev_db_get($r_max)) {
2864 push @cmd, $c;
2866 } else {
2867 my ($c_min, $c_max);
2868 $c_max = $gs->rev_db_get($r_max);
2869 $c_min = $gs->rev_db_get($r_min);
2870 if (defined $c_min && defined $c_max) {
2871 if ($r_max > $r_max) {
2872 push @cmd, "$c_min..$c_max";
2873 } else {
2874 push @cmd, "$c_max..$c_min";
2876 } elsif ($r_max > $r_min) {
2877 push @cmd, $c_max;
2878 } else {
2879 push @cmd, $c_min;
2882 return @cmd;
2885 # adapted from pager.c
2886 sub config_pager {
2887 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2888 if (!defined $pager) {
2889 $pager = 'less';
2890 } elsif (length $pager == 0 || $pager eq 'cat') {
2891 $pager = undef;
2895 sub run_pager {
2896 return unless -t *STDOUT;
2897 pipe my $rfd, my $wfd or return;
2898 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2899 if (!$pid) {
2900 open STDOUT, '>&', $wfd or
2901 ::fatal "Can't redirect to stdout: $!\n";
2902 return;
2904 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2905 $ENV{LESS} ||= 'FRSX';
2906 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2909 sub tz_to_s_offset {
2910 my ($tz) = @_;
2911 $tz =~ s/(\d\d)$//;
2912 return ($1 * 60) + ($tz * 3600);
2915 sub get_author_info {
2916 my ($dest, $author, $t, $tz) = @_;
2917 $author =~ s/(?:^\s*|\s*$)//g;
2918 $dest->{a_raw} = $author;
2919 my $au;
2920 if ($::_authors) {
2921 $au = $rusers{$author} || undef;
2923 if (!$au) {
2924 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2926 $dest->{t} = $t;
2927 $dest->{tz} = $tz;
2928 $dest->{a} = $au;
2929 # Date::Parse isn't in the standard Perl distro :(
2930 if ($tz =~ s/^\+//) {
2931 $t += tz_to_s_offset($tz);
2932 } elsif ($tz =~ s/^\-//) {
2933 $t -= tz_to_s_offset($tz);
2935 $dest->{t_utc} = $t;
2938 sub process_commit {
2939 my ($c, $r_min, $r_max, $defer) = @_;
2940 if (defined $r_min && defined $r_max) {
2941 if ($r_min == $c->{r} && $r_min == $r_max) {
2942 show_commit($c);
2943 return 0;
2945 return 1 if $r_min == $r_max;
2946 if ($r_min < $r_max) {
2947 # we need to reverse the print order
2948 return 0 if (defined $limit && --$limit < 0);
2949 push @$defer, $c;
2950 return 1;
2952 if ($r_min != $r_max) {
2953 return 1 if ($r_min < $c->{r});
2954 return 1 if ($r_max > $c->{r});
2957 return 0 if (defined $limit && --$limit < 0);
2958 show_commit($c);
2959 return 1;
2962 sub show_commit {
2963 my $c = shift;
2964 if ($oneline) {
2965 my $x = "\n";
2966 if (my $l = $c->{l}) {
2967 while ($l->[0] =~ /^\s*$/) { shift @$l }
2968 $x = $l->[0];
2970 $l_fmt ||= 'A' . length($c->{r});
2971 print 'r',pack($l_fmt, $c->{r}),' | ';
2972 print "$c->{c} | " if $show_commit;
2973 print $x;
2974 } else {
2975 show_commit_normal($c);
2979 sub show_commit_changed_paths {
2980 my ($c) = @_;
2981 return unless $c->{changed};
2982 print "Changed paths:\n", @{$c->{changed}};
2985 sub show_commit_normal {
2986 my ($c) = @_;
2987 print '-' x72, "\nr$c->{r} | ";
2988 print "$c->{c} | " if $show_commit;
2989 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2990 localtime($c->{t_utc})), ' | ';
2991 my $nr_line = 0;
2993 if (my $l = $c->{l}) {
2994 while ($l->[$#$l] eq "\n" && $#$l > 0
2995 && $l->[($#$l - 1)] eq "\n") {
2996 pop @$l;
2998 $nr_line = scalar @$l;
2999 if (!$nr_line) {
3000 print "1 line\n\n\n";
3001 } else {
3002 if ($nr_line == 1) {
3003 $nr_line = '1 line';
3004 } else {
3005 $nr_line .= ' lines';
3007 print $nr_line, "\n";
3008 show_commit_changed_paths($c);
3009 print "\n";
3010 print $_ foreach @$l;
3012 } else {
3013 print "1 line\n";
3014 show_commit_changed_paths($c);
3015 print "\n";
3018 foreach my $x (qw/raw diff/) {
3019 if ($c->{$x}) {
3020 print "\n";
3021 print $_ foreach @{$c->{$x}}
3026 sub cmd_show_log {
3027 my (@args) = @_;
3028 my ($r_min, $r_max);
3029 my $r_last = -1; # prevent dupes
3030 if (defined $TZ) {
3031 $ENV{TZ} = $TZ;
3032 } else {
3033 delete $ENV{TZ};
3035 if (defined $::_revision) {
3036 if ($::_revision =~ /^(\d+):(\d+)$/) {
3037 ($r_min, $r_max) = ($1, $2);
3038 } elsif ($::_revision =~ /^\d+$/) {
3039 $r_min = $r_max = $::_revision;
3040 } else {
3041 ::fatal "-r$::_revision is not supported, use ",
3042 "standard \'git log\' arguments instead\n";
3046 config_pager();
3047 @args = (git_svn_log_cmd($r_min, $r_max), @args);
3048 my $log = command_output_pipe(@args);
3049 run_pager();
3050 my (@k, $c, $d);
3051 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3052 while (<$log>) {
3053 if (/^${esc_color}commit ($::sha1_short)/o) {
3054 my $cmt = $1;
3055 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3056 $r_last = $c->{r};
3057 process_commit($c, $r_min, $r_max, \@k) or
3058 goto out;
3060 $d = undef;
3061 $c = { c => $cmt };
3062 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3063 get_author_info($c, $1, $2, $3);
3064 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3065 # ignore
3066 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3067 push @{$c->{raw}}, $_;
3068 } elsif (/^${esc_color}[ACRMDT]\t/) {
3069 # we could add $SVN->{svn_path} here, but that requires
3070 # remote access at the moment (repo_path_split)...
3071 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3072 push @{$c->{changed}}, $_;
3073 } elsif (/^${esc_color}diff /o) {
3074 $d = 1;
3075 push @{$c->{diff}}, $_;
3076 } elsif ($d) {
3077 push @{$c->{diff}}, $_;
3078 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3079 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3080 } elsif (s/^${esc_color} //o) {
3081 push @{$c->{l}}, $_;
3084 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3085 $r_last = $c->{r};
3086 process_commit($c, $r_min, $r_max, \@k);
3088 if (@k) {
3089 my $swap = $r_max;
3090 $r_max = $r_min;
3091 $r_min = $swap;
3092 process_commit($_, $r_min, $r_max) foreach reverse @k;
3094 out:
3095 close $log;
3096 print '-' x72,"\n" unless $incremental || $oneline;
3099 package Git::SVN::Migration;
3100 # these version numbers do NOT correspond to actual version numbers
3101 # of git nor git-svn. They are just relative.
3103 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3105 # v1 layout: .git/$id/info/url, refs/remotes/$id
3107 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3109 # v3 layout: .git/svn/$id, refs/remotes/$id
3110 # - info/url may remain for backwards compatibility
3111 # - this is what we migrate up to this layout automatically,
3112 # - this will be used by git svn init on single branches
3114 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3115 # - this is only created for newly multi-init-ed
3116 # repositories. Similar in spirit to the
3117 # --use-separate-remotes option in git-clone (now default)
3118 # - we do not automatically migrate to this (following
3119 # the example set by core git)
3120 use strict;
3121 use warnings;
3122 use Carp qw/croak/;
3123 use File::Path qw/mkpath/;
3124 use File::Basename qw/dirname basename/;
3125 use vars qw/$_minimize/;
3127 sub migrate_from_v0 {
3128 my $git_dir = $ENV{GIT_DIR};
3129 return undef unless -d $git_dir;
3130 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3131 my $migrated = 0;
3132 while (<$fh>) {
3133 chomp;
3134 my ($id, $orig_ref) = ($_, $_);
3135 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3136 next unless -f "$git_dir/$id/info/url";
3137 my $new_ref = "refs/remotes/$id";
3138 if (::verify_ref("$new_ref^0")) {
3139 print STDERR "W: $orig_ref is probably an old ",
3140 "branch used by an ancient version of ",
3141 "git-svn.\n",
3142 "However, $new_ref also exists.\n",
3143 "We will not be able ",
3144 "to use this branch until this ",
3145 "ambiguity is resolved.\n";
3146 next;
3148 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3149 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3150 command_noisy('update-ref', $new_ref, $orig_ref);
3151 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3152 $migrated++;
3154 command_close_pipe($fh, $ctx);
3155 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3156 $migrated;
3159 sub migrate_from_v1 {
3160 my $git_dir = $ENV{GIT_DIR};
3161 my $migrated = 0;
3162 return $migrated unless -d $git_dir;
3163 my $svn_dir = "$git_dir/svn";
3165 # just in case somebody used 'svn' as their $id at some point...
3166 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3168 print STDERR "Migrating from a git-svn v1 layout...\n";
3169 mkpath([$svn_dir]);
3170 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3171 "$svn_dir\n\t(required for this version ",
3172 "($::VERSION) of git-svn) does not. exist\n";
3173 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3174 while (<$fh>) {
3175 my $x = $_;
3176 next unless $x =~ s#^refs/remotes/##;
3177 chomp $x;
3178 next unless -f "$git_dir/$x/info/url";
3179 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3180 next unless $u;
3181 my $dn = dirname("$git_dir/svn/$x");
3182 mkpath([$dn]) unless -d $dn;
3183 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3184 mkpath(["$git_dir/svn/svn"]);
3185 print STDERR " - $git_dir/$x/info => ",
3186 "$git_dir/svn/$x/info\n";
3187 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3188 croak "$!: $x";
3189 # don't worry too much about these, they probably
3190 # don't exist with repos this old (save for index,
3191 # and we can easily regenerate that)
3192 foreach my $f (qw/unhandled.log index .rev_db/) {
3193 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3195 } else {
3196 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3197 rename "$git_dir/$x", "$git_dir/svn/$x" or
3198 croak "$!: $x";
3200 $migrated++;
3202 command_close_pipe($fh, $ctx);
3203 print STDERR "Done migrating from a git-svn v1 layout\n";
3204 $migrated;
3207 sub read_old_urls {
3208 my ($l_map, $pfx, $path) = @_;
3209 my @dir;
3210 foreach (<$path/*>) {
3211 if (-r "$_/info/url") {
3212 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3213 my $ref_id = $pfx . basename $_;
3214 my $url = ::file_to_s("$_/info/url");
3215 $l_map->{$ref_id} = $url;
3216 } elsif (-d $_) {
3217 push @dir, $_;
3220 foreach (@dir) {
3221 my $x = $_;
3222 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3223 read_old_urls($l_map, $x, $_);
3227 sub migrate_from_v2 {
3228 my @cfg = command(qw/config -l/);
3229 return if grep /^svn-remote\..+\.url=/, @cfg;
3230 my %l_map;
3231 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3232 my $migrated = 0;
3234 foreach my $ref_id (sort keys %l_map) {
3235 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3236 if ($@) {
3237 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3239 $migrated++;
3241 $migrated;
3244 sub minimize_connections {
3245 my $r = Git::SVN::read_all_remotes();
3246 my $new_urls = {};
3247 my $root_repos = {};
3248 foreach my $repo_id (keys %$r) {
3249 my $url = $r->{$repo_id}->{url} or next;
3250 my $fetch = $r->{$repo_id}->{fetch} or next;
3251 my $ra = Git::SVN::Ra->new($url);
3253 # skip existing cases where we already connect to the root
3254 if (($ra->{url} eq $ra->{repos_root}) ||
3255 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3256 $repo_id)) {
3257 $root_repos->{$ra->{url}} = $repo_id;
3258 next;
3261 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3262 my $root_path = $ra->{url};
3263 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3264 foreach my $path (keys %$fetch) {
3265 my $ref_id = $fetch->{$path};
3266 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3268 # make sure we can read when connecting to
3269 # a higher level of a repository
3270 my ($last_rev, undef) = $gs->last_rev_commit;
3271 if (!defined $last_rev) {
3272 $last_rev = eval {
3273 $root_ra->get_latest_revnum;
3275 next if $@;
3277 my $new = $root_path;
3278 $new .= length $path ? "/$path" : '';
3279 eval {
3280 $root_ra->get_log([$new], $last_rev, $last_rev,
3281 0, 0, 1, sub { });
3283 next if $@;
3284 $new_urls->{$ra->{repos_root}}->{$new} =
3285 { ref_id => $ref_id,
3286 old_repo_id => $repo_id,
3287 old_path => $path };
3291 my @emptied;
3292 foreach my $url (keys %$new_urls) {
3293 # see if we can re-use an existing [svn-remote "repo_id"]
3294 # instead of creating a(n ugly) new section:
3295 my $repo_id = $root_repos->{$url} ||
3296 Git::SVN::sanitize_remote_name($url);
3298 my $fetch = $new_urls->{$url};
3299 foreach my $path (keys %$fetch) {
3300 my $x = $fetch->{$path};
3301 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3302 my $pfx = "svn-remote.$x->{old_repo_id}";
3304 my $old_fetch = quotemeta("$x->{old_path}:".
3305 "refs/remotes/$x->{ref_id}");
3306 command_noisy(qw/config --unset/,
3307 "$pfx.fetch", '^'. $old_fetch . '$');
3308 delete $r->{$x->{old_repo_id}}->
3309 {fetch}->{$x->{old_path}};
3310 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3311 command_noisy(qw/config --unset/,
3312 "$pfx.url");
3313 push @emptied, $x->{old_repo_id}
3317 if (@emptied) {
3318 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3319 "$ENV{GIT_DIR}/config";
3320 print STDERR <<EOF;
3321 The following [svn-remote] sections in your config file ($file) are empty
3322 and can be safely removed:
3324 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3328 sub migration_check {
3329 migrate_from_v0();
3330 migrate_from_v1();
3331 migrate_from_v2();
3332 minimize_connections() if $_minimize;
3335 package Git::IndexInfo;
3336 use strict;
3337 use warnings;
3338 use Git qw/command_input_pipe command_close_pipe/;
3340 sub new {
3341 my ($class) = @_;
3342 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3343 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3346 sub remove {
3347 my ($self, $path) = @_;
3348 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3349 return ++$self->{nr};
3351 undef;
3354 sub update {
3355 my ($self, $mode, $hash, $path) = @_;
3356 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3357 return ++$self->{nr};
3359 undef;
3362 sub DESTROY {
3363 my ($self) = @_;
3364 command_close_pipe($self->{gui}, $self->{ctx});
3367 package Git::SVN::GlobSpec;
3368 use strict;
3369 use warnings;
3371 sub new {
3372 my ($class, $glob) = @_;
3373 my $re = $glob;
3374 $re =~ s!/+$!!g; # no need for trailing slashes
3375 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3376 my ($left, $right) = ($1, $2);
3377 if ($nr > 1) {
3378 die "Only one '*' wildcard expansion ",
3379 "is supported (got $nr): '$glob'\n";
3380 } elsif ($nr == 0) {
3381 die "One '*' is needed for glob: '$glob'\n";
3383 $re = quotemeta($left) . $re . quotemeta($right);
3384 if (length $left && !($left =~ s!/+$!!g)) {
3385 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3387 if (length $right && !($right =~ s!^/+!!g)) {
3388 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3390 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3391 bless { left => $left, right => $right, left_regex => $left_re,
3392 regex => qr/$re/, glob => $glob }, $class;
3395 sub full_path {
3396 my ($self, $path) = @_;
3397 return (length $self->{left} ? "$self->{left}/" : '') .
3398 $path . (length $self->{right} ? "/$self->{right}" : '');
3401 __END__
3403 Data structures:
3406 $remotes = { # returned by read_all_remotes()
3407 'svn' => {
3408 # svn-remote.svn.url=https://svn.musicpd.org
3409 url => 'https://svn.musicpd.org',
3410 # svn-remote.svn.fetch=mpd/trunk:trunk
3411 fetch => {
3412 'mpd/trunk' => 'trunk',
3414 # svn-remote.svn.tags=mpd/tags/*:tags/*
3415 tags => {
3416 path => {
3417 left => 'mpd/tags',
3418 right => '',
3419 regex => qr!mpd/tags/([^/]+)$!,
3420 glob => 'tags/*',
3422 ref => {
3423 left => 'tags',
3424 right => '',
3425 regex => qr!tags/([^/]+)$!,
3426 glob => 'tags/*',
3432 $log_entry hashref as returned by libsvn_log_entry()
3434 log => 'whitespace-formatted log entry
3435 ', # trailing newline is preserved
3436 revision => '8', # integer
3437 date => '2004-02-24T17:01:44.108345Z', # commit date
3438 author => 'committer name'
3442 # this is generated by generate_diff();
3443 @mods = array of diff-index line hashes, each element represents one line
3444 of diff-index output
3446 diff-index line ($m hash)
3448 mode_a => first column of diff-index output, no leading ':',
3449 mode_b => second column of diff-index output,
3450 sha1_b => sha1sum of the final blob,
3451 chg => change type [MCRADT],
3452 file_a => original file name of a file (iff chg is 'C' or 'R')
3453 file_b => new/current file name of a file (any chg)
3457 # retval of read_url_paths{,_all}();
3458 $l_map = {
3459 # repository root url
3460 'https://svn.musicpd.org' => {
3461 # repository path # GIT_SVN_ID
3462 'mpd/trunk' => 'trunk',
3463 'mpd/tags/0.11.5' => 'tags/0.11.5',
3467 Notes:
3468 I don't trust the each() function on unless I created %hash myself
3469 because the internal iterator may not have started at base.