git-svn: t9114: verify merge commit message in test
[git/kirr.git] / git-svn.perl
blobec25ea4231a062e05753f4f93a757a41062a0364
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 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41 # import functions from Git into our packages, en masse
42 no strict 'refs';
43 foreach (qw/command command_oneline command_noisy command_output_pipe
44 command_input_pipe command_close_pipe/) {
45 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
46 Git::SVN::Migration Git::SVN::Log Git::SVN),
47 __PACKAGE__) {
48 *{"${package}::$_"} = \&{"Git::$_"};
53 my ($SVN);
55 $sha1 = qr/[a-f\d]{40}/;
56 $sha1_short = qr/[a-f\d]{4,40}/;
57 my ($_stdin, $_help, $_edit,
58 $_message, $_file,
59 $_template, $_shared,
60 $_version, $_fetch_all, $_no_rebase,
61 $_merge, $_strategy, $_dry_run, $_local,
62 $_prefix, $_no_checkout, $_verbose);
63 $Git::SVN::_follow_parent = 1;
64 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
65 'config-dir=s' => \$Git::SVN::Ra::config_dir,
66 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
67 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
68 'authors-file|A=s' => \$_authors,
69 'repack:i' => \$Git::SVN::_repack,
70 'noMetadata' => \$Git::SVN::_no_metadata,
71 'useSvmProps' => \$Git::SVN::_use_svm_props,
72 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
73 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
74 'no-checkout' => \$_no_checkout,
75 'quiet|q' => \$_q,
76 'repack-flags|repack-args|repack-opts=s' =>
77 \$Git::SVN::_repack_flags,
78 %remote_opts );
80 my ($_trunk, $_tags, $_branches, $_stdlayout);
81 my %icv;
82 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
83 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
84 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
85 'stdlayout|s' => \$_stdlayout,
86 'minimize-url|m' => \$Git::SVN::_minimize_url,
87 'no-metadata' => sub { $icv{noMetadata} = 1 },
88 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
89 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
90 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
91 %remote_opts );
92 my %cmt_opts = ( 'edit|e' => \$_edit,
93 'rmdir' => \$SVN::Git::Editor::_rmdir,
94 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
95 'l=i' => \$SVN::Git::Editor::_rename_limit,
96 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
99 my %cmd = (
100 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
101 { 'revision|r=s' => \$_revision,
102 'fetch-all|all' => \$_fetch_all,
103 %fc_opts } ],
104 clone => [ \&cmd_clone, "Initialize and fetch revisions",
105 { 'revision|r=s' => \$_revision,
106 %fc_opts, %init_opts } ],
107 init => [ \&cmd_init, "Initialize a repo for tracking" .
108 " (requires URL argument)",
109 \%init_opts ],
110 'multi-init' => [ \&cmd_multi_init,
111 "Deprecated alias for ".
112 "'$0 init -T<trunk> -b<branches> -t<tags>'",
113 \%init_opts ],
114 dcommit => [ \&cmd_dcommit,
115 'Commit several diffs to merge with upstream',
116 { 'merge|m|M' => \$_merge,
117 'strategy|s=s' => \$_strategy,
118 'verbose|v' => \$_verbose,
119 'dry-run|n' => \$_dry_run,
120 'fetch-all|all' => \$_fetch_all,
121 'no-rebase' => \$_no_rebase,
122 %cmt_opts, %fc_opts } ],
123 'set-tree' => [ \&cmd_set_tree,
124 "Set an SVN repository to a git tree-ish",
125 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
126 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
127 { 'revision|r=i' => \$_revision } ],
128 'multi-fetch' => [ \&cmd_multi_fetch,
129 "Deprecated alias for $0 fetch --all",
130 { 'revision|r=s' => \$_revision, %fc_opts } ],
131 'migrate' => [ sub { },
132 # no-op, we automatically run this anyways,
133 'Migrate configuration/metadata/layout from
134 previous versions of git-svn',
135 { 'minimize' => \$Git::SVN::Migration::_minimize,
136 %remote_opts } ],
137 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
138 { 'limit=i' => \$Git::SVN::Log::limit,
139 'revision|r=s' => \$_revision,
140 'verbose|v' => \$Git::SVN::Log::verbose,
141 'incremental' => \$Git::SVN::Log::incremental,
142 'oneline' => \$Git::SVN::Log::oneline,
143 'show-commit' => \$Git::SVN::Log::show_commit,
144 'non-recursive' => \$Git::SVN::Log::non_recursive,
145 'authors-file|A=s' => \$_authors,
146 'color' => \$Git::SVN::Log::color,
147 'pager=s' => \$Git::SVN::Log::pager,
148 } ],
149 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
150 { } ],
151 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
152 { 'merge|m|M' => \$_merge,
153 'verbose|v' => \$_verbose,
154 'strategy|s=s' => \$_strategy,
155 'local|l' => \$_local,
156 'fetch-all|all' => \$_fetch_all,
157 %fc_opts } ],
158 'commit-diff' => [ \&cmd_commit_diff,
159 'Commit a diff between two trees',
160 { 'message|m=s' => \$_message,
161 'file|F=s' => \$_file,
162 'revision|r=s' => \$_revision,
163 %cmt_opts } ],
166 my $cmd;
167 for (my $i = 0; $i < @ARGV; $i++) {
168 if (defined $cmd{$ARGV[$i]}) {
169 $cmd = $ARGV[$i];
170 splice @ARGV, $i, 1;
171 last;
175 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
177 read_repo_config(\%opts);
178 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
180 'minimize-connections' => \$Git::SVN::Migration::_minimize,
181 'id|i=s' => \$Git::SVN::default_ref_id,
182 'svn-remote|remote|R=s' => sub {
183 $Git::SVN::no_reuse_existing = 1;
184 $Git::SVN::default_repo_id = $_[1] });
185 exit 1 if (!$rv && $cmd && $cmd ne 'log');
187 usage(0) if $_help;
188 version() if $_version;
189 usage(1) unless defined $cmd;
190 load_authors() if $_authors;
192 # make sure we're always running
193 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
194 unless (-d $ENV{GIT_DIR}) {
195 if ($git_dir_user_set) {
196 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
197 "but it is not a directory\n";
199 my $git_dir = delete $ENV{GIT_DIR};
200 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
201 unless (length $cdup) {
202 die "Already at toplevel, but $git_dir ",
203 "not found '$cdup'\n";
205 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
206 unless (-d $git_dir) {
207 die "$git_dir still not found after going to ",
208 "'$cdup'\n";
210 $ENV{GIT_DIR} = $git_dir;
213 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
214 Git::SVN::Migration::migration_check();
216 Git::SVN::init_vars();
217 eval {
218 Git::SVN::verify_remotes_sanity();
219 $cmd{$cmd}->[0]->(@ARGV);
221 fatal $@ if $@;
222 post_fetch_checkout();
223 exit 0;
225 ####################### primary functions ######################
226 sub usage {
227 my $exit = shift || 0;
228 my $fd = $exit ? \*STDERR : \*STDOUT;
229 print $fd <<"";
230 git-svn - bidirectional operations between a single Subversion tree and git
231 Usage: $0 <command> [options] [arguments]\n
233 print $fd "Available commands:\n" unless $cmd;
235 foreach (sort keys %cmd) {
236 next if $cmd && $cmd ne $_;
237 next if /^multi-/; # don't show deprecated commands
238 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
239 foreach (keys %{$cmd{$_}->[2]}) {
240 # mixed-case options are for .git/config only
241 next if /[A-Z]/ && /^[a-z]+$/i;
242 # prints out arguments as they should be passed:
243 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
244 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
245 "--$_" : "-$_" }
246 split /\|/,$_)," $x\n";
249 print $fd <<"";
250 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
251 arbitrary identifier if you're tracking multiple SVN branches/repositories in
252 one git repository and want to keep them separate. See git-svn(1) for more
253 information.
255 exit $exit;
258 sub version {
259 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
260 exit 0;
263 sub do_git_init_db {
264 unless (-d $ENV{GIT_DIR}) {
265 my @init_db = ('init');
266 push @init_db, "--template=$_template" if defined $_template;
267 if (defined $_shared) {
268 if ($_shared =~ /[a-z]/) {
269 push @init_db, "--shared=$_shared";
270 } else {
271 push @init_db, "--shared";
274 command_noisy(@init_db);
276 my $set;
277 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
278 foreach my $i (keys %icv) {
279 die "'$set' and '$i' cannot both be set\n" if $set;
280 next unless defined $icv{$i};
281 command_noisy('config', "$pfx.$i", $icv{$i});
282 $set = $i;
286 sub init_subdir {
287 my $repo_path = shift or return;
288 mkpath([$repo_path]) unless -d $repo_path;
289 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
290 $ENV{GIT_DIR} = '.git';
293 sub cmd_clone {
294 my ($url, $path) = @_;
295 if (!defined $path &&
296 (defined $_trunk || defined $_branches || defined $_tags ||
297 defined $_stdlayout) &&
298 $url !~ m#^[a-z\+]+://#) {
299 $path = $url;
301 $path = basename($url) if !defined $path || !length $path;
302 cmd_init($url, $path);
303 Git::SVN::fetch_all($Git::SVN::default_repo_id);
306 sub cmd_init {
307 if (defined $_stdlayout) {
308 $_trunk = 'trunk' if (!defined $_trunk);
309 $_tags = 'tags' if (!defined $_tags);
310 $_branches = 'branches' if (!defined $_branches);
312 if (defined $_trunk || defined $_branches || defined $_tags) {
313 return cmd_multi_init(@_);
315 my $url = shift or die "SVN repository location required ",
316 "as a command-line argument\n";
317 init_subdir(@_);
318 do_git_init_db();
320 Git::SVN->init($url);
323 sub cmd_fetch {
324 if (grep /^\d+=./, @_) {
325 die "'<rev>=<commit>' fetch arguments are ",
326 "no longer supported.\n";
328 my ($remote) = @_;
329 if (@_ > 1) {
330 die "Usage: $0 fetch [--all] [svn-remote]\n";
332 $remote ||= $Git::SVN::default_repo_id;
333 if ($_fetch_all) {
334 cmd_multi_fetch();
335 } else {
336 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
340 sub cmd_set_tree {
341 my (@commits) = @_;
342 if ($_stdin || !@commits) {
343 print "Reading from stdin...\n";
344 @commits = ();
345 while (<STDIN>) {
346 if (/\b($sha1_short)\b/o) {
347 unshift @commits, $1;
351 my @revs;
352 foreach my $c (@commits) {
353 my @tmp = command('rev-parse',$c);
354 if (scalar @tmp == 1) {
355 push @revs, $tmp[0];
356 } elsif (scalar @tmp > 1) {
357 push @revs, reverse(command('rev-list',@tmp));
358 } else {
359 fatal "Failed to rev-parse $c\n";
362 my $gs = Git::SVN->new;
363 my ($r_last, $cmt_last) = $gs->last_rev_commit;
364 $gs->fetch;
365 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
366 fatal "There are new revisions that were fetched ",
367 "and need to be merged (or acknowledged) ",
368 "before committing.\nlast rev: $r_last\n",
369 " current: $gs->{last_rev}\n";
371 $gs->set_tree($_) foreach @revs;
372 print "Done committing ",scalar @revs," revisions to SVN\n";
375 sub cmd_dcommit {
376 my $head = shift;
377 $head ||= 'HEAD';
378 my @refs;
379 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
380 print "Committing to $url ...\n";
381 unless ($gs) {
382 die "Unable to determine upstream SVN information from ",
383 "$head history\n";
385 my $last_rev;
386 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
387 if ($_no_rebase && scalar(@$linear_refs) > 1) {
388 warn "Attempting to commit more than one change while ",
389 "--no-rebase is enabled.\n",
390 "If these changes depend on each other, re-running ",
391 "without --no-rebase will be required."
393 while (1) {
394 my $d = shift @$linear_refs or last;
395 unless (defined $last_rev) {
396 (undef, $last_rev, undef) = cmt_metadata("$d~1");
397 unless (defined $last_rev) {
398 fatal "Unable to extract revision information ",
399 "from commit $d~1\n";
402 if ($_dry_run) {
403 print "diff-tree $d~1 $d\n";
404 } else {
405 my $cmt_rev;
406 my %ed_opts = ( r => $last_rev,
407 log => get_commit_entry($d)->{log},
408 ra => Git::SVN::Ra->new($gs->full_url),
409 tree_a => "$d~1",
410 tree_b => $d,
411 editor_cb => sub {
412 print "Committed r$_[0]\n";
413 $cmt_rev = $_[0];
415 svn_path => '');
416 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
417 print "No changes\n$d~1 == $d\n";
418 } elsif ($parents->{$d} && @{$parents->{$d}}) {
419 $gs->{inject_parents_dcommit}->{$cmt_rev} =
420 $parents->{$d};
422 $_fetch_all ? $gs->fetch_all : $gs->fetch;
423 next if $_no_rebase;
425 # we always want to rebase against the current HEAD,
426 # not any head that was passed to us
427 my @diff = command('diff-tree', $d,
428 $gs->refname, '--');
429 my @finish;
430 if (@diff) {
431 @finish = rebase_cmd();
432 print STDERR "W: $d and ", $gs->refname,
433 " differ, using @finish:\n",
434 join("\n", @diff), "\n";
435 } else {
436 print "No changes between current HEAD and ",
437 $gs->refname,
438 "\nResetting to the latest ",
439 $gs->refname, "\n";
440 @finish = qw/reset --mixed/;
442 command_noisy(@finish, $gs->refname);
443 if (@diff) {
444 @refs = ();
445 my ($url_, $rev_, $uuid_, $gs_) =
446 working_head_info($head, \@refs);
447 my ($linear_refs_, $parents_) =
448 linearize_history($gs_, \@refs);
449 if (scalar(@$linear_refs) !=
450 scalar(@$linear_refs_)) {
451 fatal "# of revisions changed ",
452 "\nbefore:\n",
453 join("\n", @$linear_refs),
454 "\n\nafter:\n",
455 join("\n", @$linear_refs_), "\n",
456 'If you are attempting to commit ',
457 "merges, try running:\n\t",
458 'git rebase --interactive',
459 '--preserve-merges ',
460 $gs->refname,
461 "\nBefore dcommitting";
463 if ($url_ ne $url) {
464 fatal "URL mismatch after rebase: ",
465 "$url_ != $url";
467 if ($uuid_ ne $uuid) {
468 fatal "uuid mismatch after rebase: ",
469 "$uuid_ != $uuid";
471 # remap parents
472 my (%p, @l, $i);
473 for ($i = 0; $i < scalar @$linear_refs; $i++) {
474 my $new = $linear_refs_->[$i] or next;
475 $p{$new} =
476 $parents->{$linear_refs->[$i]};
477 push @l, $new;
479 $parents = \%p;
480 $linear_refs = \@l;
482 $last_rev = $cmt_rev;
487 sub cmd_find_rev {
488 my $revision_or_hash = shift;
489 my $result;
490 if ($revision_or_hash =~ /^r\d+$/) {
491 my $head = shift;
492 $head ||= 'HEAD';
493 my @refs;
494 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
495 unless ($gs) {
496 die "Unable to determine upstream SVN information from ",
497 "$head history\n";
499 my $desired_revision = substr($revision_or_hash, 1);
500 $result = $gs->rev_db_get($desired_revision);
501 } else {
502 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
503 $result = $rev;
505 print "$result\n" if $result;
508 sub cmd_rebase {
509 command_noisy(qw/update-index --refresh/);
510 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
511 unless ($gs) {
512 die "Unable to determine upstream SVN information from ",
513 "working tree history\n";
515 if (command(qw/diff-index HEAD --/)) {
516 print STDERR "Cannot rebase with uncommited changes:\n";
517 command_noisy('status');
518 exit 1;
520 unless ($_local) {
521 $_fetch_all ? $gs->fetch_all : $gs->fetch;
523 command_noisy(rebase_cmd(), $gs->refname);
526 sub cmd_show_ignore {
527 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
528 $gs ||= Git::SVN->new;
529 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
530 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
533 sub cmd_multi_init {
534 my $url = shift;
535 unless (defined $_trunk || defined $_branches || defined $_tags) {
536 usage(1);
539 # there are currently some bugs that prevent multi-init/multi-fetch
540 # setups from working well without this.
541 $Git::SVN::_minimize_url = 1;
543 $_prefix = '' unless defined $_prefix;
544 if (defined $url) {
545 $url =~ s#/+$##;
546 init_subdir(@_);
548 do_git_init_db();
549 if (defined $_trunk) {
550 my $trunk_ref = $_prefix . 'trunk';
551 # try both old-style and new-style lookups:
552 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
553 unless ($gs_trunk) {
554 my ($trunk_url, $trunk_path) =
555 complete_svn_url($url, $_trunk);
556 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
557 undef, $trunk_ref);
560 return unless defined $_branches || defined $_tags;
561 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
562 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
563 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
566 sub cmd_multi_fetch {
567 my $remotes = Git::SVN::read_all_remotes();
568 foreach my $repo_id (sort keys %$remotes) {
569 if ($remotes->{$repo_id}->{url}) {
570 Git::SVN::fetch_all($repo_id, $remotes);
575 # this command is special because it requires no metadata
576 sub cmd_commit_diff {
577 my ($ta, $tb, $url) = @_;
578 my $usage = "Usage: $0 commit-diff -r<revision> ".
579 "<tree-ish> <tree-ish> [<URL>]\n";
580 fatal($usage) if (!defined $ta || !defined $tb);
581 my $svn_path;
582 if (!defined $url) {
583 my $gs = eval { Git::SVN->new };
584 if (!$gs) {
585 fatal("Needed URL or usable git-svn --id in ",
586 "the command-line\n", $usage);
588 $url = $gs->{url};
589 $svn_path = $gs->{path};
591 unless (defined $_revision) {
592 fatal("-r|--revision is a required argument\n", $usage);
594 if (defined $_message && defined $_file) {
595 fatal("Both --message/-m and --file/-F specified ",
596 "for the commit message.\n",
597 "I have no idea what you mean\n");
599 if (defined $_file) {
600 $_message = file_to_s($_file);
601 } else {
602 $_message ||= get_commit_entry($tb)->{log};
604 my $ra ||= Git::SVN::Ra->new($url);
605 $svn_path ||= $ra->{svn_path};
606 my $r = $_revision;
607 if ($r eq 'HEAD') {
608 $r = $ra->get_latest_revnum;
609 } elsif ($r !~ /^\d+$/) {
610 die "revision argument: $r not understood by git-svn\n";
612 my %ed_opts = ( r => $r,
613 log => $_message,
614 ra => $ra,
615 tree_a => $ta,
616 tree_b => $tb,
617 editor_cb => sub { print "Committed r$_[0]\n" },
618 svn_path => $svn_path );
619 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
620 print "No changes\n$ta == $tb\n";
624 ########################### utility functions #########################
626 sub rebase_cmd {
627 my @cmd = qw/rebase/;
628 push @cmd, '-v' if $_verbose;
629 push @cmd, qw/--merge/ if $_merge;
630 push @cmd, "--strategy=$_strategy" if $_strategy;
631 @cmd;
634 sub post_fetch_checkout {
635 return if $_no_checkout;
636 my $gs = $Git::SVN::_head or return;
637 return if verify_ref('refs/heads/master^0');
639 my $valid_head = verify_ref('HEAD^0');
640 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
641 return if ($valid_head || !verify_ref('HEAD^0'));
643 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
644 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
645 return if -f $index;
647 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
648 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
649 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
650 print STDERR "Checked out HEAD:\n ",
651 $gs->full_url, " r", $gs->last_rev, "\n";
654 sub complete_svn_url {
655 my ($url, $path) = @_;
656 $path =~ s#/+$##;
657 if ($path !~ m#^[a-z\+]+://#) {
658 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
659 fatal("E: '$path' is not a complete URL ",
660 "and a separate URL is not specified\n");
662 return ($url, $path);
664 return ($path, '');
667 sub complete_url_ls_init {
668 my ($ra, $repo_path, $switch, $pfx) = @_;
669 unless ($repo_path) {
670 print STDERR "W: $switch not specified\n";
671 return;
673 $repo_path =~ s#/+$##;
674 if ($repo_path =~ m#^[a-z\+]+://#) {
675 $ra = Git::SVN::Ra->new($repo_path);
676 $repo_path = '';
677 } else {
678 $repo_path =~ s#^/+##;
679 unless ($ra) {
680 fatal("E: '$repo_path' is not a complete URL ",
681 "and a separate URL is not specified\n");
684 my $url = $ra->{url};
685 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
686 my $k = "svn-remote.$gs->{repo_id}.url";
687 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
688 if ($orig_url && ($orig_url ne $gs->{url})) {
689 die "$k already set: $orig_url\n",
690 "wanted to set to: $gs->{url}\n";
692 command_oneline('config', $k, $gs->{url}) unless $orig_url;
693 my $remote_path = "$ra->{svn_path}/$repo_path/*";
694 $remote_path =~ s#/+#/#g;
695 $remote_path =~ s#^/##g;
696 my ($n) = ($switch =~ /^--(\w+)/);
697 if (length $pfx && $pfx !~ m#/$#) {
698 die "--prefix='$pfx' must have a trailing slash '/'\n";
700 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
701 "$remote_path:refs/remotes/$pfx*");
704 sub verify_ref {
705 my ($ref) = @_;
706 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
707 { STDERR => 0 }); };
710 sub get_tree_from_treeish {
711 my ($treeish) = @_;
712 # $treeish can be a symbolic ref, too:
713 my $type = command_oneline(qw/cat-file -t/, $treeish);
714 my $expected;
715 while ($type eq 'tag') {
716 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
718 if ($type eq 'commit') {
719 $expected = (grep /^tree /, command(qw/cat-file commit/,
720 $treeish))[0];
721 ($expected) = ($expected =~ /^tree ($sha1)$/o);
722 die "Unable to get tree from $treeish\n" unless $expected;
723 } elsif ($type eq 'tree') {
724 $expected = $treeish;
725 } else {
726 die "$treeish is a $type, expected tree, tag or commit\n";
728 return $expected;
731 sub get_commit_entry {
732 my ($treeish) = shift;
733 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
734 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
735 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
736 open my $log_fh, '>', $commit_editmsg or croak $!;
738 my $type = command_oneline(qw/cat-file -t/, $treeish);
739 if ($type eq 'commit' || $type eq 'tag') {
740 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
741 $type, $treeish);
742 my $in_msg = 0;
743 while (<$msg_fh>) {
744 if (!$in_msg) {
745 $in_msg = 1 if (/^\s*$/);
746 } elsif (/^git-svn-id: /) {
747 # skip this for now, we regenerate the
748 # correct one on re-fetch anyways
749 # TODO: set *:merge properties or like...
750 } else {
751 print $log_fh $_ or croak $!;
754 command_close_pipe($msg_fh, $ctx);
756 close $log_fh or croak $!;
758 if ($_edit || ($type eq 'tree')) {
759 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
760 # TODO: strip out spaces, comments, like git-commit.sh
761 system($editor, $commit_editmsg);
763 rename $commit_editmsg, $commit_msg or croak $!;
764 open $log_fh, '<', $commit_msg or croak $!;
765 { local $/; chomp($log_entry{log} = <$log_fh>); }
766 close $log_fh or croak $!;
767 unlink $commit_msg;
768 \%log_entry;
771 sub s_to_file {
772 my ($str, $file, $mode) = @_;
773 open my $fd,'>',$file or croak $!;
774 print $fd $str,"\n" or croak $!;
775 close $fd or croak $!;
776 chmod ($mode &~ umask, $file) if (defined $mode);
779 sub file_to_s {
780 my $file = shift;
781 open my $fd,'<',$file or croak "$!: file: $file\n";
782 local $/;
783 my $ret = <$fd>;
784 close $fd or croak $!;
785 $ret =~ s/\s*$//s;
786 return $ret;
789 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
790 sub load_authors {
791 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
792 my $log = $cmd eq 'log';
793 while (<$authors>) {
794 chomp;
795 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
796 my ($user, $name, $email) = ($1, $2, $3);
797 if ($log) {
798 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
799 } else {
800 $users{$user} = [$name, $email];
803 close $authors or croak $!;
806 # convert GetOpt::Long specs for use by git-config
807 sub read_repo_config {
808 return unless -d $ENV{GIT_DIR};
809 my $opts = shift;
810 my @config_only;
811 foreach my $o (keys %$opts) {
812 # if we have mixedCase and a long option-only, then
813 # it's a config-only variable that we don't need for
814 # the command-line.
815 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
816 my $v = $opts->{$o};
817 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
818 $key =~ s/-//g;
819 my $arg = 'git-config';
820 $arg .= ' --int' if ($o =~ /[:=]i$/);
821 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
822 if (ref $v eq 'ARRAY') {
823 chomp(my @tmp = `$arg --get-all svn.$key`);
824 @$v = @tmp if @tmp;
825 } else {
826 chomp(my $tmp = `$arg --get svn.$key`);
827 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
828 $$v = $tmp;
832 delete @$opts{@config_only} if @config_only;
835 sub extract_metadata {
836 my $id = shift or return (undef, undef, undef);
837 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
838 \s([a-f\d\-]+)$/x);
839 if (!defined $rev || !$uuid || !$url) {
840 # some of the original repositories I made had
841 # identifiers like this:
842 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
844 return ($url, $rev, $uuid);
847 sub cmt_metadata {
848 return extract_metadata((grep(/^git-svn-id: /,
849 command(qw/cat-file commit/, shift)))[-1]);
852 sub working_head_info {
853 my ($head, $refs) = @_;
854 my ($fh, $ctx) = command_output_pipe('log', '--no-color', $head);
855 my $hash;
856 my %max;
857 while (<$fh>) {
858 if ( m{^commit ($::sha1)$} ) {
859 unshift @$refs, $hash if $hash and $refs;
860 $hash = $1;
861 next;
863 next unless s{^\s*(git-svn-id:)}{$1};
864 my ($url, $rev, $uuid) = extract_metadata($_);
865 if (defined $url && defined $rev) {
866 next if $max{$url} and $max{$url} < $rev;
867 if (my $gs = Git::SVN->find_by_url($url)) {
868 my $c = $gs->rev_db_get($rev);
869 if ($c && $c eq $hash) {
870 close $fh; # break the pipe
871 return ($url, $rev, $uuid, $gs);
872 } else {
873 $max{$url} ||= $gs->rev_db_max;
878 command_close_pipe($fh, $ctx);
879 (undef, undef, undef, undef);
882 sub read_commit_parents {
883 my ($parents, $c) = @_;
884 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
885 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
886 @{$parents->{$c}} = split(/ /, $p);
889 sub linearize_history {
890 my ($gs, $refs) = @_;
891 my %parents;
892 foreach my $c (@$refs) {
893 read_commit_parents(\%parents, $c);
896 my @linear_refs;
897 my %skip = ();
898 my $last_svn_commit = $gs->last_commit;
899 foreach my $c (reverse @$refs) {
900 next if $c eq $last_svn_commit;
901 last if $skip{$c};
903 unshift @linear_refs, $c;
904 $skip{$c} = 1;
906 # we only want the first parent to diff against for linear
907 # history, we save the rest to inject when we finalize the
908 # svn commit
909 my $fp_a = verify_ref("$c~1");
910 my $fp_b = shift @{$parents{$c}} if $parents{$c};
911 if (!$fp_a || !$fp_b) {
912 die "Commit $c\n",
913 "has no parent commit, and therefore ",
914 "nothing to diff against.\n",
915 "You should be working from a repository ",
916 "originally created by git-svn\n";
918 if ($fp_a ne $fp_b) {
919 die "$c~1 = $fp_a, however parsing commit $c ",
920 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
923 foreach my $p (@{$parents{$c}}) {
924 $skip{$p} = 1;
927 (\@linear_refs, \%parents);
930 package Git::SVN;
931 use strict;
932 use warnings;
933 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
934 $_repack $_repack_flags $_use_svm_props $_head
935 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
936 use Carp qw/croak/;
937 use File::Path qw/mkpath/;
938 use File::Copy qw/copy/;
939 use IPC::Open3;
941 my $_repack_nr;
942 # properties that we do not log:
943 my %SKIP_PROP;
944 BEGIN {
945 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
946 svn:special svn:executable
947 svn:entry:committed-rev
948 svn:entry:last-author
949 svn:entry:uuid
950 svn:entry:committed-date/;
952 # some options are read globally, but can be overridden locally
953 # per [svn-remote "..."] section. Command-line options will *NOT*
954 # override options set in an [svn-remote "..."] section
955 no strict 'refs';
956 for my $option (qw/follow_parent no_metadata use_svm_props
957 use_svnsync_props/) {
958 my $key = $option;
959 $key =~ tr/_//d;
960 my $prop = "-$option";
961 *$option = sub {
962 my ($self) = @_;
963 return $self->{$prop} if exists $self->{$prop};
964 my $k = "svn-remote.$self->{repo_id}.$key";
965 eval { command_oneline(qw/config --get/, $k) };
966 if ($@) {
967 $self->{$prop} = ${"Git::SVN::_$option"};
968 } else {
969 my $v = command_oneline(qw/config --bool/,$k);
970 $self->{$prop} = $v eq 'false' ? 0 : 1;
972 return $self->{$prop};
977 my %LOCKFILES;
978 END { unlink keys %LOCKFILES if %LOCKFILES }
980 sub resolve_local_globs {
981 my ($url, $fetch, $glob_spec) = @_;
982 return unless defined $glob_spec;
983 my $ref = $glob_spec->{ref};
984 my $path = $glob_spec->{path};
985 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
986 next unless m#^refs/remotes/$ref->{regex}$#;
987 my $p = $1;
988 my $pathname = desanitize_refname($path->full_path($p));
989 my $refname = desanitize_refname($ref->full_path($p));
990 if (my $existing = $fetch->{$pathname}) {
991 if ($existing ne $refname) {
992 die "Refspec conflict:\n",
993 "existing: refs/remotes/$existing\n",
994 " globbed: refs/remotes/$refname\n";
996 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
997 $u =~ s!^\Q$url\E(/|$)!! or die
998 "refs/remotes/$refname: '$url' not found in '$u'\n";
999 if ($pathname ne $u) {
1000 warn "W: Refspec glob conflict ",
1001 "(ref: refs/remotes/$refname):\n",
1002 "expected path: $pathname\n",
1003 " real path: $u\n",
1004 "Continuing ahead with $u\n";
1005 next;
1007 } else {
1008 $fetch->{$pathname} = $refname;
1013 sub parse_revision_argument {
1014 my ($base, $head) = @_;
1015 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1016 return ($base, $head);
1018 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1019 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1020 return ($head, $head) if ($::_revision eq 'HEAD');
1021 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1022 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1023 die "revision argument: $::_revision not understood by git-svn\n";
1026 sub fetch_all {
1027 my ($repo_id, $remotes) = @_;
1028 if (ref $repo_id) {
1029 my $gs = $repo_id;
1030 $repo_id = undef;
1031 $repo_id = $gs->{repo_id};
1033 $remotes ||= read_all_remotes();
1034 my $remote = $remotes->{$repo_id} or
1035 die "[svn-remote \"$repo_id\"] unknown\n";
1036 my $fetch = $remote->{fetch};
1037 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1038 my (@gs, @globs);
1039 my $ra = Git::SVN::Ra->new($url);
1040 my $uuid = $ra->get_uuid;
1041 my $head = $ra->get_latest_revnum;
1042 my $base = defined $fetch ? $head : 0;
1044 # read the max revs for wildcard expansion (branches/*, tags/*)
1045 foreach my $t (qw/branches tags/) {
1046 defined $remote->{$t} or next;
1047 push @globs, $remote->{$t};
1048 my $max_rev = eval { tmp_config(qw/--int --get/,
1049 "svn-remote.$repo_id.${t}-maxRev") };
1050 if (defined $max_rev && ($max_rev < $base)) {
1051 $base = $max_rev;
1052 } elsif (!defined $max_rev) {
1053 $base = 0;
1057 if ($fetch) {
1058 foreach my $p (sort keys %$fetch) {
1059 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1060 my $lr = $gs->rev_db_max;
1061 if (defined $lr) {
1062 $base = $lr if ($lr < $base);
1064 push @gs, $gs;
1068 ($base, $head) = parse_revision_argument($base, $head);
1069 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1072 sub read_all_remotes {
1073 my $r = {};
1074 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1075 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1076 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1077 $local_ref =~ s{^/}{};
1078 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1079 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1080 $r->{$1}->{url} = $2;
1081 } elsif (m!^(.+)\.(branches|tags)=
1082 (.*):refs/remotes/(.+)\s*$/!x) {
1083 my ($p, $g) = ($3, $4);
1084 my $rs = $r->{$1}->{$2} = {
1085 t => $2,
1086 remote => $1,
1087 path => Git::SVN::GlobSpec->new($p),
1088 ref => Git::SVN::GlobSpec->new($g) };
1089 if (length($rs->{ref}->{right}) != 0) {
1090 die "The '*' glob character must be the last ",
1091 "character of '$g'\n";
1098 sub init_vars {
1099 if (defined $_repack) {
1100 $_repack = 1000 if ($_repack <= 0);
1101 $_repack_nr = $_repack;
1102 $_repack_flags ||= '-d';
1106 sub verify_remotes_sanity {
1107 return unless -d $ENV{GIT_DIR};
1108 my %seen;
1109 foreach (command(qw/config -l/)) {
1110 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1111 if ($seen{$1}) {
1112 die "Remote ref refs/remote/$1 is tracked by",
1113 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1114 "Please resolve this ambiguity in ",
1115 "your git configuration file before ",
1116 "continuing\n";
1118 $seen{$1} = $_;
1123 # we allow more chars than remotes2config.sh...
1124 sub sanitize_remote_name {
1125 my ($name) = @_;
1126 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1127 $name;
1130 sub find_existing_remote {
1131 my ($url, $remotes) = @_;
1132 return undef if $no_reuse_existing;
1133 my $existing;
1134 foreach my $repo_id (keys %$remotes) {
1135 my $u = $remotes->{$repo_id}->{url} or next;
1136 next if $u ne $url;
1137 $existing = $repo_id;
1138 last;
1140 $existing;
1143 sub init_remote_config {
1144 my ($self, $url, $no_write) = @_;
1145 $url =~ s!/+$!!; # strip trailing slash
1146 my $r = read_all_remotes();
1147 my $existing = find_existing_remote($url, $r);
1148 if ($existing) {
1149 unless ($no_write) {
1150 print STDERR "Using existing ",
1151 "[svn-remote \"$existing\"]\n";
1153 $self->{repo_id} = $existing;
1154 } elsif ($_minimize_url) {
1155 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1156 $existing = find_existing_remote($min_url, $r);
1157 if ($existing) {
1158 unless ($no_write) {
1159 print STDERR "Using existing ",
1160 "[svn-remote \"$existing\"]\n";
1162 $self->{repo_id} = $existing;
1164 if ($min_url ne $url) {
1165 unless ($no_write) {
1166 print STDERR "Using higher level of URL: ",
1167 "$url => $min_url\n";
1169 my $old_path = $self->{path};
1170 $self->{path} = $url;
1171 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1172 if (length $old_path) {
1173 $self->{path} .= "/$old_path";
1175 $url = $min_url;
1178 my $orig_url;
1179 if (!$existing) {
1180 # verify that we aren't overwriting anything:
1181 $orig_url = eval {
1182 command_oneline('config', '--get',
1183 "svn-remote.$self->{repo_id}.url")
1185 if ($orig_url && ($orig_url ne $url)) {
1186 die "svn-remote.$self->{repo_id}.url already set: ",
1187 "$orig_url\nwanted to set to: $url\n";
1190 my ($xrepo_id, $xpath) = find_ref($self->refname);
1191 if (defined $xpath) {
1192 die "svn-remote.$xrepo_id.fetch already set to track ",
1193 "$xpath:refs/remotes/", $self->refname, "\n";
1195 unless ($no_write) {
1196 command_noisy('config',
1197 "svn-remote.$self->{repo_id}.url", $url);
1198 $self->{path} =~ s{^/}{};
1199 command_noisy('config', '--add',
1200 "svn-remote.$self->{repo_id}.fetch",
1201 "$self->{path}:".$self->refname);
1203 $self->{url} = $url;
1206 sub find_by_url { # repos_root and, path are optional
1207 my ($class, $full_url, $repos_root, $path) = @_;
1209 return undef unless defined $full_url;
1210 remove_username($full_url);
1211 remove_username($repos_root) if defined $repos_root;
1212 my $remotes = read_all_remotes();
1213 if (defined $full_url && defined $repos_root && !defined $path) {
1214 $path = $full_url;
1215 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1217 foreach my $repo_id (keys %$remotes) {
1218 my $u = $remotes->{$repo_id}->{url} or next;
1219 remove_username($u);
1220 next if defined $repos_root && $repos_root ne $u;
1222 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1223 foreach (qw/branches tags/) {
1224 resolve_local_globs($u, $fetch,
1225 $remotes->{$repo_id}->{$_});
1227 my $p = $path;
1228 unless (defined $p) {
1229 $p = $full_url;
1230 $p =~ s#^\Q$u\E(?:/|$)## or next;
1232 foreach my $f (keys %$fetch) {
1233 next if $f ne $p;
1234 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1237 undef;
1240 sub init {
1241 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1242 my $self = _new($class, $repo_id, $ref_id, $path);
1243 if (defined $url) {
1244 $self->init_remote_config($url, $no_write);
1246 $self;
1249 sub find_ref {
1250 my ($ref_id) = @_;
1251 foreach (command(qw/config -l/)) {
1252 next unless m!^svn-remote\.(.+)\.fetch=
1253 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1254 my ($repo_id, $path, $ref) = ($1, $2, $3);
1255 if ($ref eq $ref_id) {
1256 $path = '' if ($path =~ m#^\./?#);
1257 return ($repo_id, $path);
1260 (undef, undef, undef);
1263 sub new {
1264 my ($class, $ref_id, $repo_id, $path) = @_;
1265 if (defined $ref_id && !defined $repo_id && !defined $path) {
1266 ($repo_id, $path) = find_ref($ref_id);
1267 if (!defined $repo_id) {
1268 die "Could not find a \"svn-remote.*.fetch\" key ",
1269 "in the repository configuration matching: ",
1270 "refs/remotes/$ref_id\n";
1273 my $self = _new($class, $repo_id, $ref_id, $path);
1274 if (!defined $self->{path} || !length $self->{path}) {
1275 my $fetch = command_oneline('config', '--get',
1276 "svn-remote.$repo_id.fetch",
1277 ":refs/remotes/$ref_id\$") or
1278 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1279 "\":refs/remotes/$ref_id\$\" in config\n";
1280 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1282 $self->{url} = command_oneline('config', '--get',
1283 "svn-remote.$repo_id.url") or
1284 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1285 $self->rebuild;
1286 $self;
1289 sub refname {
1290 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1292 # It cannot end with a slash /, we'll throw up on this because
1293 # SVN can't have directories with a slash in their name, either:
1294 if ($refname =~ m{/$}) {
1295 die "ref: '$refname' ends with a trailing slash, this is ",
1296 "not permitted by git nor Subversion\n";
1299 # It cannot have ASCII control character space, tilde ~, caret ^,
1300 # colon :, question-mark ?, asterisk *, space, or open bracket [
1301 # anywhere.
1303 # Additionally, % must be escaped because it is used for escaping
1304 # and we want our escaped refname to be reversible
1305 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1307 # no slash-separated component can begin with a dot .
1308 # /.* becomes /%2E*
1309 $refname =~ s{/\.}{/%2E}g;
1311 # It cannot have two consecutive dots .. anywhere
1312 # .. becomes %2E%2E
1313 $refname =~ s{\.\.}{%2E%2E}g;
1315 return $refname;
1318 sub desanitize_refname {
1319 my ($refname) = @_;
1320 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1321 return $refname;
1324 sub svm_uuid {
1325 my ($self) = @_;
1326 return $self->{svm}->{uuid} if $self->svm;
1327 $self->ra;
1328 unless ($self->{svm}) {
1329 die "SVM UUID not cached, and reading remotely failed\n";
1331 $self->{svm}->{uuid};
1334 sub svm {
1335 my ($self) = @_;
1336 return $self->{svm} if $self->{svm};
1337 my $svm;
1338 # see if we have it in our config, first:
1339 eval {
1340 my $section = "svn-remote.$self->{repo_id}";
1341 $svm = {
1342 source => tmp_config('--get', "$section.svm-source"),
1343 uuid => tmp_config('--get', "$section.svm-uuid"),
1344 replace => tmp_config('--get', "$section.svm-replace"),
1347 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1348 $self->{svm} = $svm;
1350 $self->{svm};
1353 sub _set_svm_vars {
1354 my ($self, $ra) = @_;
1355 return $ra if $self->svm;
1357 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1358 "(svm:source, svm:uuid) ",
1359 "from the following URLs:\n" );
1360 sub read_svm_props {
1361 my ($self, $ra, $path, $r) = @_;
1362 my $props = ($ra->get_dir($path, $r))[2];
1363 my $src = $props->{'svm:source'};
1364 my $uuid = $props->{'svm:uuid'};
1365 return undef if (!$src || !$uuid);
1367 chomp($src, $uuid);
1369 $uuid =~ m{^[0-9a-f\-]{30,}$}
1370 or die "doesn't look right - svm:uuid is '$uuid'\n";
1372 # the '!' is used to mark the repos_root!/relative/path
1373 $src =~ s{/?!/?}{/};
1374 $src =~ s{/+$}{}; # no trailing slashes please
1375 # username is of no interest
1376 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1378 my $replace = $ra->{url};
1379 $replace .= "/$path" if length $path;
1381 my $section = "svn-remote.$self->{repo_id}";
1382 tmp_config("$section.svm-source", $src);
1383 tmp_config("$section.svm-replace", $replace);
1384 tmp_config("$section.svm-uuid", $uuid);
1385 $self->{svm} = {
1386 source => $src,
1387 uuid => $uuid,
1388 replace => $replace
1392 my $r = $ra->get_latest_revnum;
1393 my $path = $self->{path};
1394 my %tried;
1395 while (length $path) {
1396 unless ($tried{"$self->{url}/$path"}) {
1397 return $ra if $self->read_svm_props($ra, $path, $r);
1398 $tried{"$self->{url}/$path"} = 1;
1400 $path =~ s#/?[^/]+$##;
1402 die "Path: '$path' should be ''\n" if $path ne '';
1403 return $ra if $self->read_svm_props($ra, $path, $r);
1404 $tried{"$self->{url}/$path"} = 1;
1406 if ($ra->{repos_root} eq $self->{url}) {
1407 die @err, (map { " $_\n" } keys %tried), "\n";
1410 # nope, make sure we're connected to the repository root:
1411 my $ok;
1412 my @tried_b;
1413 $path = $ra->{svn_path};
1414 $ra = Git::SVN::Ra->new($ra->{repos_root});
1415 while (length $path) {
1416 unless ($tried{"$ra->{url}/$path"}) {
1417 $ok = $self->read_svm_props($ra, $path, $r);
1418 last if $ok;
1419 $tried{"$ra->{url}/$path"} = 1;
1421 $path =~ s#/?[^/]+$##;
1423 die "Path: '$path' should be ''\n" if $path ne '';
1424 $ok ||= $self->read_svm_props($ra, $path, $r);
1425 $tried{"$ra->{url}/$path"} = 1;
1426 if (!$ok) {
1427 die @err, (map { " $_\n" } keys %tried), "\n";
1429 Git::SVN::Ra->new($self->{url});
1432 sub svnsync {
1433 my ($self) = @_;
1434 return $self->{svnsync} if $self->{svnsync};
1436 if ($self->no_metadata) {
1437 die "Can't have both 'noMetadata' and ",
1438 "'useSvnsyncProps' options set!\n";
1440 if ($self->rewrite_root) {
1441 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1442 "options set!\n";
1445 my $svnsync;
1446 # see if we have it in our config, first:
1447 eval {
1448 my $section = "svn-remote.$self->{repo_id}";
1449 $svnsync = {
1450 url => tmp_config('--get', "$section.svnsync-url"),
1451 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1454 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1455 return $self->{svnsync} = $svnsync;
1458 my $err = "useSvnsyncProps set, but failed to read " .
1459 "svnsync property: svn:sync-from-";
1460 my $rp = $self->ra->rev_proplist(0);
1462 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1463 $url =~ m{^[a-z\+]+://} or
1464 die "doesn't look right - svn:sync-from-url is '$url'\n";
1466 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1467 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1468 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1470 my $section = "svn-remote.$self->{repo_id}";
1471 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1472 tmp_config('--add', "$section.svnsync-url", $url);
1473 return $self->{svnsync} = { url => $url, uuid => $uuid };
1476 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1477 # remote lookup (useful for 'git svn log').
1478 sub ra_uuid {
1479 my ($self) = @_;
1480 unless ($self->{ra_uuid}) {
1481 my $key = "svn-remote.$self->{repo_id}.uuid";
1482 my $uuid = eval { tmp_config('--get', $key) };
1483 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1484 $self->{ra_uuid} = $uuid;
1485 } else {
1486 die "ra_uuid called without URL\n" unless $self->{url};
1487 $self->{ra_uuid} = $self->ra->get_uuid;
1488 tmp_config('--add', $key, $self->{ra_uuid});
1491 $self->{ra_uuid};
1494 sub ra {
1495 my ($self) = shift;
1496 my $ra = Git::SVN::Ra->new($self->{url});
1497 if ($self->use_svm_props && !$self->{svm}) {
1498 if ($self->no_metadata) {
1499 die "Can't have both 'noMetadata' and ",
1500 "'useSvmProps' options set!\n";
1501 } elsif ($self->use_svnsync_props) {
1502 die "Can't have both 'useSvnsyncProps' and ",
1503 "'useSvmProps' options set!\n";
1505 $ra = $self->_set_svm_vars($ra);
1506 $self->{-want_revprops} = 1;
1508 $ra;
1511 sub rel_path {
1512 my ($self) = @_;
1513 my $repos_root = $self->ra->{repos_root};
1514 return $self->{path} if ($self->{url} eq $repos_root);
1515 my $url = $self->{url} .
1516 (length $self->{path} ? "/$self->{path}" : $self->{path});
1517 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1518 $url;
1521 sub traverse_ignore {
1522 my ($self, $fh, $path, $r) = @_;
1523 $path =~ s#^/+##g;
1524 my $ra = $self->ra;
1525 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1526 my $p = $path;
1527 $p =~ s#^\Q$self->{path}\E(/|$)##;
1528 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1529 if (my $s = $props->{'svn:ignore'}) {
1530 $s =~ s/[\r\n]+/\n/g;
1531 chomp $s;
1532 if (length $p == 0) {
1533 $s =~ s#\n#\n/$p#g;
1534 print $fh "/$s\n";
1535 } else {
1536 $s =~ s#\n#\n/$p/#g;
1537 print $fh "/$p/$s\n";
1540 foreach (sort keys %$dirent) {
1541 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1542 $self->traverse_ignore($fh, "$path/$_", $r);
1546 sub last_rev { ($_[0]->last_rev_commit)[0] }
1547 sub last_commit { ($_[0]->last_rev_commit)[1] }
1549 # returns the newest SVN revision number and newest commit SHA1
1550 sub last_rev_commit {
1551 my ($self) = @_;
1552 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1553 return ($self->{last_rev}, $self->{last_commit});
1555 my $c = ::verify_ref($self->refname.'^0');
1556 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1557 my $rev = (::cmt_metadata($c))[1];
1558 if (defined $rev) {
1559 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1560 return ($rev, $c);
1563 my $db_path = $self->db_path;
1564 unless (-e $db_path) {
1565 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1566 return (undef, undef);
1568 my $offset = -41; # from tail
1569 my $rl;
1570 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1571 sysseek($fh, $offset, 2); # don't care for errors
1572 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1573 chomp $rl;
1574 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1575 $offset -= 41;
1576 sysseek($fh, $offset, 2); # don't care for errors
1577 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1578 chomp $rl;
1580 if ($c && $c ne $rl) {
1581 die "$db_path and ", $self->refname,
1582 " inconsistent!:\n$c != $rl\n";
1584 my $rev = sysseek($fh, 0, 1) or croak $!;
1585 $rev = ($rev - 41) / 41;
1586 close $fh or croak $!;
1587 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1588 return ($rev, $c);
1591 sub get_fetch_range {
1592 my ($self, $min, $max) = @_;
1593 $max ||= $self->ra->get_latest_revnum;
1594 $min ||= $self->rev_db_max;
1595 (++$min, $max);
1598 sub tmp_config {
1599 my (@args) = @_;
1600 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1601 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1602 if (! -f $config && -f $old_def_config) {
1603 rename $old_def_config, $config or
1604 die "Failed rename $old_def_config => $config: $!\n";
1606 my $old_config = $ENV{GIT_CONFIG};
1607 $ENV{GIT_CONFIG} = $config;
1608 $@ = undef;
1609 my @ret = eval {
1610 unless (-f $config) {
1611 mkfile($config);
1612 open my $fh, '>', $config or
1613 die "Can't open $config: $!\n";
1614 print $fh "; This file is used internally by ",
1615 "git-svn\n" or die
1616 "Couldn't write to $config: $!\n";
1617 print $fh "; You should not have to edit it\n" or
1618 die "Couldn't write to $config: $!\n";
1619 close $fh or die "Couldn't close $config: $!\n";
1621 command('config', @args);
1623 my $err = $@;
1624 if (defined $old_config) {
1625 $ENV{GIT_CONFIG} = $old_config;
1626 } else {
1627 delete $ENV{GIT_CONFIG};
1629 die $err if $err;
1630 wantarray ? @ret : $ret[0];
1633 sub tmp_index_do {
1634 my ($self, $sub) = @_;
1635 my $old_index = $ENV{GIT_INDEX_FILE};
1636 $ENV{GIT_INDEX_FILE} = $self->{index};
1637 $@ = undef;
1638 my @ret = eval {
1639 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1640 mkpath([$dir]) unless -d $dir;
1641 &$sub;
1643 my $err = $@;
1644 if (defined $old_index) {
1645 $ENV{GIT_INDEX_FILE} = $old_index;
1646 } else {
1647 delete $ENV{GIT_INDEX_FILE};
1649 die $err if $err;
1650 wantarray ? @ret : $ret[0];
1653 sub assert_index_clean {
1654 my ($self, $treeish) = @_;
1656 $self->tmp_index_do(sub {
1657 command_noisy('read-tree', $treeish) unless -e $self->{index};
1658 my $x = command_oneline('write-tree');
1659 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1660 /^tree ($::sha1)/mo);
1661 return if $y eq $x;
1663 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1664 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1665 command_noisy('read-tree', $treeish);
1666 $x = command_oneline('write-tree');
1667 if ($y ne $x) {
1668 ::fatal "trees ($treeish) $y != $x\n",
1669 "Something is seriously wrong...\n";
1674 sub get_commit_parents {
1675 my ($self, $log_entry) = @_;
1676 my (%seen, @ret, @tmp);
1677 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1678 if (my $ip = $self->{inject_parents}) {
1679 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1680 push @tmp, $commit;
1683 if (my $cur = ::verify_ref($self->refname.'^0')) {
1684 push @tmp, $cur;
1686 if (my $ipd = $self->{inject_parents_dcommit}) {
1687 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1688 push @tmp, @$commit;
1691 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1692 while (my $p = shift @tmp) {
1693 next if $seen{$p};
1694 $seen{$p} = 1;
1695 push @ret, $p;
1696 # MAXPARENT is defined to 16 in commit-tree.c:
1697 last if @ret >= 16;
1699 if (@tmp) {
1700 die "r$log_entry->{revision}: No room for parents:\n\t",
1701 join("\n\t", @tmp), "\n";
1703 @ret;
1706 sub rewrite_root {
1707 my ($self) = @_;
1708 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1709 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1710 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1711 if ($rwr) {
1712 $rwr =~ s#/+$##;
1713 if ($rwr !~ m#^[a-z\+]+://#) {
1714 die "$rwr is not a valid URL (key: $k)\n";
1717 $self->{-rewrite_root} = $rwr;
1720 sub metadata_url {
1721 my ($self) = @_;
1722 ($self->rewrite_root || $self->{url}) .
1723 (length $self->{path} ? '/' . $self->{path} : '');
1726 sub full_url {
1727 my ($self) = @_;
1728 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1731 sub do_git_commit {
1732 my ($self, $log_entry) = @_;
1733 my $lr = $self->last_rev;
1734 if (defined $lr && $lr >= $log_entry->{revision}) {
1735 die "Last fetched revision of ", $self->refname,
1736 " was r$lr, but we are about to fetch: ",
1737 "r$log_entry->{revision}!\n";
1739 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1740 croak "$log_entry->{revision} = $c already exists! ",
1741 "Why are we refetching it?\n";
1743 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1744 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1745 $log_entry->{email};
1746 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1748 my $tree = $log_entry->{tree};
1749 if (!defined $tree) {
1750 $tree = $self->tmp_index_do(sub {
1751 command_oneline('write-tree') });
1753 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1755 my @exec = ('git-commit-tree', $tree);
1756 foreach ($self->get_commit_parents($log_entry)) {
1757 push @exec, '-p', $_;
1759 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1760 or croak $!;
1761 print $msg_fh $log_entry->{log} or croak $!;
1762 unless ($self->no_metadata) {
1763 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1764 or croak $!;
1766 $msg_fh->flush == 0 or croak $!;
1767 close $msg_fh or croak $!;
1768 chomp(my $commit = do { local $/; <$out_fh> });
1769 close $out_fh or croak $!;
1770 waitpid $pid, 0;
1771 croak $? if $?;
1772 if ($commit !~ /^$::sha1$/o) {
1773 die "Failed to commit, invalid sha1: $commit\n";
1776 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1778 $self->{last_rev} = $log_entry->{revision};
1779 $self->{last_commit} = $commit;
1780 print "r$log_entry->{revision}";
1781 if (defined $log_entry->{svm_revision}) {
1782 print " (\@$log_entry->{svm_revision})";
1783 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1784 0, $self->svm_uuid);
1786 print " = $commit ($self->{ref_id})\n";
1787 if (defined $_repack && (--$_repack_nr == 0)) {
1788 $_repack_nr = $_repack;
1789 # repack doesn't use any arguments with spaces in them, does it?
1790 print "Running git repack $_repack_flags ...\n";
1791 command_noisy('repack', split(/\s+/, $_repack_flags));
1792 print "Done repacking\n";
1794 return $commit;
1797 sub match_paths {
1798 my ($self, $paths, $r) = @_;
1799 return 1 if $self->{path} eq '';
1800 if (my $path = $paths->{"/$self->{path}"}) {
1801 return ($path->{action} eq 'D') ? 0 : 1;
1803 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1804 if (grep /$self->{path_regex}/, keys %$paths) {
1805 return 1;
1807 my $c = '';
1808 foreach (split m#/#, $self->{path}) {
1809 $c .= "/$_";
1810 next unless ($paths->{$c} &&
1811 ($paths->{$c}->{action} =~ /^[AR]$/));
1812 if ($self->ra->check_path($self->{path}, $r) ==
1813 $SVN::Node::dir) {
1814 return 1;
1817 return 0;
1820 sub find_parent_branch {
1821 my ($self, $paths, $rev) = @_;
1822 return undef unless $self->follow_parent;
1823 unless (defined $paths) {
1824 my $err_handler = $SVN::Error::handler;
1825 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1826 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1827 $paths =
1828 Git::SVN::Ra::dup_changed_paths($_[0]) });
1829 $SVN::Error::handler = $err_handler;
1831 return undef unless defined $paths;
1833 # look for a parent from another branch:
1834 my @b_path_components = split m#/#, $self->rel_path;
1835 my @a_path_components;
1836 my $i;
1837 while (@b_path_components) {
1838 $i = $paths->{'/'.join('/', @b_path_components)};
1839 last if $i && defined $i->{copyfrom_path};
1840 unshift(@a_path_components, pop(@b_path_components));
1842 return undef unless defined $i && defined $i->{copyfrom_path};
1843 my $branch_from = $i->{copyfrom_path};
1844 if (@a_path_components) {
1845 print STDERR "branch_from: $branch_from => ";
1846 $branch_from .= '/'.join('/', @a_path_components);
1847 print STDERR $branch_from, "\n";
1849 my $r = $i->{copyfrom_rev};
1850 my $repos_root = $self->ra->{repos_root};
1851 my $url = $self->ra->{url};
1852 my $new_url = $repos_root . $branch_from;
1853 print STDERR "Found possible branch point: ",
1854 "$new_url => ", $self->full_url, ", $r\n";
1855 $branch_from =~ s#^/##;
1856 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1857 unless ($gs) {
1858 my $ref_id = $self->{ref_id};
1859 $ref_id =~ s/\@\d+$//;
1860 $ref_id .= "\@$r";
1861 # just grow a tail if we're not unique enough :x
1862 $ref_id .= '-' while find_ref($ref_id);
1863 print STDERR "Initializing parent: $ref_id\n";
1864 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1866 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1867 if (!defined $r0 || !defined $parent) {
1868 my ($base, $head) = parse_revision_argument(0, $r);
1869 if ($base <= $r) {
1870 $gs->fetch($base, $r);
1872 ($r0, $parent) = $gs->last_rev_commit;
1874 if (defined $r0 && defined $parent) {
1875 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1876 my $ed;
1877 if ($self->ra->can_do_switch) {
1878 $self->assert_index_clean($parent);
1879 print STDERR "Following parent with do_switch\n";
1880 # do_switch works with svn/trunk >= r22312, but that
1881 # is not included with SVN 1.4.3 (the latest version
1882 # at the moment), so we can't rely on it
1883 $self->{last_commit} = $parent;
1884 $ed = SVN::Git::Fetcher->new($self);
1885 $gs->ra->gs_do_switch($r0, $rev, $gs,
1886 $self->full_url, $ed)
1887 or die "SVN connection failed somewhere...\n";
1888 } else {
1889 print STDERR "Following parent with do_update\n";
1890 $ed = SVN::Git::Fetcher->new($self);
1891 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1892 or die "SVN connection failed somewhere...\n";
1894 print STDERR "Successfully followed parent\n";
1895 return $self->make_log_entry($rev, [$parent], $ed);
1897 return undef;
1900 sub do_fetch {
1901 my ($self, $paths, $rev) = @_;
1902 my $ed;
1903 my ($last_rev, @parents);
1904 if (my $lc = $self->last_commit) {
1905 # we can have a branch that was deleted, then re-added
1906 # under the same name but copied from another path, in
1907 # which case we'll have multiple parents (we don't
1908 # want to break the original ref, nor lose copypath info):
1909 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1910 push @{$log_entry->{parents}}, $lc;
1911 return $log_entry;
1913 $ed = SVN::Git::Fetcher->new($self);
1914 $last_rev = $self->{last_rev};
1915 $ed->{c} = $lc;
1916 @parents = ($lc);
1917 } else {
1918 $last_rev = $rev;
1919 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1920 return $log_entry;
1922 $ed = SVN::Git::Fetcher->new($self);
1924 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1925 die "SVN connection failed somewhere...\n";
1927 $self->make_log_entry($rev, \@parents, $ed);
1930 sub get_untracked {
1931 my ($self, $ed) = @_;
1932 my @out;
1933 my $h = $ed->{empty};
1934 foreach (sort keys %$h) {
1935 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1936 push @out, " $act: " . uri_encode($_);
1937 warn "W: $act: $_\n";
1939 foreach my $t (qw/dir_prop file_prop/) {
1940 $h = $ed->{$t} or next;
1941 foreach my $path (sort keys %$h) {
1942 my $ppath = $path eq '' ? '.' : $path;
1943 foreach my $prop (sort keys %{$h->{$path}}) {
1944 next if $SKIP_PROP{$prop};
1945 my $v = $h->{$path}->{$prop};
1946 my $t_ppath_prop = "$t: " .
1947 uri_encode($ppath) . ' ' .
1948 uri_encode($prop);
1949 if (defined $v) {
1950 push @out, " +$t_ppath_prop " .
1951 uri_encode($v);
1952 } else {
1953 push @out, " -$t_ppath_prop";
1958 foreach my $t (qw/absent_file absent_directory/) {
1959 $h = $ed->{$t} or next;
1960 foreach my $parent (sort keys %$h) {
1961 foreach my $path (sort @{$h->{$parent}}) {
1962 push @out, " $t: " .
1963 uri_encode("$parent/$path");
1964 warn "W: $t: $parent/$path ",
1965 "Insufficient permissions?\n";
1969 \@out;
1972 sub parse_svn_date {
1973 my $date = shift || return '+0000 1970-01-01 00:00:00';
1974 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1975 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1976 croak "Unable to parse date: $date\n";
1977 "+0000 $Y-$m-$d $H:$M:$S";
1980 sub check_author {
1981 my ($author) = @_;
1982 if (!defined $author || length $author == 0) {
1983 $author = '(no author)';
1985 if (defined $::_authors && ! defined $::users{$author}) {
1986 die "Author: $author not defined in $::_authors file\n";
1988 $author;
1991 sub make_log_entry {
1992 my ($self, $rev, $parents, $ed) = @_;
1993 my $untracked = $self->get_untracked($ed);
1995 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1996 print $un "r$rev\n" or croak $!;
1997 print $un $_, "\n" foreach @$untracked;
1998 my %log_entry = ( parents => $parents || [], revision => $rev,
1999 log => '');
2001 my $headrev;
2002 my $logged = delete $self->{logged_rev_props};
2003 if (!$logged || $self->{-want_revprops}) {
2004 my $rp = $self->ra->rev_proplist($rev);
2005 foreach (sort keys %$rp) {
2006 my $v = $rp->{$_};
2007 if (/^svn:(author|date|log)$/) {
2008 $log_entry{$1} = $v;
2009 } elsif ($_ eq 'svm:headrev') {
2010 $headrev = $v;
2011 } else {
2012 print $un " rev_prop: ", uri_encode($_), ' ',
2013 uri_encode($v), "\n";
2016 } else {
2017 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2019 close $un or croak $!;
2021 $log_entry{date} = parse_svn_date($log_entry{date});
2022 $log_entry{log} .= "\n";
2023 my $author = $log_entry{author} = check_author($log_entry{author});
2024 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2025 : ($author, undef);
2026 if (defined $headrev && $self->use_svm_props) {
2027 if ($self->rewrite_root) {
2028 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2029 "options set!\n";
2031 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2032 # we don't want "SVM: initializing mirror for junk" ...
2033 return undef if $r == 0;
2034 my $svm = $self->svm;
2035 if ($uuid ne $svm->{uuid}) {
2036 die "UUID mismatch on SVM path:\n",
2037 "expected: $svm->{uuid}\n",
2038 " got: $uuid\n";
2040 my $full_url = $self->full_url;
2041 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2042 die "Failed to replace '$svm->{replace}' with ",
2043 "'$svm->{source}' in $full_url\n";
2044 # throw away username for storing in records
2045 remove_username($full_url);
2046 $log_entry{metadata} = "$full_url\@$r $uuid";
2047 $log_entry{svm_revision} = $r;
2048 $email ||= "$author\@$uuid"
2049 } elsif ($self->use_svnsync_props) {
2050 my $full_url = $self->svnsync->{url};
2051 $full_url .= "/$self->{path}" if length $self->{path};
2052 remove_username($full_url);
2053 my $uuid = $self->svnsync->{uuid};
2054 $log_entry{metadata} = "$full_url\@$rev $uuid";
2055 $email ||= "$author\@$uuid"
2056 } else {
2057 my $url = $self->metadata_url;
2058 remove_username($url);
2059 $log_entry{metadata} = "$url\@$rev " .
2060 $self->ra->get_uuid;
2061 $email ||= "$author\@" . $self->ra->get_uuid;
2063 $log_entry{name} = $name;
2064 $log_entry{email} = $email;
2065 \%log_entry;
2068 sub fetch {
2069 my ($self, $min_rev, $max_rev, @parents) = @_;
2070 my ($last_rev, $last_commit) = $self->last_rev_commit;
2071 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2072 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2075 sub set_tree_cb {
2076 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2077 $self->{inject_parents} = { $rev => $tree };
2078 $self->fetch(undef, undef);
2081 sub set_tree {
2082 my ($self, $tree) = (shift, shift);
2083 my $log_entry = ::get_commit_entry($tree);
2084 unless ($self->{last_rev}) {
2085 fatal("Must have an existing revision to commit\n");
2087 my %ed_opts = ( r => $self->{last_rev},
2088 log => $log_entry->{log},
2089 ra => $self->ra,
2090 tree_a => $self->{last_commit},
2091 tree_b => $tree,
2092 editor_cb => sub {
2093 $self->set_tree_cb($log_entry, $tree, @_) },
2094 svn_path => $self->{path} );
2095 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2096 print "No changes\nr$self->{last_rev} = $tree\n";
2100 sub rebuild {
2101 my ($self) = @_;
2102 my $db_path = $self->db_path;
2103 return if (-e $db_path && ! -z $db_path);
2104 return unless ::verify_ref($self->refname.'^0');
2105 if (-f $self->{db_root}) {
2106 rename $self->{db_root}, $db_path or die
2107 "rename $self->{db_root} => $db_path failed: $!\n";
2108 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2109 symlink $base, $self->{db_root} or die
2110 "symlink $base => $self->{db_root} failed: $!\n";
2111 return;
2113 print "Rebuilding $db_path ...\n";
2114 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2115 my $latest;
2116 my $full_url = $self->full_url;
2117 remove_username($full_url);
2118 my $svn_uuid;
2119 my $c;
2120 while (<$log>) {
2121 if ( m{^commit ($::sha1)$} ) {
2122 $c = $1;
2123 next;
2125 next unless s{^\s*(git-svn-id:)}{$1};
2126 my ($url, $rev, $uuid) = ::extract_metadata($_);
2127 remove_username($url);
2129 # ignore merges (from set-tree)
2130 next if (!defined $rev || !$uuid);
2132 # if we merged or otherwise started elsewhere, this is
2133 # how we break out of it
2134 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2135 ($full_url && $url && ($url ne $full_url))) {
2136 next;
2138 $latest ||= $rev;
2139 $svn_uuid ||= $uuid;
2141 $self->rev_db_set($rev, $c);
2142 print "r$rev = $c\n";
2144 command_close_pipe($log, $ctx);
2145 print "Done rebuilding $db_path\n";
2148 # rev_db:
2149 # Tie::File seems to be prone to offset errors if revisions get sparse,
2150 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2151 # one of my favorite modules is out :< Next up would be one of the DBM
2152 # modules, but I'm not sure which is most portable... So I'll just
2153 # go with something that's plain-text, but still capable of
2154 # being randomly accessed. So here's my ultra-simple fixed-width
2155 # database. All records are 40 characters + "\n", so it's easy to seek
2156 # to a revision: (41 * rev) is the byte offset.
2157 # A record of 40 0s denotes an empty revision.
2158 # And yes, it's still pretty fast (faster than Tie::File).
2159 # These files are disposable unless noMetadata or useSvmProps is set
2161 sub _rev_db_set {
2162 my ($fh, $rev, $commit) = @_;
2163 my $offset = $rev * 41;
2164 # assume that append is the common case:
2165 seek $fh, 0, 2 or croak $!;
2166 my $pos = tell $fh;
2167 if ($pos < $offset) {
2168 for (1 .. (($offset - $pos) / 41)) {
2169 print $fh (('0' x 40),"\n") or croak $!;
2172 seek $fh, $offset, 0 or croak $!;
2173 print $fh $commit,"\n" or croak $!;
2176 sub mkfile {
2177 my ($path) = @_;
2178 unless (-e $path) {
2179 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2180 mkpath([$dir]) unless -d $dir;
2181 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2182 close $fh or die "Couldn't close (create) $path: $!\n";
2186 sub rev_db_set {
2187 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2188 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2189 my $db = $self->db_path($uuid);
2190 my $db_lock = "$db.lock";
2191 my $sig;
2192 if ($update_ref) {
2193 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2194 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2196 mkfile($db);
2198 $LOCKFILES{$db_lock} = 1;
2199 my $sync;
2200 # both of these options make our .rev_db file very, very important
2201 # and we can't afford to lose it because rebuild() won't work
2202 if ($self->use_svm_props || $self->no_metadata) {
2203 $sync = 1;
2204 copy($db, $db_lock) or die "rev_db_set(@_): ",
2205 "Failed to copy: ",
2206 "$db => $db_lock ($!)\n";
2207 } else {
2208 rename $db, $db_lock or die "rev_db_set(@_): ",
2209 "Failed to rename: ",
2210 "$db => $db_lock ($!)\n";
2212 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2213 _rev_db_set($fh, $rev, $commit);
2214 if ($sync) {
2215 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2216 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2218 close $fh or croak $!;
2219 if ($update_ref) {
2220 $_head = $self;
2221 command_noisy('update-ref', '-m', "r$rev",
2222 $self->refname, $commit);
2224 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2225 "$db_lock => $db ($!)\n";
2226 delete $LOCKFILES{$db_lock};
2227 if ($update_ref) {
2228 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2229 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2230 kill $sig, $$ if defined $sig;
2234 sub rev_db_max {
2235 my ($self) = @_;
2236 $self->rebuild;
2237 my $db_path = $self->db_path;
2238 my @stat = stat $db_path or return 0;
2239 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2240 my $max = $stat[7] / 41;
2241 (($max > 0) ? $max - 1 : 0);
2244 sub rev_db_get {
2245 my ($self, $rev, $uuid) = @_;
2246 my $ret;
2247 my $offset = $rev * 41;
2248 my $db_path = $self->db_path($uuid);
2249 return undef unless -e $db_path;
2250 open my $fh, '<', $db_path or croak $!;
2251 if (sysseek($fh, $offset, 0) == $offset) {
2252 my $read = sysread($fh, $ret, 40);
2253 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2255 close $fh or croak $!;
2256 $ret;
2259 sub find_rev_before {
2260 my ($self, $rev, $eq_ok) = @_;
2261 --$rev unless $eq_ok;
2262 while ($rev > 0) {
2263 if (my $c = $self->rev_db_get($rev)) {
2264 return ($rev, $c);
2266 --$rev;
2268 return (undef, undef);
2271 sub _new {
2272 my ($class, $repo_id, $ref_id, $path) = @_;
2273 unless (defined $repo_id && length $repo_id) {
2274 $repo_id = $Git::SVN::default_repo_id;
2276 unless (defined $ref_id && length $ref_id) {
2277 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2279 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2280 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2281 $_[3] = $path = '' unless (defined $path);
2282 mkpath(["$ENV{GIT_DIR}/svn"]);
2283 bless {
2284 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2285 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2286 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2289 sub db_path {
2290 my ($self, $uuid) = @_;
2291 $uuid ||= $self->ra_uuid;
2292 "$self->{db_root}.$uuid";
2295 sub uri_encode {
2296 my ($f) = @_;
2297 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2301 sub remove_username {
2302 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2305 package Git::SVN::Prompt;
2306 use strict;
2307 use warnings;
2308 require SVN::Core;
2309 use vars qw/$_no_auth_cache $_username/;
2311 sub simple {
2312 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2313 $may_save = undef if $_no_auth_cache;
2314 $default_username = $_username if defined $_username;
2315 if (defined $default_username && length $default_username) {
2316 if (defined $realm && length $realm) {
2317 print STDERR "Authentication realm: $realm\n";
2318 STDERR->flush;
2320 $cred->username($default_username);
2321 } else {
2322 username($cred, $realm, $may_save, $pool);
2324 $cred->password(_read_password("Password for '" .
2325 $cred->username . "': ", $realm));
2326 $cred->may_save($may_save);
2327 $SVN::_Core::SVN_NO_ERROR;
2330 sub ssl_server_trust {
2331 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2332 $may_save = undef if $_no_auth_cache;
2333 print STDERR "Error validating server certificate for '$realm':\n";
2334 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2335 print STDERR " - The certificate is not issued by a trusted ",
2336 "authority. Use the\n",
2337 " fingerprint to validate the certificate manually!\n";
2339 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2340 print STDERR " - The certificate hostname does not match.\n";
2342 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2343 print STDERR " - The certificate is not yet valid.\n";
2345 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2346 print STDERR " - The certificate has expired.\n";
2348 if ($failures & $SVN::Auth::SSL::OTHER) {
2349 print STDERR " - The certificate has an unknown error.\n";
2351 printf STDERR
2352 "Certificate information:\n".
2353 " - Hostname: %s\n".
2354 " - Valid: from %s until %s\n".
2355 " - Issuer: %s\n".
2356 " - Fingerprint: %s\n",
2357 map $cert_info->$_, qw(hostname valid_from valid_until
2358 issuer_dname fingerprint);
2359 my $choice;
2360 prompt:
2361 print STDERR $may_save ?
2362 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2363 "(R)eject or accept (t)emporarily? ";
2364 STDERR->flush;
2365 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2366 if ($choice =~ /^t$/i) {
2367 $cred->may_save(undef);
2368 } elsif ($choice =~ /^r$/i) {
2369 return -1;
2370 } elsif ($may_save && $choice =~ /^p$/i) {
2371 $cred->may_save($may_save);
2372 } else {
2373 goto prompt;
2375 $cred->accepted_failures($failures);
2376 $SVN::_Core::SVN_NO_ERROR;
2379 sub ssl_client_cert {
2380 my ($cred, $realm, $may_save, $pool) = @_;
2381 $may_save = undef if $_no_auth_cache;
2382 print STDERR "Client certificate filename: ";
2383 STDERR->flush;
2384 chomp(my $filename = <STDIN>);
2385 $cred->cert_file($filename);
2386 $cred->may_save($may_save);
2387 $SVN::_Core::SVN_NO_ERROR;
2390 sub ssl_client_cert_pw {
2391 my ($cred, $realm, $may_save, $pool) = @_;
2392 $may_save = undef if $_no_auth_cache;
2393 $cred->password(_read_password("Password: ", $realm));
2394 $cred->may_save($may_save);
2395 $SVN::_Core::SVN_NO_ERROR;
2398 sub username {
2399 my ($cred, $realm, $may_save, $pool) = @_;
2400 $may_save = undef if $_no_auth_cache;
2401 if (defined $realm && length $realm) {
2402 print STDERR "Authentication realm: $realm\n";
2404 my $username;
2405 if (defined $_username) {
2406 $username = $_username;
2407 } else {
2408 print STDERR "Username: ";
2409 STDERR->flush;
2410 chomp($username = <STDIN>);
2412 $cred->username($username);
2413 $cred->may_save($may_save);
2414 $SVN::_Core::SVN_NO_ERROR;
2417 sub _read_password {
2418 my ($prompt, $realm) = @_;
2419 print STDERR $prompt;
2420 STDERR->flush;
2421 require Term::ReadKey;
2422 Term::ReadKey::ReadMode('noecho');
2423 my $password = '';
2424 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2425 last if $key =~ /[\012\015]/; # \n\r
2426 $password .= $key;
2428 Term::ReadKey::ReadMode('restore');
2429 print STDERR "\n";
2430 STDERR->flush;
2431 $password;
2434 package main;
2437 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2438 $SVN::Node::dir.$SVN::Node::unknown.
2439 $SVN::Node::none.$SVN::Node::file.
2440 $SVN::Node::dir.$SVN::Node::unknown.
2441 $SVN::Auth::SSL::CNMISMATCH.
2442 $SVN::Auth::SSL::NOTYETVALID.
2443 $SVN::Auth::SSL::EXPIRED.
2444 $SVN::Auth::SSL::UNKNOWNCA.
2445 $SVN::Auth::SSL::OTHER;
2448 package SVN::Git::Fetcher;
2449 use vars qw/@ISA/;
2450 use strict;
2451 use warnings;
2452 use Carp qw/croak/;
2453 use IO::File qw//;
2454 use Digest::MD5;
2456 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2457 sub new {
2458 my ($class, $git_svn) = @_;
2459 my $self = SVN::Delta::Editor->new;
2460 bless $self, $class;
2461 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2462 $self->{empty} = {};
2463 $self->{dir_prop} = {};
2464 $self->{file_prop} = {};
2465 $self->{absent_dir} = {};
2466 $self->{absent_file} = {};
2467 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2468 $self;
2471 sub set_path_strip {
2472 my ($self, $path) = @_;
2473 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2476 sub open_root {
2477 { path => '' };
2480 sub open_directory {
2481 my ($self, $path, $pb, $rev) = @_;
2482 { path => $path };
2485 sub git_path {
2486 my ($self, $path) = @_;
2487 if ($self->{path_strip}) {
2488 $path =~ s!$self->{path_strip}!! or
2489 die "Failed to strip path '$path' ($self->{path_strip})\n";
2491 $path;
2494 sub delete_entry {
2495 my ($self, $path, $rev, $pb) = @_;
2497 my $gpath = $self->git_path($path);
2498 return undef if ($gpath eq '');
2500 # remove entire directories.
2501 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2502 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2503 -r --name-only -z/,
2504 $self->{c}, '--', $gpath);
2505 local $/ = "\0";
2506 while (<$ls>) {
2507 chomp;
2508 $self->{gii}->remove($_);
2509 print "\tD\t$_\n" unless $::_q;
2511 print "\tD\t$gpath/\n" unless $::_q;
2512 command_close_pipe($ls, $ctx);
2513 $self->{empty}->{$path} = 0
2514 } else {
2515 $self->{gii}->remove($gpath);
2516 print "\tD\t$gpath\n" unless $::_q;
2518 undef;
2521 sub open_file {
2522 my ($self, $path, $pb, $rev) = @_;
2523 my $gpath = $self->git_path($path);
2524 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2525 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2526 unless (defined $mode && defined $blob) {
2527 die "$path was not found in commit $self->{c} (r$rev)\n";
2529 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2530 pool => SVN::Pool->new, action => 'M' };
2533 sub add_file {
2534 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2535 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2536 delete $self->{empty}->{$dir};
2537 { path => $path, mode_a => 100644, mode_b => 100644,
2538 pool => SVN::Pool->new, action => 'A' };
2541 sub add_directory {
2542 my ($self, $path, $cp_path, $cp_rev) = @_;
2543 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2544 delete $self->{empty}->{$dir};
2545 $self->{empty}->{$path} = 1;
2546 { path => $path };
2549 sub change_dir_prop {
2550 my ($self, $db, $prop, $value) = @_;
2551 $self->{dir_prop}->{$db->{path}} ||= {};
2552 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2553 undef;
2556 sub absent_directory {
2557 my ($self, $path, $pb) = @_;
2558 $self->{absent_dir}->{$pb->{path}} ||= [];
2559 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2560 undef;
2563 sub absent_file {
2564 my ($self, $path, $pb) = @_;
2565 $self->{absent_file}->{$pb->{path}} ||= [];
2566 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2567 undef;
2570 sub change_file_prop {
2571 my ($self, $fb, $prop, $value) = @_;
2572 if ($prop eq 'svn:executable') {
2573 if ($fb->{mode_b} != 120000) {
2574 $fb->{mode_b} = defined $value ? 100755 : 100644;
2576 } elsif ($prop eq 'svn:special') {
2577 $fb->{mode_b} = defined $value ? 120000 : 100644;
2578 } else {
2579 $self->{file_prop}->{$fb->{path}} ||= {};
2580 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2582 undef;
2585 sub apply_textdelta {
2586 my ($self, $fb, $exp) = @_;
2587 my $fh = IO::File->new_tmpfile;
2588 $fh->autoflush(1);
2589 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2590 # (but $base does not,) so dup() it for reading in close_file
2591 open my $dup, '<&', $fh or croak $!;
2592 my $base = IO::File->new_tmpfile;
2593 $base->autoflush(1);
2594 if ($fb->{blob}) {
2595 defined (my $pid = fork) or croak $!;
2596 if (!$pid) {
2597 open STDOUT, '>&', $base or croak $!;
2598 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2599 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2601 waitpid $pid, 0;
2602 croak $? if $?;
2604 if (defined $exp) {
2605 seek $base, 0, 0 or croak $!;
2606 my $md5 = Digest::MD5->new;
2607 $md5->addfile($base);
2608 my $got = $md5->hexdigest;
2609 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2610 "expected: $exp\n",
2611 " got: $got\n" if ($got ne $exp);
2614 seek $base, 0, 0 or croak $!;
2615 $fb->{fh} = $dup;
2616 $fb->{base} = $base;
2617 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2620 sub close_file {
2621 my ($self, $fb, $exp) = @_;
2622 my $hash;
2623 my $path = $self->git_path($fb->{path});
2624 if (my $fh = $fb->{fh}) {
2625 if (defined $exp) {
2626 seek($fh, 0, 0) or croak $!;
2627 my $md5 = Digest::MD5->new;
2628 $md5->addfile($fh);
2629 my $got = $md5->hexdigest;
2630 if ($got ne $exp) {
2631 die "Checksum mismatch: $path\n",
2632 "expected: $exp\n got: $got\n";
2635 sysseek($fh, 0, 0) or croak $!;
2636 if ($fb->{mode_b} == 120000) {
2637 sysread($fh, my $buf, 5) == 5 or croak $!;
2638 $buf eq 'link ' or die "$path has mode 120000",
2639 "but is not a link\n";
2641 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2642 if (!$pid) {
2643 open STDIN, '<&', $fh or croak $!;
2644 exec qw/git-hash-object -w --stdin/ or croak $!;
2646 chomp($hash = do { local $/; <$out> });
2647 close $out or croak $!;
2648 close $fh or croak $!;
2649 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2650 close $fb->{base} or croak $!;
2651 } else {
2652 $hash = $fb->{blob} or die "no blob information\n";
2654 $fb->{pool}->clear;
2655 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2656 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2657 undef;
2660 sub abort_edit {
2661 my $self = shift;
2662 $self->{nr} = $self->{gii}->{nr};
2663 delete $self->{gii};
2664 $self->SUPER::abort_edit(@_);
2667 sub close_edit {
2668 my $self = shift;
2669 $self->{git_commit_ok} = 1;
2670 $self->{nr} = $self->{gii}->{nr};
2671 delete $self->{gii};
2672 $self->SUPER::close_edit(@_);
2675 package SVN::Git::Editor;
2676 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2677 use strict;
2678 use warnings;
2679 use Carp qw/croak/;
2680 use IO::File;
2681 use Digest::MD5;
2683 sub new {
2684 my ($class, $opts) = @_;
2685 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2686 die "$_ required!\n" unless (defined $opts->{$_});
2689 my $pool = SVN::Pool->new;
2690 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2691 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2692 $opts->{r}, $mods);
2694 # $opts->{ra} functions should not be used after this:
2695 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2696 $opts->{editor_cb}, $pool);
2697 my $self = SVN::Delta::Editor->new(@ce, $pool);
2698 bless $self, $class;
2699 foreach (qw/svn_path r tree_a tree_b/) {
2700 $self->{$_} = $opts->{$_};
2702 $self->{url} = $opts->{ra}->{url};
2703 $self->{mods} = $mods;
2704 $self->{types} = $types;
2705 $self->{pool} = $pool;
2706 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2707 $self->{rm} = { };
2708 $self->{path_prefix} = length $self->{svn_path} ?
2709 "$self->{svn_path}/" : '';
2710 return $self;
2713 sub generate_diff {
2714 my ($tree_a, $tree_b) = @_;
2715 my @diff_tree = qw(diff-tree -z -r);
2716 if ($_cp_similarity) {
2717 push @diff_tree, "-C$_cp_similarity";
2718 } else {
2719 push @diff_tree, '-C';
2721 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2722 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2723 push @diff_tree, $tree_a, $tree_b;
2724 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2725 local $/ = "\0";
2726 my $state = 'meta';
2727 my @mods;
2728 while (<$diff_fh>) {
2729 chomp $_; # this gets rid of the trailing "\0"
2730 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2731 $::sha1\s($::sha1)\s
2732 ([MTCRAD])\d*$/xo) {
2733 push @mods, { mode_a => $1, mode_b => $2,
2734 sha1_b => $3, chg => $4 };
2735 if ($4 =~ /^(?:C|R)$/) {
2736 $state = 'file_a';
2737 } else {
2738 $state = 'file_b';
2740 } elsif ($state eq 'file_a') {
2741 my $x = $mods[$#mods] or croak "Empty array\n";
2742 if ($x->{chg} !~ /^(?:C|R)$/) {
2743 croak "Error parsing $_, $x->{chg}\n";
2745 $x->{file_a} = $_;
2746 $state = 'file_b';
2747 } elsif ($state eq 'file_b') {
2748 my $x = $mods[$#mods] or croak "Empty array\n";
2749 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2750 croak "Error parsing $_, $x->{chg}\n";
2752 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2753 croak "Error parsing $_, $x->{chg}\n";
2755 $x->{file_b} = $_;
2756 $state = 'meta';
2757 } else {
2758 croak "Error parsing $_\n";
2761 command_close_pipe($diff_fh, $ctx);
2762 \@mods;
2765 sub check_diff_paths {
2766 my ($ra, $pfx, $rev, $mods) = @_;
2767 my %types;
2768 $pfx .= '/' if length $pfx;
2770 sub type_diff_paths {
2771 my ($ra, $types, $path, $rev) = @_;
2772 my @p = split m#/+#, $path;
2773 my $c = shift @p;
2774 unless (defined $types->{$c}) {
2775 $types->{$c} = $ra->check_path($c, $rev);
2777 while (@p) {
2778 $c .= '/' . shift @p;
2779 next if defined $types->{$c};
2780 $types->{$c} = $ra->check_path($c, $rev);
2784 foreach my $m (@$mods) {
2785 foreach my $f (qw/file_a file_b/) {
2786 next unless defined $m->{$f};
2787 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2788 if (length $pfx.$dir && ! defined $types{$dir}) {
2789 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2793 \%types;
2796 sub split_path {
2797 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2800 sub repo_path {
2801 my ($self, $path) = @_;
2802 $self->{path_prefix}.(defined $path ? $path : '');
2805 sub url_path {
2806 my ($self, $path) = @_;
2807 if ($self->{url} =~ m#^https?://#) {
2808 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2810 $self->{url} . '/' . $self->repo_path($path);
2813 sub rmdirs {
2814 my ($self) = @_;
2815 my $rm = $self->{rm};
2816 delete $rm->{''}; # we never delete the url we're tracking
2817 return unless %$rm;
2819 foreach (keys %$rm) {
2820 my @d = split m#/#, $_;
2821 my $c = shift @d;
2822 $rm->{$c} = 1;
2823 while (@d) {
2824 $c .= '/' . shift @d;
2825 $rm->{$c} = 1;
2828 delete $rm->{$self->{svn_path}};
2829 delete $rm->{''}; # we never delete the url we're tracking
2830 return unless %$rm;
2832 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2833 $self->{tree_b});
2834 local $/ = "\0";
2835 while (<$fh>) {
2836 chomp;
2837 my @dn = split m#/#, $_;
2838 while (pop @dn) {
2839 delete $rm->{join '/', @dn};
2841 unless (%$rm) {
2842 close $fh;
2843 return;
2846 command_close_pipe($fh, $ctx);
2848 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2849 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2850 $self->close_directory($bat->{$d}, $p);
2851 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2852 print "\tD+\t$d/\n" unless $::_q;
2853 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2854 delete $bat->{$d};
2858 sub open_or_add_dir {
2859 my ($self, $full_path, $baton) = @_;
2860 my $t = $self->{types}->{$full_path};
2861 if (!defined $t) {
2862 die "$full_path not known in r$self->{r} or we have a bug!\n";
2864 if ($t == $SVN::Node::none) {
2865 return $self->add_directory($full_path, $baton,
2866 undef, -1, $self->{pool});
2867 } elsif ($t == $SVN::Node::dir) {
2868 return $self->open_directory($full_path, $baton,
2869 $self->{r}, $self->{pool});
2871 print STDERR "$full_path already exists in repository at ",
2872 "r$self->{r} and it is not a directory (",
2873 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2874 exit 1;
2877 sub ensure_path {
2878 my ($self, $path) = @_;
2879 my $bat = $self->{bat};
2880 my $repo_path = $self->repo_path($path);
2881 return $bat->{''} unless (length $repo_path);
2882 my @p = split m#/+#, $repo_path;
2883 my $c = shift @p;
2884 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2885 while (@p) {
2886 my $c0 = $c;
2887 $c .= '/' . shift @p;
2888 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2890 return $bat->{$c};
2893 sub A {
2894 my ($self, $m) = @_;
2895 my ($dir, $file) = split_path($m->{file_b});
2896 my $pbat = $self->ensure_path($dir);
2897 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2898 undef, -1);
2899 print "\tA\t$m->{file_b}\n" unless $::_q;
2900 $self->chg_file($fbat, $m);
2901 $self->close_file($fbat,undef,$self->{pool});
2904 sub C {
2905 my ($self, $m) = @_;
2906 my ($dir, $file) = split_path($m->{file_b});
2907 my $pbat = $self->ensure_path($dir);
2908 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2909 $self->url_path($m->{file_a}), $self->{r});
2910 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2911 $self->chg_file($fbat, $m);
2912 $self->close_file($fbat,undef,$self->{pool});
2915 sub delete_entry {
2916 my ($self, $path, $pbat) = @_;
2917 my $rpath = $self->repo_path($path);
2918 my ($dir, $file) = split_path($rpath);
2919 $self->{rm}->{$dir} = 1;
2920 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2923 sub R {
2924 my ($self, $m) = @_;
2925 my ($dir, $file) = split_path($m->{file_b});
2926 my $pbat = $self->ensure_path($dir);
2927 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2928 $self->url_path($m->{file_a}), $self->{r});
2929 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2930 $self->chg_file($fbat, $m);
2931 $self->close_file($fbat,undef,$self->{pool});
2933 ($dir, $file) = split_path($m->{file_a});
2934 $pbat = $self->ensure_path($dir);
2935 $self->delete_entry($m->{file_a}, $pbat);
2938 sub M {
2939 my ($self, $m) = @_;
2940 my ($dir, $file) = split_path($m->{file_b});
2941 my $pbat = $self->ensure_path($dir);
2942 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2943 $pbat,$self->{r},$self->{pool});
2944 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2945 $self->chg_file($fbat, $m);
2946 $self->close_file($fbat,undef,$self->{pool});
2949 sub T { shift->M(@_) }
2951 sub change_file_prop {
2952 my ($self, $fbat, $pname, $pval) = @_;
2953 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2956 sub chg_file {
2957 my ($self, $fbat, $m) = @_;
2958 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2959 $self->change_file_prop($fbat,'svn:executable','*');
2960 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2961 $self->change_file_prop($fbat,'svn:executable',undef);
2963 my $fh = IO::File->new_tmpfile or croak $!;
2964 if ($m->{mode_b} =~ /^120/) {
2965 print $fh 'link ' or croak $!;
2966 $self->change_file_prop($fbat,'svn:special','*');
2967 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2968 $self->change_file_prop($fbat,'svn:special',undef);
2970 defined(my $pid = fork) or croak $!;
2971 if (!$pid) {
2972 open STDOUT, '>&', $fh or croak $!;
2973 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2975 waitpid $pid, 0;
2976 croak $? if $?;
2977 $fh->flush == 0 or croak $!;
2978 seek $fh, 0, 0 or croak $!;
2980 my $md5 = Digest::MD5->new;
2981 $md5->addfile($fh) or croak $!;
2982 seek $fh, 0, 0 or croak $!;
2984 my $exp = $md5->hexdigest;
2985 my $pool = SVN::Pool->new;
2986 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2987 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2988 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2989 $pool->clear;
2991 close $fh or croak $!;
2994 sub D {
2995 my ($self, $m) = @_;
2996 my ($dir, $file) = split_path($m->{file_b});
2997 my $pbat = $self->ensure_path($dir);
2998 print "\tD\t$m->{file_b}\n" unless $::_q;
2999 $self->delete_entry($m->{file_b}, $pbat);
3002 sub close_edit {
3003 my ($self) = @_;
3004 my ($p,$bat) = ($self->{pool}, $self->{bat});
3005 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3006 next if $_ eq '';
3007 $self->close_directory($bat->{$_}, $p);
3009 $self->close_directory($bat->{''}, $p);
3010 $self->SUPER::close_edit($p);
3011 $p->clear;
3014 sub abort_edit {
3015 my ($self) = @_;
3016 $self->SUPER::abort_edit($self->{pool});
3019 sub DESTROY {
3020 my $self = shift;
3021 $self->SUPER::DESTROY(@_);
3022 $self->{pool}->clear;
3025 # this drives the editor
3026 sub apply_diff {
3027 my ($self) = @_;
3028 my $mods = $self->{mods};
3029 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3030 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3031 my $f = $m->{chg};
3032 if (defined $o{$f}) {
3033 $self->$f($m);
3034 } else {
3035 fatal("Invalid change type: $f\n");
3038 $self->rmdirs if $_rmdir;
3039 if (@$mods == 0) {
3040 $self->abort_edit;
3041 } else {
3042 $self->close_edit;
3044 return scalar @$mods;
3047 package Git::SVN::Ra;
3048 use vars qw/@ISA $config_dir $_log_window_size/;
3049 use strict;
3050 use warnings;
3051 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3053 BEGIN {
3054 # enforce temporary pool usage for some simple functions
3055 no strict 'refs';
3056 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3057 my $SUPER = "SUPER::$f";
3058 *$f = sub {
3059 my $self = shift;
3060 my $pool = SVN::Pool->new;
3061 my @ret = $self->$SUPER(@_,$pool);
3062 $pool->clear;
3063 wantarray ? @ret : $ret[0];
3068 sub new {
3069 my ($class, $url) = @_;
3070 $url =~ s!/+$!!;
3071 return $RA if ($RA && $RA->{url} eq $url);
3073 SVN::_Core::svn_config_ensure($config_dir, undef);
3074 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3075 SVN::Client::get_simple_provider(),
3076 SVN::Client::get_ssl_server_trust_file_provider(),
3077 SVN::Client::get_simple_prompt_provider(
3078 \&Git::SVN::Prompt::simple, 2),
3079 SVN::Client::get_ssl_client_cert_file_provider(),
3080 SVN::Client::get_ssl_client_cert_prompt_provider(
3081 \&Git::SVN::Prompt::ssl_client_cert, 2),
3082 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3083 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3084 SVN::Client::get_username_provider(),
3085 SVN::Client::get_ssl_server_trust_prompt_provider(
3086 \&Git::SVN::Prompt::ssl_server_trust),
3087 SVN::Client::get_username_prompt_provider(
3088 \&Git::SVN::Prompt::username, 2),
3090 my $config = SVN::Core::config_get_config($config_dir);
3091 $RA = undef;
3092 my $self = SVN::Ra->new(url => $url, auth => $baton,
3093 config => $config,
3094 pool => SVN::Pool->new,
3095 auth_provider_callbacks => $callbacks);
3096 $self->{svn_path} = $url;
3097 $self->{repos_root} = $self->get_repos_root;
3098 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3099 $self->{cache} = { check_path => { r => 0, data => {} },
3100 get_dir => { r => 0, data => {} } };
3101 $RA = bless $self, $class;
3104 sub check_path {
3105 my ($self, $path, $r) = @_;
3106 my $cache = $self->{cache}->{check_path};
3107 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3108 return $cache->{data}->{$path};
3110 my $pool = SVN::Pool->new;
3111 my $t = $self->SUPER::check_path($path, $r, $pool);
3112 $pool->clear;
3113 if ($r != $cache->{r}) {
3114 %{$cache->{data}} = ();
3115 $cache->{r} = $r;
3117 $cache->{data}->{$path} = $t;
3120 sub get_dir {
3121 my ($self, $dir, $r) = @_;
3122 my $cache = $self->{cache}->{get_dir};
3123 if ($r == $cache->{r}) {
3124 if (my $x = $cache->{data}->{$dir}) {
3125 return wantarray ? @$x : $x->[0];
3128 my $pool = SVN::Pool->new;
3129 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3130 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3131 $pool->clear;
3132 if ($r != $cache->{r}) {
3133 %{$cache->{data}} = ();
3134 $cache->{r} = $r;
3136 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3137 wantarray ? (\%dirents, $r, $props) : \%dirents;
3140 sub DESTROY {
3141 # do not call the real DESTROY since we store ourselves in $RA
3144 sub get_log {
3145 my ($self, @args) = @_;
3146 my $pool = SVN::Pool->new;
3147 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3148 my $ret = $self->SUPER::get_log(@args, $pool);
3149 $pool->clear;
3150 $ret;
3153 sub get_commit_editor {
3154 my ($self, $log, $cb, $pool) = @_;
3155 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3156 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3159 sub gs_do_update {
3160 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3161 my $new = ($rev_a == $rev_b);
3162 my $path = $gs->{path};
3164 if ($new && -e $gs->{index}) {
3165 unlink $gs->{index} or die
3166 "Couldn't unlink index: $gs->{index}: $!\n";
3168 my $pool = SVN::Pool->new;
3169 $editor->set_path_strip($path);
3170 my (@pc) = split m#/#, $path;
3171 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3172 1, $editor, $pool);
3173 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3175 # Since we can't rely on svn_ra_reparent being available, we'll
3176 # just have to do some magic with set_path to make it so
3177 # we only want a partial path.
3178 my $sp = '';
3179 my $final = join('/', @pc);
3180 while (@pc) {
3181 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3182 $sp .= '/' if length $sp;
3183 $sp .= shift @pc;
3185 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3187 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3189 $reporter->finish_report($pool);
3190 $pool->clear;
3191 $editor->{git_commit_ok};
3194 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3195 # svn_ra_reparent didn't work before 1.4)
3196 sub gs_do_switch {
3197 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3198 my $path = $gs->{path};
3199 my $pool = SVN::Pool->new;
3201 my $full_url = $self->{url};
3202 my $old_url = $full_url;
3203 $full_url .= "/$path" if length $path;
3204 my ($ra, $reparented);
3205 if ($old_url ne $full_url) {
3206 if ($old_url !~ m#^svn(\+ssh)?://#) {
3207 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3208 $pool);
3209 $self->{url} = $full_url;
3210 $reparented = 1;
3211 } else {
3212 $_[0] = undef;
3213 $self = undef;
3214 $RA = undef;
3215 $ra = Git::SVN::Ra->new($full_url);
3216 $ra_invalid = 1;
3219 $ra ||= $self;
3220 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3221 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3222 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3223 $reporter->finish_report($pool);
3225 if ($reparented) {
3226 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3227 $self->{url} = $old_url;
3230 $pool->clear;
3231 $editor->{git_commit_ok};
3234 sub longest_common_path {
3235 my ($gsv, $globs) = @_;
3236 my %common;
3237 my $common_max = scalar @$gsv;
3239 foreach my $gs (@$gsv) {
3240 my @tmp = split m#/#, $gs->{path};
3241 my $p = '';
3242 foreach (@tmp) {
3243 $p .= length($p) ? "/$_" : $_;
3244 $common{$p} ||= 0;
3245 $common{$p}++;
3248 $globs ||= [];
3249 $common_max += scalar @$globs;
3250 foreach my $glob (@$globs) {
3251 my @tmp = split m#/#, $glob->{path}->{left};
3252 my $p = '';
3253 foreach (@tmp) {
3254 $p .= length($p) ? "/$_" : $_;
3255 $common{$p} ||= 0;
3256 $common{$p}++;
3260 my $longest_path = '';
3261 foreach (sort {length $b <=> length $a} keys %common) {
3262 if ($common{$_} == $common_max) {
3263 $longest_path = $_;
3264 last;
3267 $longest_path;
3270 sub gs_fetch_loop_common {
3271 my ($self, $base, $head, $gsv, $globs) = @_;
3272 return if ($base > $head);
3273 my $inc = $_log_window_size;
3274 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3275 my $longest_path = longest_common_path($gsv, $globs);
3276 my $ra_url = $self->{url};
3277 while (1) {
3278 my %revs;
3279 my $err;
3280 my $err_handler = $SVN::Error::handler;
3281 $SVN::Error::handler = sub {
3282 ($err) = @_;
3283 skip_unknown_revs($err);
3285 sub _cb {
3286 my ($paths, $r, $author, $date, $log) = @_;
3287 [ dup_changed_paths($paths),
3288 { author => $author, date => $date, log => $log } ];
3290 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3291 sub { $revs{$_[1]} = _cb(@_) });
3292 if ($err && $max >= $head) {
3293 print STDERR "Path '$longest_path' ",
3294 "was probably deleted:\n",
3295 $err->expanded_message,
3296 "\nWill attempt to follow ",
3297 "revisions r$min .. r$max ",
3298 "committed before the deletion\n";
3299 my $hi = $max;
3300 while (--$hi >= $min) {
3301 my $ok;
3302 $self->get_log([$longest_path], $min, $hi,
3303 0, 1, 1, sub {
3304 $ok ||= $_[1];
3305 $revs{$_[1]} = _cb(@_) });
3306 if ($ok) {
3307 print STDERR "r$min .. r$ok OK\n";
3308 last;
3312 $SVN::Error::handler = $err_handler;
3314 my %exists = map { $_->{path} => $_ } @$gsv;
3315 foreach my $r (sort {$a <=> $b} keys %revs) {
3316 my ($paths, $logged) = @{$revs{$r}};
3318 foreach my $gs ($self->match_globs(\%exists, $paths,
3319 $globs, $r)) {
3320 if ($gs->rev_db_max >= $r) {
3321 next;
3323 next unless $gs->match_paths($paths, $r);
3324 $gs->{logged_rev_props} = $logged;
3325 if (my $last_commit = $gs->last_commit) {
3326 $gs->assert_index_clean($last_commit);
3328 my $log_entry = $gs->do_fetch($paths, $r);
3329 if ($log_entry) {
3330 $gs->do_git_commit($log_entry);
3333 foreach my $g (@$globs) {
3334 my $k = "svn-remote.$g->{remote}." .
3335 "$g->{t}-maxRev";
3336 Git::SVN::tmp_config($k, $r);
3338 if ($ra_invalid) {
3339 $_[0] = undef;
3340 $self = undef;
3341 $RA = undef;
3342 $self = Git::SVN::Ra->new($ra_url);
3343 $ra_invalid = undef;
3346 # pre-fill the .rev_db since it'll eventually get filled in
3347 # with '0' x40 if something new gets committed
3348 foreach my $gs (@$gsv) {
3349 next if defined $gs->rev_db_get($max);
3350 $gs->rev_db_set($max, 0 x40);
3352 foreach my $g (@$globs) {
3353 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3354 Git::SVN::tmp_config($k, $max);
3356 last if $max >= $head;
3357 $min = $max + 1;
3358 $max += $inc;
3359 $max = $head if ($max > $head);
3363 sub match_globs {
3364 my ($self, $exists, $paths, $globs, $r) = @_;
3366 sub get_dir_check {
3367 my ($self, $exists, $g, $r) = @_;
3368 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3369 return unless scalar @x == 3;
3370 my $dirents = $x[0];
3371 foreach my $de (keys %$dirents) {
3372 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3373 my $p = $g->{path}->full_path($de);
3374 next if $exists->{$p};
3375 next if (length $g->{path}->{right} &&
3376 ($self->check_path($p, $r) !=
3377 $SVN::Node::dir));
3378 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3379 $g->{ref}->full_path($de), 1);
3382 foreach my $g (@$globs) {
3383 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3384 if ($path->{action} =~ /^[AR]$/) {
3385 get_dir_check($self, $exists, $g, $r);
3388 foreach (keys %$paths) {
3389 if (/$g->{path}->{left_regex}/ &&
3390 !/$g->{path}->{regex}/) {
3391 next if $paths->{$_}->{action} !~ /^[AR]$/;
3392 get_dir_check($self, $exists, $g, $r);
3394 next unless /$g->{path}->{regex}/;
3395 my $p = $1;
3396 my $pathname = $g->{path}->full_path($p);
3397 next if $exists->{$pathname};
3398 next if ($self->check_path($pathname, $r) !=
3399 $SVN::Node::dir);
3400 $exists->{$pathname} = Git::SVN->init(
3401 $self->{url}, $pathname, undef,
3402 $g->{ref}->full_path($p), 1);
3404 my $c = '';
3405 foreach (split m#/#, $g->{path}->{left}) {
3406 $c .= "/$_";
3407 next unless ($paths->{$c} &&
3408 ($paths->{$c}->{action} =~ /^[AR]$/));
3409 get_dir_check($self, $exists, $g, $r);
3412 values %$exists;
3415 sub minimize_url {
3416 my ($self) = @_;
3417 return $self->{url} if ($self->{url} eq $self->{repos_root});
3418 my $url = $self->{repos_root};
3419 my @components = split(m!/!, $self->{svn_path});
3420 my $c = '';
3421 do {
3422 $url .= "/$c" if length $c;
3423 eval { (ref $self)->new($url)->get_latest_revnum };
3424 } while ($@ && ($c = shift @components));
3425 $url;
3428 sub can_do_switch {
3429 my $self = shift;
3430 unless (defined $can_do_switch) {
3431 my $pool = SVN::Pool->new;
3432 my $rep = eval {
3433 $self->do_switch(1, '', 0, $self->{url},
3434 SVN::Delta::Editor->new, $pool);
3436 if ($@) {
3437 $can_do_switch = 0;
3438 } else {
3439 $rep->abort_report($pool);
3440 $can_do_switch = 1;
3442 $pool->clear;
3444 $can_do_switch;
3447 sub skip_unknown_revs {
3448 my ($err) = @_;
3449 my $errno = $err->apr_err();
3450 # Maybe the branch we're tracking didn't
3451 # exist when the repo started, so it's
3452 # not an error if it doesn't, just continue
3454 # Wonderfully consistent library, eh?
3455 # 160013 - svn:// and file://
3456 # 175002 - http(s)://
3457 # 175007 - http(s):// (this repo required authorization, too...)
3458 # More codes may be discovered later...
3459 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3460 my $err_key = $err->expanded_message;
3461 # revision numbers change every time, filter them out
3462 $err_key =~ s/\d+/\0/g;
3463 $err_key = "$errno\0$err_key";
3464 unless ($ignored_err{$err_key}) {
3465 warn "W: Ignoring error from SVN, path probably ",
3466 "does not exist: ($errno): ",
3467 $err->expanded_message,"\n";
3468 $ignored_err{$err_key} = 1;
3470 return;
3472 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3475 # svn_log_changed_path_t objects passed to get_log are likely to be
3476 # overwritten even if only the refs are copied to an external variable,
3477 # so we should dup the structures in their entirety. Using an externally
3478 # passed pool (instead of our temporary and quickly cleared pool in
3479 # Git::SVN::Ra) does not help matters at all...
3480 sub dup_changed_paths {
3481 my ($paths) = @_;
3482 return undef unless $paths;
3483 my %ret;
3484 foreach my $p (keys %$paths) {
3485 my $i = $paths->{$p};
3486 my %s = map { $_ => $i->$_ }
3487 qw/copyfrom_path copyfrom_rev action/;
3488 $ret{$p} = \%s;
3490 \%ret;
3493 package Git::SVN::Log;
3494 use strict;
3495 use warnings;
3496 use POSIX qw/strftime/;
3497 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3498 %rusers $show_commit $incremental/;
3499 my $l_fmt;
3501 sub cmt_showable {
3502 my ($c) = @_;
3503 return 1 if defined $c->{r};
3505 # big commit message got truncated by the 16k pretty buffer in rev-list
3506 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3507 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3508 @{$c->{l}} = ();
3509 my @log = command(qw/cat-file commit/, $c->{c});
3511 # shift off the headers
3512 shift @log while ($log[0] ne '');
3513 shift @log;
3515 # TODO: make $c->{l} not have a trailing newline in the future
3516 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3518 (undef, $c->{r}, undef) = ::extract_metadata(
3519 (grep(/^git-svn-id: /, @log))[-1]);
3521 return defined $c->{r};
3524 sub log_use_color {
3525 return 1 if $color;
3526 my ($dc, $dcvar);
3527 $dcvar = 'color.diff';
3528 $dc = `git-config --get $dcvar`;
3529 if ($dc eq '') {
3530 # nothing at all; fallback to "diff.color"
3531 $dcvar = 'diff.color';
3532 $dc = `git-config --get $dcvar`;
3534 chomp($dc);
3535 if ($dc eq 'auto') {
3536 my $pc;
3537 $pc = `git-config --get color.pager`;
3538 if ($pc eq '') {
3539 # does not have it -- fallback to pager.color
3540 $pc = `git-config --bool --get pager.color`;
3542 else {
3543 $pc = `git-config --bool --get color.pager`;
3544 if ($?) {
3545 $pc = 'false';
3548 chomp($pc);
3549 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3550 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3552 return 0;
3554 return 0 if $dc eq 'never';
3555 return 1 if $dc eq 'always';
3556 chomp($dc = `git-config --bool --get $dcvar`);
3557 return ($dc eq 'true');
3560 sub git_svn_log_cmd {
3561 my ($r_min, $r_max, @args) = @_;
3562 my $head = 'HEAD';
3563 my (@files, @log_opts);
3564 foreach my $x (@args) {
3565 if ($x eq '--' || @files) {
3566 push @files, $x;
3567 } else {
3568 if (::verify_ref("$x^0")) {
3569 $head = $x;
3570 } else {
3571 push @log_opts, $x;
3576 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3577 $gs ||= Git::SVN->_new;
3578 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3579 $gs->refname);
3580 push @cmd, '-r' unless $non_recursive;
3581 push @cmd, qw/--raw --name-status/ if $verbose;
3582 push @cmd, '--color' if log_use_color();
3583 push @cmd, @log_opts;
3584 if (defined $r_max && $r_max == $r_min) {
3585 push @cmd, '--max-count=1';
3586 if (my $c = $gs->rev_db_get($r_max)) {
3587 push @cmd, $c;
3589 } elsif (defined $r_max) {
3590 my ($c_min, $c_max);
3591 $c_max = $gs->rev_db_get($r_max);
3592 $c_min = $gs->rev_db_get($r_min);
3593 if (defined $c_min && defined $c_max) {
3594 if ($r_max > $r_max) {
3595 push @cmd, "$c_min..$c_max";
3596 } else {
3597 push @cmd, "$c_max..$c_min";
3599 } elsif ($r_max > $r_min) {
3600 push @cmd, $c_max;
3601 } else {
3602 push @cmd, $c_min;
3605 return (@cmd, @files);
3608 # adapted from pager.c
3609 sub config_pager {
3610 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3611 if (!defined $pager) {
3612 $pager = 'less';
3613 } elsif (length $pager == 0 || $pager eq 'cat') {
3614 $pager = undef;
3618 sub run_pager {
3619 return unless -t *STDOUT && defined $pager;
3620 pipe my $rfd, my $wfd or return;
3621 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3622 if (!$pid) {
3623 open STDOUT, '>&', $wfd or
3624 ::fatal "Can't redirect to stdout: $!\n";
3625 return;
3627 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3628 $ENV{LESS} ||= 'FRSX';
3629 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3632 sub tz_to_s_offset {
3633 my ($tz) = @_;
3634 $tz =~ s/(\d\d)$//;
3635 return ($1 * 60) + ($tz * 3600);
3638 sub get_author_info {
3639 my ($dest, $author, $t, $tz) = @_;
3640 $author =~ s/(?:^\s*|\s*$)//g;
3641 $dest->{a_raw} = $author;
3642 my $au;
3643 if ($::_authors) {
3644 $au = $rusers{$author} || undef;
3646 if (!$au) {
3647 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3649 $dest->{t} = $t;
3650 $dest->{tz} = $tz;
3651 $dest->{a} = $au;
3652 # Date::Parse isn't in the standard Perl distro :(
3653 if ($tz =~ s/^\+//) {
3654 $t += tz_to_s_offset($tz);
3655 } elsif ($tz =~ s/^\-//) {
3656 $t -= tz_to_s_offset($tz);
3658 $dest->{t_utc} = $t;
3661 sub process_commit {
3662 my ($c, $r_min, $r_max, $defer) = @_;
3663 if (defined $r_min && defined $r_max) {
3664 if ($r_min == $c->{r} && $r_min == $r_max) {
3665 show_commit($c);
3666 return 0;
3668 return 1 if $r_min == $r_max;
3669 if ($r_min < $r_max) {
3670 # we need to reverse the print order
3671 return 0 if (defined $limit && --$limit < 0);
3672 push @$defer, $c;
3673 return 1;
3675 if ($r_min != $r_max) {
3676 return 1 if ($r_min < $c->{r});
3677 return 1 if ($r_max > $c->{r});
3680 return 0 if (defined $limit && --$limit < 0);
3681 show_commit($c);
3682 return 1;
3685 sub show_commit {
3686 my $c = shift;
3687 if ($oneline) {
3688 my $x = "\n";
3689 if (my $l = $c->{l}) {
3690 while ($l->[0] =~ /^\s*$/) { shift @$l }
3691 $x = $l->[0];
3693 $l_fmt ||= 'A' . length($c->{r});
3694 print 'r',pack($l_fmt, $c->{r}),' | ';
3695 print "$c->{c} | " if $show_commit;
3696 print $x;
3697 } else {
3698 show_commit_normal($c);
3702 sub show_commit_changed_paths {
3703 my ($c) = @_;
3704 return unless $c->{changed};
3705 print "Changed paths:\n", @{$c->{changed}};
3708 sub show_commit_normal {
3709 my ($c) = @_;
3710 print '-' x72, "\nr$c->{r} | ";
3711 print "$c->{c} | " if $show_commit;
3712 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3713 localtime($c->{t_utc})), ' | ';
3714 my $nr_line = 0;
3716 if (my $l = $c->{l}) {
3717 while ($l->[$#$l] eq "\n" && $#$l > 0
3718 && $l->[($#$l - 1)] eq "\n") {
3719 pop @$l;
3721 $nr_line = scalar @$l;
3722 if (!$nr_line) {
3723 print "1 line\n\n\n";
3724 } else {
3725 if ($nr_line == 1) {
3726 $nr_line = '1 line';
3727 } else {
3728 $nr_line .= ' lines';
3730 print $nr_line, "\n";
3731 show_commit_changed_paths($c);
3732 print "\n";
3733 print $_ foreach @$l;
3735 } else {
3736 print "1 line\n";
3737 show_commit_changed_paths($c);
3738 print "\n";
3741 foreach my $x (qw/raw stat diff/) {
3742 if ($c->{$x}) {
3743 print "\n";
3744 print $_ foreach @{$c->{$x}}
3749 sub cmd_show_log {
3750 my (@args) = @_;
3751 my ($r_min, $r_max);
3752 my $r_last = -1; # prevent dupes
3753 if (defined $TZ) {
3754 $ENV{TZ} = $TZ;
3755 } else {
3756 delete $ENV{TZ};
3758 if (defined $::_revision) {
3759 if ($::_revision =~ /^(\d+):(\d+)$/) {
3760 ($r_min, $r_max) = ($1, $2);
3761 } elsif ($::_revision =~ /^\d+$/) {
3762 $r_min = $r_max = $::_revision;
3763 } else {
3764 ::fatal "-r$::_revision is not supported, use ",
3765 "standard \'git log\' arguments instead\n";
3769 config_pager();
3770 @args = git_svn_log_cmd($r_min, $r_max, @args);
3771 my $log = command_output_pipe(@args);
3772 run_pager();
3773 my (@k, $c, $d, $stat);
3774 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3775 while (<$log>) {
3776 if (/^${esc_color}commit ($::sha1_short)/o) {
3777 my $cmt = $1;
3778 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3779 $r_last = $c->{r};
3780 process_commit($c, $r_min, $r_max, \@k) or
3781 goto out;
3783 $d = undef;
3784 $c = { c => $cmt };
3785 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3786 get_author_info($c, $1, $2, $3);
3787 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3788 # ignore
3789 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3790 push @{$c->{raw}}, $_;
3791 } elsif (/^${esc_color}[ACRMDT]\t/) {
3792 # we could add $SVN->{svn_path} here, but that requires
3793 # remote access at the moment (repo_path_split)...
3794 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3795 push @{$c->{changed}}, $_;
3796 } elsif (/^${esc_color}diff /o) {
3797 $d = 1;
3798 push @{$c->{diff}}, $_;
3799 } elsif ($d) {
3800 push @{$c->{diff}}, $_;
3801 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3802 $esc_color*[\+\-]*$esc_color$/x) {
3803 $stat = 1;
3804 push @{$c->{stat}}, $_;
3805 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3806 push @{$c->{stat}}, $_;
3807 $stat = undef;
3808 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3809 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3810 } elsif (s/^${esc_color} //o) {
3811 push @{$c->{l}}, $_;
3814 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3815 $r_last = $c->{r};
3816 process_commit($c, $r_min, $r_max, \@k);
3818 if (@k) {
3819 my $swap = $r_max;
3820 $r_max = $r_min;
3821 $r_min = $swap;
3822 process_commit($_, $r_min, $r_max) foreach reverse @k;
3824 out:
3825 close $log;
3826 print '-' x72,"\n" unless $incremental || $oneline;
3829 package Git::SVN::Migration;
3830 # these version numbers do NOT correspond to actual version numbers
3831 # of git nor git-svn. They are just relative.
3833 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3835 # v1 layout: .git/$id/info/url, refs/remotes/$id
3837 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3839 # v3 layout: .git/svn/$id, refs/remotes/$id
3840 # - info/url may remain for backwards compatibility
3841 # - this is what we migrate up to this layout automatically,
3842 # - this will be used by git svn init on single branches
3843 # v3.1 layout (auto migrated):
3844 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3845 # for backwards compatibility
3847 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3848 # - this is only created for newly multi-init-ed
3849 # repositories. Similar in spirit to the
3850 # --use-separate-remotes option in git-clone (now default)
3851 # - we do not automatically migrate to this (following
3852 # the example set by core git)
3853 use strict;
3854 use warnings;
3855 use Carp qw/croak/;
3856 use File::Path qw/mkpath/;
3857 use File::Basename qw/dirname basename/;
3858 use vars qw/$_minimize/;
3860 sub migrate_from_v0 {
3861 my $git_dir = $ENV{GIT_DIR};
3862 return undef unless -d $git_dir;
3863 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3864 my $migrated = 0;
3865 while (<$fh>) {
3866 chomp;
3867 my ($id, $orig_ref) = ($_, $_);
3868 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3869 next unless -f "$git_dir/$id/info/url";
3870 my $new_ref = "refs/remotes/$id";
3871 if (::verify_ref("$new_ref^0")) {
3872 print STDERR "W: $orig_ref is probably an old ",
3873 "branch used by an ancient version of ",
3874 "git-svn.\n",
3875 "However, $new_ref also exists.\n",
3876 "We will not be able ",
3877 "to use this branch until this ",
3878 "ambiguity is resolved.\n";
3879 next;
3881 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3882 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3883 command_noisy('update-ref', $new_ref, $orig_ref);
3884 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3885 $migrated++;
3887 command_close_pipe($fh, $ctx);
3888 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3889 $migrated;
3892 sub migrate_from_v1 {
3893 my $git_dir = $ENV{GIT_DIR};
3894 my $migrated = 0;
3895 return $migrated unless -d $git_dir;
3896 my $svn_dir = "$git_dir/svn";
3898 # just in case somebody used 'svn' as their $id at some point...
3899 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3901 print STDERR "Migrating from a git-svn v1 layout...\n";
3902 mkpath([$svn_dir]);
3903 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3904 "$svn_dir\n\t(required for this version ",
3905 "($::VERSION) of git-svn) does not. exist\n";
3906 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3907 while (<$fh>) {
3908 my $x = $_;
3909 next unless $x =~ s#^refs/remotes/##;
3910 chomp $x;
3911 next unless -f "$git_dir/$x/info/url";
3912 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3913 next unless $u;
3914 my $dn = dirname("$git_dir/svn/$x");
3915 mkpath([$dn]) unless -d $dn;
3916 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3917 mkpath(["$git_dir/svn/svn"]);
3918 print STDERR " - $git_dir/$x/info => ",
3919 "$git_dir/svn/$x/info\n";
3920 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3921 croak "$!: $x";
3922 # don't worry too much about these, they probably
3923 # don't exist with repos this old (save for index,
3924 # and we can easily regenerate that)
3925 foreach my $f (qw/unhandled.log index .rev_db/) {
3926 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3928 } else {
3929 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3930 rename "$git_dir/$x", "$git_dir/svn/$x" or
3931 croak "$!: $x";
3933 $migrated++;
3935 command_close_pipe($fh, $ctx);
3936 print STDERR "Done migrating from a git-svn v1 layout\n";
3937 $migrated;
3940 sub read_old_urls {
3941 my ($l_map, $pfx, $path) = @_;
3942 my @dir;
3943 foreach (<$path/*>) {
3944 if (-r "$_/info/url") {
3945 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3946 my $ref_id = $pfx . basename $_;
3947 my $url = ::file_to_s("$_/info/url");
3948 $l_map->{$ref_id} = $url;
3949 } elsif (-d $_) {
3950 push @dir, $_;
3953 foreach (@dir) {
3954 my $x = $_;
3955 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3956 read_old_urls($l_map, $x, $_);
3960 sub migrate_from_v2 {
3961 my @cfg = command(qw/config -l/);
3962 return if grep /^svn-remote\..+\.url=/, @cfg;
3963 my %l_map;
3964 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3965 my $migrated = 0;
3967 foreach my $ref_id (sort keys %l_map) {
3968 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3969 if ($@) {
3970 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3972 $migrated++;
3974 $migrated;
3977 sub minimize_connections {
3978 my $r = Git::SVN::read_all_remotes();
3979 my $new_urls = {};
3980 my $root_repos = {};
3981 foreach my $repo_id (keys %$r) {
3982 my $url = $r->{$repo_id}->{url} or next;
3983 my $fetch = $r->{$repo_id}->{fetch} or next;
3984 my $ra = Git::SVN::Ra->new($url);
3986 # skip existing cases where we already connect to the root
3987 if (($ra->{url} eq $ra->{repos_root}) ||
3988 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3989 $repo_id)) {
3990 $root_repos->{$ra->{url}} = $repo_id;
3991 next;
3994 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3995 my $root_path = $ra->{url};
3996 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3997 foreach my $path (keys %$fetch) {
3998 my $ref_id = $fetch->{$path};
3999 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4001 # make sure we can read when connecting to
4002 # a higher level of a repository
4003 my ($last_rev, undef) = $gs->last_rev_commit;
4004 if (!defined $last_rev) {
4005 $last_rev = eval {
4006 $root_ra->get_latest_revnum;
4008 next if $@;
4010 my $new = $root_path;
4011 $new .= length $path ? "/$path" : '';
4012 eval {
4013 $root_ra->get_log([$new], $last_rev, $last_rev,
4014 0, 0, 1, sub { });
4016 next if $@;
4017 $new_urls->{$ra->{repos_root}}->{$new} =
4018 { ref_id => $ref_id,
4019 old_repo_id => $repo_id,
4020 old_path => $path };
4024 my @emptied;
4025 foreach my $url (keys %$new_urls) {
4026 # see if we can re-use an existing [svn-remote "repo_id"]
4027 # instead of creating a(n ugly) new section:
4028 my $repo_id = $root_repos->{$url} ||
4029 Git::SVN::sanitize_remote_name($url);
4031 my $fetch = $new_urls->{$url};
4032 foreach my $path (keys %$fetch) {
4033 my $x = $fetch->{$path};
4034 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4035 my $pfx = "svn-remote.$x->{old_repo_id}";
4037 my $old_fetch = quotemeta("$x->{old_path}:".
4038 "refs/remotes/$x->{ref_id}");
4039 command_noisy(qw/config --unset/,
4040 "$pfx.fetch", '^'. $old_fetch . '$');
4041 delete $r->{$x->{old_repo_id}}->
4042 {fetch}->{$x->{old_path}};
4043 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4044 command_noisy(qw/config --unset/,
4045 "$pfx.url");
4046 push @emptied, $x->{old_repo_id}
4050 if (@emptied) {
4051 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4052 "$ENV{GIT_DIR}/config";
4053 print STDERR <<EOF;
4054 The following [svn-remote] sections in your config file ($file) are empty
4055 and can be safely removed:
4057 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4061 sub migration_check {
4062 migrate_from_v0();
4063 migrate_from_v1();
4064 migrate_from_v2();
4065 minimize_connections() if $_minimize;
4068 package Git::IndexInfo;
4069 use strict;
4070 use warnings;
4071 use Git qw/command_input_pipe command_close_pipe/;
4073 sub new {
4074 my ($class) = @_;
4075 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4076 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4079 sub remove {
4080 my ($self, $path) = @_;
4081 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4082 return ++$self->{nr};
4084 undef;
4087 sub update {
4088 my ($self, $mode, $hash, $path) = @_;
4089 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4090 return ++$self->{nr};
4092 undef;
4095 sub DESTROY {
4096 my ($self) = @_;
4097 command_close_pipe($self->{gui}, $self->{ctx});
4100 package Git::SVN::GlobSpec;
4101 use strict;
4102 use warnings;
4104 sub new {
4105 my ($class, $glob) = @_;
4106 my $re = $glob;
4107 $re =~ s!/+$!!g; # no need for trailing slashes
4108 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4109 my ($left, $right) = ($1, $2);
4110 if ($nr > 1) {
4111 die "Only one '*' wildcard expansion ",
4112 "is supported (got $nr): '$glob'\n";
4113 } elsif ($nr == 0) {
4114 die "One '*' is needed for glob: '$glob'\n";
4116 $re = quotemeta($left) . $re . quotemeta($right);
4117 if (length $left && !($left =~ s!/+$!!g)) {
4118 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4120 if (length $right && !($right =~ s!^/+!!g)) {
4121 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4123 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4124 bless { left => $left, right => $right, left_regex => $left_re,
4125 regex => qr/$re/, glob => $glob }, $class;
4128 sub full_path {
4129 my ($self, $path) = @_;
4130 return (length $self->{left} ? "$self->{left}/" : '') .
4131 $path . (length $self->{right} ? "/$self->{right}" : '');
4134 __END__
4136 Data structures:
4139 $remotes = { # returned by read_all_remotes()
4140 'svn' => {
4141 # svn-remote.svn.url=https://svn.musicpd.org
4142 url => 'https://svn.musicpd.org',
4143 # svn-remote.svn.fetch=mpd/trunk:trunk
4144 fetch => {
4145 'mpd/trunk' => 'trunk',
4147 # svn-remote.svn.tags=mpd/tags/*:tags/*
4148 tags => {
4149 path => {
4150 left => 'mpd/tags',
4151 right => '',
4152 regex => qr!mpd/tags/([^/]+)$!,
4153 glob => 'tags/*',
4155 ref => {
4156 left => 'tags',
4157 right => '',
4158 regex => qr!tags/([^/]+)$!,
4159 glob => 'tags/*',
4165 $log_entry hashref as returned by libsvn_log_entry()
4167 log => 'whitespace-formatted log entry
4168 ', # trailing newline is preserved
4169 revision => '8', # integer
4170 date => '2004-02-24T17:01:44.108345Z', # commit date
4171 author => 'committer name'
4175 # this is generated by generate_diff();
4176 @mods = array of diff-index line hashes, each element represents one line
4177 of diff-index output
4179 diff-index line ($m hash)
4181 mode_a => first column of diff-index output, no leading ':',
4182 mode_b => second column of diff-index output,
4183 sha1_b => sha1sum of the final blob,
4184 chg => change type [MCRADT],
4185 file_a => original file name of a file (iff chg is 'C' or 'R')
4186 file_b => new/current file name of a file (any chg)
4190 # retval of read_url_paths{,_all}();
4191 $l_map = {
4192 # repository root url
4193 'https://svn.musicpd.org' => {
4194 # repository path # GIT_SVN_ID
4195 'mpd/trunk' => 'trunk',
4196 'mpd/tags/0.11.5' => 'tags/0.11.5',
4200 Notes:
4201 I don't trust the each() function on unless I created %hash myself
4202 because the internal iterator may not have started at base.