Merge branch 'db/clone-in-c'
[git.git] / git-svn.perl
blob37976f25057ac5d3c91a13ab8564a4cb40f59f79
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 $_repository
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
74 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
75 'authors-file|A=s' => \$_authors,
76 'repack:i' => \$Git::SVN::_repack,
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
81 'no-checkout' => \$_no_checkout,
82 'quiet|q' => \$_q,
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
85 'use-log-author' => \$Git::SVN::_use_log_author,
86 'add-author-from' => \$Git::SVN::_add_author_from,
87 %remote_opts );
89 my ($_trunk, $_tags, $_branches, $_stdlayout);
90 my %icv;
91 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
92 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
93 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
94 'stdlayout|s' => \$_stdlayout,
95 'minimize-url|m' => \$Git::SVN::_minimize_url,
96 'no-metadata' => sub { $icv{noMetadata} = 1 },
97 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
98 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
99 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
100 %remote_opts );
101 my %cmt_opts = ( 'edit|e' => \$_edit,
102 'rmdir' => \$SVN::Git::Editor::_rmdir,
103 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
104 'l=i' => \$SVN::Git::Editor::_rename_limit,
105 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
108 my %cmd = (
109 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
110 { 'revision|r=s' => \$_revision,
111 'fetch-all|all' => \$_fetch_all,
112 %fc_opts } ],
113 clone => [ \&cmd_clone, "Initialize and fetch revisions",
114 { 'revision|r=s' => \$_revision,
115 %fc_opts, %init_opts } ],
116 init => [ \&cmd_init, "Initialize a repo for tracking" .
117 " (requires URL argument)",
118 \%init_opts ],
119 'multi-init' => [ \&cmd_multi_init,
120 "Deprecated alias for ".
121 "'$0 init -T<trunk> -b<branches> -t<tags>'",
122 \%init_opts ],
123 dcommit => [ \&cmd_dcommit,
124 'Commit several diffs to merge with upstream',
125 { 'merge|m|M' => \$_merge,
126 'strategy|s=s' => \$_strategy,
127 'verbose|v' => \$_verbose,
128 'dry-run|n' => \$_dry_run,
129 'fetch-all|all' => \$_fetch_all,
130 'no-rebase' => \$_no_rebase,
131 %cmt_opts, %fc_opts } ],
132 'set-tree' => [ \&cmd_set_tree,
133 "Set an SVN repository to a git tree-ish",
134 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
135 'create-ignore' => [ \&cmd_create_ignore,
136 'Create a .gitignore per svn:ignore',
137 { 'revision|r=i' => \$_revision
138 } ],
139 'propget' => [ \&cmd_propget,
140 'Print the value of a property on a file or directory',
141 { 'revision|r=i' => \$_revision } ],
142 'proplist' => [ \&cmd_proplist,
143 'List all properties of a file or directory',
144 { 'revision|r=i' => \$_revision } ],
145 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
146 { 'revision|r=i' => \$_revision
147 } ],
148 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
149 { 'revision|r=i' => \$_revision
150 } ],
151 'multi-fetch' => [ \&cmd_multi_fetch,
152 "Deprecated alias for $0 fetch --all",
153 { 'revision|r=s' => \$_revision, %fc_opts } ],
154 'migrate' => [ sub { },
155 # no-op, we automatically run this anyways,
156 'Migrate configuration/metadata/layout from
157 previous versions of git-svn',
158 { 'minimize' => \$Git::SVN::Migration::_minimize,
159 %remote_opts } ],
160 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
161 { 'limit=i' => \$Git::SVN::Log::limit,
162 'revision|r=s' => \$_revision,
163 'verbose|v' => \$Git::SVN::Log::verbose,
164 'incremental' => \$Git::SVN::Log::incremental,
165 'oneline' => \$Git::SVN::Log::oneline,
166 'show-commit' => \$Git::SVN::Log::show_commit,
167 'non-recursive' => \$Git::SVN::Log::non_recursive,
168 'authors-file|A=s' => \$_authors,
169 'color' => \$Git::SVN::Log::color,
170 'pager=s' => \$Git::SVN::Log::pager
171 } ],
172 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
173 {} ],
174 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
175 { 'merge|m|M' => \$_merge,
176 'verbose|v' => \$_verbose,
177 'strategy|s=s' => \$_strategy,
178 'local|l' => \$_local,
179 'fetch-all|all' => \$_fetch_all,
180 %fc_opts } ],
181 'commit-diff' => [ \&cmd_commit_diff,
182 'Commit a diff between two trees',
183 { 'message|m=s' => \$_message,
184 'file|F=s' => \$_file,
185 'revision|r=s' => \$_revision,
186 %cmt_opts } ],
187 'info' => [ \&cmd_info,
188 "Show info about the latest SVN revision
189 on the current branch",
190 { 'url' => \$_url, } ],
191 'blame' => [ \&Git::SVN::Log::cmd_blame,
192 "Show what revision and author last modified each line of a file",
193 { 'git-format' => \$_git_format } ],
196 my $cmd;
197 for (my $i = 0; $i < @ARGV; $i++) {
198 if (defined $cmd{$ARGV[$i]}) {
199 $cmd = $ARGV[$i];
200 splice @ARGV, $i, 1;
201 last;
205 # make sure we're always running at the top-level working directory
206 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
207 unless (-d $ENV{GIT_DIR}) {
208 if ($git_dir_user_set) {
209 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
210 "but it is not a directory\n";
212 my $git_dir = delete $ENV{GIT_DIR};
213 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
214 unless (length $cdup) {
215 die "Already at toplevel, but $git_dir ",
216 "not found '$cdup'\n";
218 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
219 unless (-d $git_dir) {
220 die "$git_dir still not found after going to ",
221 "'$cdup'\n";
223 $ENV{GIT_DIR} = $git_dir;
225 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
228 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
230 read_repo_config(\%opts);
231 Getopt::Long::Configure('pass_through') if ($cmd && ($cmd eq 'log' || $cmd eq 'blame'));
232 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
233 'minimize-connections' => \$Git::SVN::Migration::_minimize,
234 'id|i=s' => \$Git::SVN::default_ref_id,
235 'svn-remote|remote|R=s' => sub {
236 $Git::SVN::no_reuse_existing = 1;
237 $Git::SVN::default_repo_id = $_[1] });
238 exit 1 if (!$rv && $cmd && $cmd ne 'log');
240 usage(0) if $_help;
241 version() if $_version;
242 usage(1) unless defined $cmd;
243 load_authors() if $_authors;
245 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
246 Git::SVN::Migration::migration_check();
248 Git::SVN::init_vars();
249 eval {
250 Git::SVN::verify_remotes_sanity();
251 $cmd{$cmd}->[0]->(@ARGV);
253 fatal $@ if $@;
254 post_fetch_checkout();
255 exit 0;
257 ####################### primary functions ######################
258 sub usage {
259 my $exit = shift || 0;
260 my $fd = $exit ? \*STDERR : \*STDOUT;
261 print $fd <<"";
262 git-svn - bidirectional operations between a single Subversion tree and git
263 Usage: $0 <command> [options] [arguments]\n
265 print $fd "Available commands:\n" unless $cmd;
267 foreach (sort keys %cmd) {
268 next if $cmd && $cmd ne $_;
269 next if /^multi-/; # don't show deprecated commands
270 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
271 foreach (sort keys %{$cmd{$_}->[2]}) {
272 # mixed-case options are for .git/config only
273 next if /[A-Z]/ && /^[a-z]+$/i;
274 # prints out arguments as they should be passed:
275 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
276 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
277 "--$_" : "-$_" }
278 split /\|/,$_)," $x\n";
281 print $fd <<"";
282 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
283 arbitrary identifier if you're tracking multiple SVN branches/repositories in
284 one git repository and want to keep them separate. See git-svn(1) for more
285 information.
287 exit $exit;
290 sub version {
291 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
292 exit 0;
295 sub do_git_init_db {
296 unless (-d $ENV{GIT_DIR}) {
297 my @init_db = ('init');
298 push @init_db, "--template=$_template" if defined $_template;
299 if (defined $_shared) {
300 if ($_shared =~ /[a-z]/) {
301 push @init_db, "--shared=$_shared";
302 } else {
303 push @init_db, "--shared";
306 command_noisy(@init_db);
307 $_repository = Git->repository(Repository => ".git");
309 my $set;
310 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
311 foreach my $i (keys %icv) {
312 die "'$set' and '$i' cannot both be set\n" if $set;
313 next unless defined $icv{$i};
314 command_noisy('config', "$pfx.$i", $icv{$i});
315 $set = $i;
319 sub init_subdir {
320 my $repo_path = shift or return;
321 mkpath([$repo_path]) unless -d $repo_path;
322 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
323 $ENV{GIT_DIR} = '.git';
324 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
327 sub cmd_clone {
328 my ($url, $path) = @_;
329 if (!defined $path &&
330 (defined $_trunk || defined $_branches || defined $_tags ||
331 defined $_stdlayout) &&
332 $url !~ m#^[a-z\+]+://#) {
333 $path = $url;
335 $path = basename($url) if !defined $path || !length $path;
336 cmd_init($url, $path);
337 Git::SVN::fetch_all($Git::SVN::default_repo_id);
340 sub cmd_init {
341 if (defined $_stdlayout) {
342 $_trunk = 'trunk' if (!defined $_trunk);
343 $_tags = 'tags' if (!defined $_tags);
344 $_branches = 'branches' if (!defined $_branches);
346 if (defined $_trunk || defined $_branches || defined $_tags) {
347 return cmd_multi_init(@_);
349 my $url = shift or die "SVN repository location required ",
350 "as a command-line argument\n";
351 init_subdir(@_);
352 do_git_init_db();
354 Git::SVN->init($url);
357 sub cmd_fetch {
358 if (grep /^\d+=./, @_) {
359 die "'<rev>=<commit>' fetch arguments are ",
360 "no longer supported.\n";
362 my ($remote) = @_;
363 if (@_ > 1) {
364 die "Usage: $0 fetch [--all] [svn-remote]\n";
366 $remote ||= $Git::SVN::default_repo_id;
367 if ($_fetch_all) {
368 cmd_multi_fetch();
369 } else {
370 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
374 sub cmd_set_tree {
375 my (@commits) = @_;
376 if ($_stdin || !@commits) {
377 print "Reading from stdin...\n";
378 @commits = ();
379 while (<STDIN>) {
380 if (/\b($sha1_short)\b/o) {
381 unshift @commits, $1;
385 my @revs;
386 foreach my $c (@commits) {
387 my @tmp = command('rev-parse',$c);
388 if (scalar @tmp == 1) {
389 push @revs, $tmp[0];
390 } elsif (scalar @tmp > 1) {
391 push @revs, reverse(command('rev-list',@tmp));
392 } else {
393 fatal "Failed to rev-parse $c";
396 my $gs = Git::SVN->new;
397 my ($r_last, $cmt_last) = $gs->last_rev_commit;
398 $gs->fetch;
399 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
400 fatal "There are new revisions that were fetched ",
401 "and need to be merged (or acknowledged) ",
402 "before committing.\nlast rev: $r_last\n",
403 " current: $gs->{last_rev}";
405 $gs->set_tree($_) foreach @revs;
406 print "Done committing ",scalar @revs," revisions to SVN\n";
407 unlink $gs->{index};
410 sub cmd_dcommit {
411 my $head = shift;
412 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
413 'Cannot dcommit with a dirty index. Commit your changes first, '
414 . "or stash them with `git stash'.\n";
415 $head ||= 'HEAD';
416 my @refs;
417 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
418 if ($url) {
419 print "Committing to $url ...\n";
421 unless ($gs) {
422 die "Unable to determine upstream SVN information from ",
423 "$head history.\nPerhaps the repository is empty.";
425 my $last_rev;
426 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
427 if ($_no_rebase && scalar(@$linear_refs) > 1) {
428 warn "Attempting to commit more than one change while ",
429 "--no-rebase is enabled.\n",
430 "If these changes depend on each other, re-running ",
431 "without --no-rebase may be required."
433 while (1) {
434 my $d = shift @$linear_refs or last;
435 unless (defined $last_rev) {
436 (undef, $last_rev, undef) = cmt_metadata("$d~1");
437 unless (defined $last_rev) {
438 fatal "Unable to extract revision information ",
439 "from commit $d~1";
442 if ($_dry_run) {
443 print "diff-tree $d~1 $d\n";
444 } else {
445 my $cmt_rev;
446 my %ed_opts = ( r => $last_rev,
447 log => get_commit_entry($d)->{log},
448 ra => Git::SVN::Ra->new($gs->full_url),
449 config => SVN::Core::config_get_config(
450 $Git::SVN::Ra::config_dir
452 tree_a => "$d~1",
453 tree_b => $d,
454 editor_cb => sub {
455 print "Committed r$_[0]\n";
456 $cmt_rev = $_[0];
458 svn_path => '');
459 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
460 print "No changes\n$d~1 == $d\n";
461 } elsif ($parents->{$d} && @{$parents->{$d}}) {
462 $gs->{inject_parents_dcommit}->{$cmt_rev} =
463 $parents->{$d};
465 $_fetch_all ? $gs->fetch_all : $gs->fetch;
466 $last_rev = $cmt_rev;
467 next if $_no_rebase;
469 # we always want to rebase against the current HEAD,
470 # not any head that was passed to us
471 my @diff = command('diff-tree', $d,
472 $gs->refname, '--');
473 my @finish;
474 if (@diff) {
475 @finish = rebase_cmd();
476 print STDERR "W: $d and ", $gs->refname,
477 " differ, using @finish:\n",
478 join("\n", @diff), "\n";
479 } else {
480 print "No changes between current HEAD and ",
481 $gs->refname,
482 "\nResetting to the latest ",
483 $gs->refname, "\n";
484 @finish = qw/reset --mixed/;
486 command_noisy(@finish, $gs->refname);
487 if (@diff) {
488 @refs = ();
489 my ($url_, $rev_, $uuid_, $gs_) =
490 working_head_info($head, \@refs);
491 my ($linear_refs_, $parents_) =
492 linearize_history($gs_, \@refs);
493 if (scalar(@$linear_refs) !=
494 scalar(@$linear_refs_)) {
495 fatal "# of revisions changed ",
496 "\nbefore:\n",
497 join("\n", @$linear_refs),
498 "\n\nafter:\n",
499 join("\n", @$linear_refs_), "\n",
500 'If you are attempting to commit ',
501 "merges, try running:\n\t",
502 'git rebase --interactive',
503 '--preserve-merges ',
504 $gs->refname,
505 "\nBefore dcommitting";
507 if ($url_ ne $url) {
508 fatal "URL mismatch after rebase: ",
509 "$url_ != $url";
511 if ($uuid_ ne $uuid) {
512 fatal "uuid mismatch after rebase: ",
513 "$uuid_ != $uuid";
515 # remap parents
516 my (%p, @l, $i);
517 for ($i = 0; $i < scalar @$linear_refs; $i++) {
518 my $new = $linear_refs_->[$i] or next;
519 $p{$new} =
520 $parents->{$linear_refs->[$i]};
521 push @l, $new;
523 $parents = \%p;
524 $linear_refs = \@l;
528 unlink $gs->{index};
531 sub cmd_find_rev {
532 my $revision_or_hash = shift or die "SVN or git revision required ",
533 "as a command-line argument\n";
534 my $result;
535 if ($revision_or_hash =~ /^r\d+$/) {
536 my $head = shift;
537 $head ||= 'HEAD';
538 my @refs;
539 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
540 unless ($gs) {
541 die "Unable to determine upstream SVN information from ",
542 "$head history\n";
544 my $desired_revision = substr($revision_or_hash, 1);
545 $result = $gs->rev_map_get($desired_revision);
546 } else {
547 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
548 $result = $rev;
550 print "$result\n" if $result;
553 sub cmd_rebase {
554 command_noisy(qw/update-index --refresh/);
555 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
556 unless ($gs) {
557 die "Unable to determine upstream SVN information from ",
558 "working tree history\n";
560 if (command(qw/diff-index HEAD --/)) {
561 print STDERR "Cannot rebase with uncommited changes:\n";
562 command_noisy('status');
563 exit 1;
565 unless ($_local) {
566 # rebase will checkout for us, so no need to do it explicitly
567 $_no_checkout = 'true';
568 $_fetch_all ? $gs->fetch_all : $gs->fetch;
570 command_noisy(rebase_cmd(), $gs->refname);
573 sub cmd_show_ignore {
574 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
575 $gs ||= Git::SVN->new;
576 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
577 $gs->prop_walk($gs->{path}, $r, sub {
578 my ($gs, $path, $props) = @_;
579 print STDOUT "\n# $path\n";
580 my $s = $props->{'svn:ignore'} or return;
581 $s =~ s/[\r\n]+/\n/g;
582 chomp $s;
583 $s =~ s#^#$path#gm;
584 print STDOUT "$s\n";
588 sub cmd_show_externals {
589 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
590 $gs ||= Git::SVN->new;
591 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
592 $gs->prop_walk($gs->{path}, $r, sub {
593 my ($gs, $path, $props) = @_;
594 print STDOUT "\n# $path\n";
595 my $s = $props->{'svn:externals'} or return;
596 $s =~ s/[\r\n]+/\n/g;
597 chomp $s;
598 $s =~ s#^#$path#gm;
599 print STDOUT "$s\n";
603 sub cmd_create_ignore {
604 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
605 $gs ||= Git::SVN->new;
606 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
607 $gs->prop_walk($gs->{path}, $r, sub {
608 my ($gs, $path, $props) = @_;
609 # $path is of the form /path/to/dir/
610 my $ignore = '.' . $path . '.gitignore';
611 my $s = $props->{'svn:ignore'} or return;
612 open(GITIGNORE, '>', $ignore)
613 or fatal("Failed to open `$ignore' for writing: $!");
614 $s =~ s/[\r\n]+/\n/g;
615 chomp $s;
616 # Prefix all patterns so that the ignore doesn't apply
617 # to sub-directories.
618 $s =~ s#^#/#gm;
619 print GITIGNORE "$s\n";
620 close(GITIGNORE)
621 or fatal("Failed to close `$ignore': $!");
622 command_noisy('add', '-f', $ignore);
626 sub canonicalize_path {
627 my ($path) = @_;
628 my $dot_slash_added = 0;
629 if (substr($path, 0, 1) ne "/") {
630 $path = "./" . $path;
631 $dot_slash_added = 1;
633 # File::Spec->canonpath doesn't collapse x/../y into y (for a
634 # good reason), so let's do this manually.
635 $path =~ s#/+#/#g;
636 $path =~ s#/\.(?:/|$)#/#g;
637 $path =~ s#/[^/]+/\.\.##g;
638 $path =~ s#/$##g;
639 $path =~ s#^\./## if $dot_slash_added;
640 return $path;
643 # get_svnprops(PATH)
644 # ------------------
645 # Helper for cmd_propget and cmd_proplist below.
646 sub get_svnprops {
647 my $path = shift;
648 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
649 $gs ||= Git::SVN->new;
651 # prefix THE PATH by the sub-directory from which the user
652 # invoked us.
653 $path = $cmd_dir_prefix . $path;
654 fatal("No such file or directory: $path") unless -e $path;
655 my $is_dir = -d $path ? 1 : 0;
656 $path = $gs->{path} . '/' . $path;
658 # canonicalize the path (otherwise libsvn will abort or fail to
659 # find the file)
660 $path = canonicalize_path($path);
662 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
663 my $props;
664 if ($is_dir) {
665 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
667 else {
668 (undef, $props) = $gs->ra->get_file($path, $r, undef);
670 return $props;
673 # cmd_propget (PROP, PATH)
674 # ------------------------
675 # Print the SVN property PROP for PATH.
676 sub cmd_propget {
677 my ($prop, $path) = @_;
678 $path = '.' if not defined $path;
679 usage(1) if not defined $prop;
680 my $props = get_svnprops($path);
681 if (not defined $props->{$prop}) {
682 fatal("`$path' does not have a `$prop' SVN property.");
684 print $props->{$prop} . "\n";
687 # cmd_proplist (PATH)
688 # -------------------
689 # Print the list of SVN properties for PATH.
690 sub cmd_proplist {
691 my $path = shift;
692 $path = '.' if not defined $path;
693 my $props = get_svnprops($path);
694 print "Properties on '$path':\n";
695 foreach (sort keys %{$props}) {
696 print " $_\n";
700 sub cmd_multi_init {
701 my $url = shift;
702 unless (defined $_trunk || defined $_branches || defined $_tags) {
703 usage(1);
706 # there are currently some bugs that prevent multi-init/multi-fetch
707 # setups from working well without this.
708 $Git::SVN::_minimize_url = 1;
710 $_prefix = '' unless defined $_prefix;
711 if (defined $url) {
712 $url =~ s#/+$##;
713 init_subdir(@_);
715 do_git_init_db();
716 if (defined $_trunk) {
717 my $trunk_ref = $_prefix . 'trunk';
718 # try both old-style and new-style lookups:
719 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
720 unless ($gs_trunk) {
721 my ($trunk_url, $trunk_path) =
722 complete_svn_url($url, $_trunk);
723 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
724 undef, $trunk_ref);
727 return unless defined $_branches || defined $_tags;
728 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
729 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
730 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
733 sub cmd_multi_fetch {
734 my $remotes = Git::SVN::read_all_remotes();
735 foreach my $repo_id (sort keys %$remotes) {
736 if ($remotes->{$repo_id}->{url}) {
737 Git::SVN::fetch_all($repo_id, $remotes);
742 # this command is special because it requires no metadata
743 sub cmd_commit_diff {
744 my ($ta, $tb, $url) = @_;
745 my $usage = "Usage: $0 commit-diff -r<revision> ".
746 "<tree-ish> <tree-ish> [<URL>]";
747 fatal($usage) if (!defined $ta || !defined $tb);
748 my $svn_path;
749 if (!defined $url) {
750 my $gs = eval { Git::SVN->new };
751 if (!$gs) {
752 fatal("Needed URL or usable git-svn --id in ",
753 "the command-line\n", $usage);
755 $url = $gs->{url};
756 $svn_path = $gs->{path};
758 unless (defined $_revision) {
759 fatal("-r|--revision is a required argument\n", $usage);
761 if (defined $_message && defined $_file) {
762 fatal("Both --message/-m and --file/-F specified ",
763 "for the commit message.\n",
764 "I have no idea what you mean");
766 if (defined $_file) {
767 $_message = file_to_s($_file);
768 } else {
769 $_message ||= get_commit_entry($tb)->{log};
771 my $ra ||= Git::SVN::Ra->new($url);
772 $svn_path ||= $ra->{svn_path};
773 my $r = $_revision;
774 if ($r eq 'HEAD') {
775 $r = $ra->get_latest_revnum;
776 } elsif ($r !~ /^\d+$/) {
777 die "revision argument: $r not understood by git-svn\n";
779 my %ed_opts = ( r => $r,
780 log => $_message,
781 ra => $ra,
782 tree_a => $ta,
783 tree_b => $tb,
784 editor_cb => sub { print "Committed r$_[0]\n" },
785 svn_path => $svn_path );
786 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
787 print "No changes\n$ta == $tb\n";
791 sub cmd_info {
792 my $path = canonicalize_path(shift or ".");
793 unless (scalar(@_) == 0) {
794 die "Too many arguments specified\n";
797 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
799 if (!$file_type && !$diff_status) {
800 print STDERR "$path: (Not a versioned resource)\n\n";
801 return;
804 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
805 unless ($gs) {
806 die "Unable to determine upstream SVN information from ",
807 "working tree history\n";
809 my $full_url = $url . ($path eq "." ? "" : "/$path");
811 if ($_url) {
812 print $full_url, "\n";
813 return;
816 my $result = "Path: $path\n";
817 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
818 $result .= "URL: " . $full_url . "\n";
820 eval {
821 my $repos_root = $gs->repos_root;
822 Git::SVN::remove_username($repos_root);
823 $result .= "Repository Root: $repos_root\n";
825 if ($@) {
826 $result .= "Repository Root: (offline)\n";
828 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
829 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
831 $result .= "Node Kind: " .
832 ($file_type eq "dir" ? "directory" : "file") . "\n";
834 my $schedule = $diff_status eq "A"
835 ? "add"
836 : ($diff_status eq "D" ? "delete" : "normal");
837 $result .= "Schedule: $schedule\n";
839 if ($diff_status eq "A") {
840 print $result, "\n";
841 return;
844 my ($lc_author, $lc_rev, $lc_date_utc);
845 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
846 my $log = command_output_pipe(@args);
847 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
848 while (<$log>) {
849 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
850 $lc_author = $1;
851 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
852 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
853 (undef, $lc_rev, undef) = ::extract_metadata($1);
856 close $log;
858 Git::SVN::Log::set_local_timezone();
860 $result .= "Last Changed Author: $lc_author\n";
861 $result .= "Last Changed Rev: $lc_rev\n";
862 $result .= "Last Changed Date: " .
863 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
865 if ($file_type ne "dir") {
866 my $text_last_updated_date =
867 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
868 $result .=
869 "Text Last Updated: " .
870 Git::SVN::Log::format_svn_date($text_last_updated_date) .
871 "\n";
872 my $checksum;
873 if ($diff_status eq "D") {
874 my ($fh, $ctx) =
875 command_output_pipe(qw(cat-file blob), "HEAD:$path");
876 if ($file_type eq "link") {
877 my $file_name = <$fh>;
878 $checksum = md5sum("link $file_name");
879 } else {
880 $checksum = md5sum($fh);
882 command_close_pipe($fh, $ctx);
883 } elsif ($file_type eq "link") {
884 my $file_name =
885 command(qw(cat-file blob), "HEAD:$path");
886 $checksum =
887 md5sum("link " . $file_name);
888 } else {
889 open FILE, "<", $path or die $!;
890 $checksum = md5sum(\*FILE);
891 close FILE or die $!;
893 $result .= "Checksum: " . $checksum . "\n";
896 print $result, "\n";
899 ########################### utility functions #########################
901 sub rebase_cmd {
902 my @cmd = qw/rebase/;
903 push @cmd, '-v' if $_verbose;
904 push @cmd, qw/--merge/ if $_merge;
905 push @cmd, "--strategy=$_strategy" if $_strategy;
906 @cmd;
909 sub post_fetch_checkout {
910 return if $_no_checkout;
911 my $gs = $Git::SVN::_head or return;
912 return if verify_ref('refs/heads/master^0');
914 my $valid_head = verify_ref('HEAD^0');
915 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
916 return if ($valid_head || !verify_ref('HEAD^0'));
918 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
919 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
920 return if -f $index;
922 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
923 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
924 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
925 print STDERR "Checked out HEAD:\n ",
926 $gs->full_url, " r", $gs->last_rev, "\n";
929 sub complete_svn_url {
930 my ($url, $path) = @_;
931 $path =~ s#/+$##;
932 if ($path !~ m#^[a-z\+]+://#) {
933 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
934 fatal("E: '$path' is not a complete URL ",
935 "and a separate URL is not specified");
937 return ($url, $path);
939 return ($path, '');
942 sub complete_url_ls_init {
943 my ($ra, $repo_path, $switch, $pfx) = @_;
944 unless ($repo_path) {
945 print STDERR "W: $switch not specified\n";
946 return;
948 $repo_path =~ s#/+$##;
949 if ($repo_path =~ m#^[a-z\+]+://#) {
950 $ra = Git::SVN::Ra->new($repo_path);
951 $repo_path = '';
952 } else {
953 $repo_path =~ s#^/+##;
954 unless ($ra) {
955 fatal("E: '$repo_path' is not a complete URL ",
956 "and a separate URL is not specified");
959 my $url = $ra->{url};
960 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
961 my $k = "svn-remote.$gs->{repo_id}.url";
962 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
963 if ($orig_url && ($orig_url ne $gs->{url})) {
964 die "$k already set: $orig_url\n",
965 "wanted to set to: $gs->{url}\n";
967 command_oneline('config', $k, $gs->{url}) unless $orig_url;
968 my $remote_path = "$ra->{svn_path}/$repo_path";
969 $remote_path =~ s#/+#/#g;
970 $remote_path =~ s#^/##g;
971 $remote_path .= "/*" if $remote_path !~ /\*/;
972 my ($n) = ($switch =~ /^--(\w+)/);
973 if (length $pfx && $pfx !~ m#/$#) {
974 die "--prefix='$pfx' must have a trailing slash '/'\n";
976 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
977 "$remote_path:refs/remotes/$pfx*");
980 sub verify_ref {
981 my ($ref) = @_;
982 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
983 { STDERR => 0 }); };
986 sub get_tree_from_treeish {
987 my ($treeish) = @_;
988 # $treeish can be a symbolic ref, too:
989 my $type = command_oneline(qw/cat-file -t/, $treeish);
990 my $expected;
991 while ($type eq 'tag') {
992 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
994 if ($type eq 'commit') {
995 $expected = (grep /^tree /, command(qw/cat-file commit/,
996 $treeish))[0];
997 ($expected) = ($expected =~ /^tree ($sha1)$/o);
998 die "Unable to get tree from $treeish\n" unless $expected;
999 } elsif ($type eq 'tree') {
1000 $expected = $treeish;
1001 } else {
1002 die "$treeish is a $type, expected tree, tag or commit\n";
1004 return $expected;
1007 sub get_commit_entry {
1008 my ($treeish) = shift;
1009 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1010 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1011 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1012 open my $log_fh, '>', $commit_editmsg or croak $!;
1014 my $type = command_oneline(qw/cat-file -t/, $treeish);
1015 if ($type eq 'commit' || $type eq 'tag') {
1016 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1017 $type, $treeish);
1018 my $in_msg = 0;
1019 my $author;
1020 my $saw_from = 0;
1021 while (<$msg_fh>) {
1022 if (!$in_msg) {
1023 $in_msg = 1 if (/^\s*$/);
1024 $author = $1 if (/^author (.*>)/);
1025 } elsif (/^git-svn-id: /) {
1026 # skip this for now, we regenerate the
1027 # correct one on re-fetch anyways
1028 # TODO: set *:merge properties or like...
1029 } else {
1030 if (/^From:/ || /^Signed-off-by:/) {
1031 $saw_from = 1;
1033 print $log_fh $_ or croak $!;
1036 if ($Git::SVN::_add_author_from && defined($author)
1037 && !$saw_from) {
1038 print $log_fh "\nFrom: $author\n"
1039 or croak $!;
1041 command_close_pipe($msg_fh, $ctx);
1043 close $log_fh or croak $!;
1045 if ($_edit || ($type eq 'tree')) {
1046 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1047 # TODO: strip out spaces, comments, like git-commit.sh
1048 system($editor, $commit_editmsg);
1050 rename $commit_editmsg, $commit_msg or croak $!;
1051 open $log_fh, '<', $commit_msg or croak $!;
1052 { local $/; chomp($log_entry{log} = <$log_fh>); }
1053 close $log_fh or croak $!;
1054 unlink $commit_msg;
1055 \%log_entry;
1058 sub s_to_file {
1059 my ($str, $file, $mode) = @_;
1060 open my $fd,'>',$file or croak $!;
1061 print $fd $str,"\n" or croak $!;
1062 close $fd or croak $!;
1063 chmod ($mode &~ umask, $file) if (defined $mode);
1066 sub file_to_s {
1067 my $file = shift;
1068 open my $fd,'<',$file or croak "$!: file: $file\n";
1069 local $/;
1070 my $ret = <$fd>;
1071 close $fd or croak $!;
1072 $ret =~ s/\s*$//s;
1073 return $ret;
1076 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1077 sub load_authors {
1078 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1079 my $log = $cmd eq 'log';
1080 while (<$authors>) {
1081 chomp;
1082 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1083 my ($user, $name, $email) = ($1, $2, $3);
1084 if ($log) {
1085 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1086 } else {
1087 $users{$user} = [$name, $email];
1090 close $authors or croak $!;
1093 # convert GetOpt::Long specs for use by git-config
1094 sub read_repo_config {
1095 return unless -d $ENV{GIT_DIR};
1096 my $opts = shift;
1097 my @config_only;
1098 foreach my $o (keys %$opts) {
1099 # if we have mixedCase and a long option-only, then
1100 # it's a config-only variable that we don't need for
1101 # the command-line.
1102 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1103 my $v = $opts->{$o};
1104 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1105 $key =~ s/-//g;
1106 my $arg = 'git-config';
1107 $arg .= ' --int' if ($o =~ /[:=]i$/);
1108 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1109 if (ref $v eq 'ARRAY') {
1110 chomp(my @tmp = `$arg --get-all svn.$key`);
1111 @$v = @tmp if @tmp;
1112 } else {
1113 chomp(my $tmp = `$arg --get svn.$key`);
1114 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1115 $$v = $tmp;
1119 delete @$opts{@config_only} if @config_only;
1122 sub extract_metadata {
1123 my $id = shift or return (undef, undef, undef);
1124 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1125 \s([a-f\d\-]+)$/x);
1126 if (!defined $rev || !$uuid || !$url) {
1127 # some of the original repositories I made had
1128 # identifiers like this:
1129 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1131 return ($url, $rev, $uuid);
1134 sub cmt_metadata {
1135 return extract_metadata((grep(/^git-svn-id: /,
1136 command(qw/cat-file commit/, shift)))[-1]);
1139 sub working_head_info {
1140 my ($head, $refs) = @_;
1141 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1142 my ($fh, $ctx) = command_output_pipe(@args, $head);
1143 my $hash;
1144 my %max;
1145 while (<$fh>) {
1146 if ( m{^commit ($::sha1)$} ) {
1147 unshift @$refs, $hash if $hash and $refs;
1148 $hash = $1;
1149 next;
1151 next unless s{^\s*(git-svn-id:)}{$1};
1152 my ($url, $rev, $uuid) = extract_metadata($_);
1153 if (defined $url && defined $rev) {
1154 next if $max{$url} and $max{$url} < $rev;
1155 if (my $gs = Git::SVN->find_by_url($url)) {
1156 my $c = $gs->rev_map_get($rev);
1157 if ($c && $c eq $hash) {
1158 close $fh; # break the pipe
1159 return ($url, $rev, $uuid, $gs);
1160 } else {
1161 $max{$url} ||= $gs->rev_map_max;
1166 command_close_pipe($fh, $ctx);
1167 (undef, undef, undef, undef);
1170 sub read_commit_parents {
1171 my ($parents, $c) = @_;
1172 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1173 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1174 @{$parents->{$c}} = split(/ /, $p);
1177 sub linearize_history {
1178 my ($gs, $refs) = @_;
1179 my %parents;
1180 foreach my $c (@$refs) {
1181 read_commit_parents(\%parents, $c);
1184 my @linear_refs;
1185 my %skip = ();
1186 my $last_svn_commit = $gs->last_commit;
1187 foreach my $c (reverse @$refs) {
1188 next if $c eq $last_svn_commit;
1189 last if $skip{$c};
1191 unshift @linear_refs, $c;
1192 $skip{$c} = 1;
1194 # we only want the first parent to diff against for linear
1195 # history, we save the rest to inject when we finalize the
1196 # svn commit
1197 my $fp_a = verify_ref("$c~1");
1198 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1199 if (!$fp_a || !$fp_b) {
1200 die "Commit $c\n",
1201 "has no parent commit, and therefore ",
1202 "nothing to diff against.\n",
1203 "You should be working from a repository ",
1204 "originally created by git-svn\n";
1206 if ($fp_a ne $fp_b) {
1207 die "$c~1 = $fp_a, however parsing commit $c ",
1208 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1211 foreach my $p (@{$parents{$c}}) {
1212 $skip{$p} = 1;
1215 (\@linear_refs, \%parents);
1218 sub find_file_type_and_diff_status {
1219 my ($path) = @_;
1220 return ('dir', '') if $path eq '.';
1222 my $diff_output =
1223 command_oneline(qw(diff --cached --name-status --), $path) || "";
1224 my $diff_status = (split(' ', $diff_output))[0] || "";
1226 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1228 return (undef, undef) if !$diff_status && !$ls_tree;
1230 if ($diff_status eq "A") {
1231 return ("link", $diff_status) if -l $path;
1232 return ("dir", $diff_status) if -d $path;
1233 return ("file", $diff_status);
1236 my $mode = (split(' ', $ls_tree))[0] || "";
1238 return ("link", $diff_status) if $mode eq "120000";
1239 return ("dir", $diff_status) if $mode eq "040000";
1240 return ("file", $diff_status);
1243 sub md5sum {
1244 my $arg = shift;
1245 my $ref = ref $arg;
1246 my $md5 = Digest::MD5->new();
1247 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1248 $md5->addfile($arg) or croak $!;
1249 } elsif ($ref eq 'SCALAR') {
1250 $md5->add($$arg) or croak $!;
1251 } elsif (!$ref) {
1252 $md5->add($arg) or croak $!;
1253 } else {
1254 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1256 return $md5->hexdigest();
1259 package Git::SVN;
1260 use strict;
1261 use warnings;
1262 use Fcntl qw/:DEFAULT :seek/;
1263 use constant rev_map_fmt => 'NH40';
1264 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1265 $_repack $_repack_flags $_use_svm_props $_head
1266 $_use_svnsync_props $no_reuse_existing $_minimize_url
1267 $_use_log_author $_add_author_from/;
1268 use Carp qw/croak/;
1269 use File::Path qw/mkpath/;
1270 use File::Copy qw/copy/;
1271 use IPC::Open3;
1273 my ($_gc_nr, $_gc_period);
1275 # properties that we do not log:
1276 my %SKIP_PROP;
1277 BEGIN {
1278 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1279 svn:special svn:executable
1280 svn:entry:committed-rev
1281 svn:entry:last-author
1282 svn:entry:uuid
1283 svn:entry:committed-date/;
1285 # some options are read globally, but can be overridden locally
1286 # per [svn-remote "..."] section. Command-line options will *NOT*
1287 # override options set in an [svn-remote "..."] section
1288 no strict 'refs';
1289 for my $option (qw/follow_parent no_metadata use_svm_props
1290 use_svnsync_props/) {
1291 my $key = $option;
1292 $key =~ tr/_//d;
1293 my $prop = "-$option";
1294 *$option = sub {
1295 my ($self) = @_;
1296 return $self->{$prop} if exists $self->{$prop};
1297 my $k = "svn-remote.$self->{repo_id}.$key";
1298 eval { command_oneline(qw/config --get/, $k) };
1299 if ($@) {
1300 $self->{$prop} = ${"Git::SVN::_$option"};
1301 } else {
1302 my $v = command_oneline(qw/config --bool/,$k);
1303 $self->{$prop} = $v eq 'false' ? 0 : 1;
1305 return $self->{$prop};
1310 my (%LOCKFILES, %INDEX_FILES);
1311 END {
1312 unlink keys %LOCKFILES if %LOCKFILES;
1313 unlink keys %INDEX_FILES if %INDEX_FILES;
1316 sub resolve_local_globs {
1317 my ($url, $fetch, $glob_spec) = @_;
1318 return unless defined $glob_spec;
1319 my $ref = $glob_spec->{ref};
1320 my $path = $glob_spec->{path};
1321 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1322 next unless m#^refs/remotes/$ref->{regex}$#;
1323 my $p = $1;
1324 my $pathname = desanitize_refname($path->full_path($p));
1325 my $refname = desanitize_refname($ref->full_path($p));
1326 if (my $existing = $fetch->{$pathname}) {
1327 if ($existing ne $refname) {
1328 die "Refspec conflict:\n",
1329 "existing: refs/remotes/$existing\n",
1330 " globbed: refs/remotes/$refname\n";
1332 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1333 $u =~ s!^\Q$url\E(/|$)!! or die
1334 "refs/remotes/$refname: '$url' not found in '$u'\n";
1335 if ($pathname ne $u) {
1336 warn "W: Refspec glob conflict ",
1337 "(ref: refs/remotes/$refname):\n",
1338 "expected path: $pathname\n",
1339 " real path: $u\n",
1340 "Continuing ahead with $u\n";
1341 next;
1343 } else {
1344 $fetch->{$pathname} = $refname;
1349 sub parse_revision_argument {
1350 my ($base, $head) = @_;
1351 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1352 return ($base, $head);
1354 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1355 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1356 return ($head, $head) if ($::_revision eq 'HEAD');
1357 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1358 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1359 die "revision argument: $::_revision not understood by git-svn\n";
1362 sub fetch_all {
1363 my ($repo_id, $remotes) = @_;
1364 if (ref $repo_id) {
1365 my $gs = $repo_id;
1366 $repo_id = undef;
1367 $repo_id = $gs->{repo_id};
1369 $remotes ||= read_all_remotes();
1370 my $remote = $remotes->{$repo_id} or
1371 die "[svn-remote \"$repo_id\"] unknown\n";
1372 my $fetch = $remote->{fetch};
1373 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1374 my (@gs, @globs);
1375 my $ra = Git::SVN::Ra->new($url);
1376 my $uuid = $ra->get_uuid;
1377 my $head = $ra->get_latest_revnum;
1378 my $base = defined $fetch ? $head : 0;
1380 # read the max revs for wildcard expansion (branches/*, tags/*)
1381 foreach my $t (qw/branches tags/) {
1382 defined $remote->{$t} or next;
1383 push @globs, $remote->{$t};
1384 my $max_rev = eval { tmp_config(qw/--int --get/,
1385 "svn-remote.$repo_id.${t}-maxRev") };
1386 if (defined $max_rev && ($max_rev < $base)) {
1387 $base = $max_rev;
1388 } elsif (!defined $max_rev) {
1389 $base = 0;
1393 if ($fetch) {
1394 foreach my $p (sort keys %$fetch) {
1395 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1396 my $lr = $gs->rev_map_max;
1397 if (defined $lr) {
1398 $base = $lr if ($lr < $base);
1400 push @gs, $gs;
1404 ($base, $head) = parse_revision_argument($base, $head);
1405 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1408 sub read_all_remotes {
1409 my $r = {};
1410 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1411 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1412 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1413 $local_ref =~ s{^/}{};
1414 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1415 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1416 $r->{$1}->{url} = $2;
1417 } elsif (m!^(.+)\.(branches|tags)=
1418 (.*):refs/remotes/(.+)\s*$/!x) {
1419 my ($p, $g) = ($3, $4);
1420 my $rs = $r->{$1}->{$2} = {
1421 t => $2,
1422 remote => $1,
1423 path => Git::SVN::GlobSpec->new($p),
1424 ref => Git::SVN::GlobSpec->new($g) };
1425 if (length($rs->{ref}->{right}) != 0) {
1426 die "The '*' glob character must be the last ",
1427 "character of '$g'\n";
1434 sub init_vars {
1435 $_gc_nr = $_gc_period = 1000;
1436 if (defined $_repack || defined $_repack_flags) {
1437 warn "Repack options are obsolete; they have no effect.\n";
1441 sub verify_remotes_sanity {
1442 return unless -d $ENV{GIT_DIR};
1443 my %seen;
1444 foreach (command(qw/config -l/)) {
1445 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1446 if ($seen{$1}) {
1447 die "Remote ref refs/remote/$1 is tracked by",
1448 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1449 "Please resolve this ambiguity in ",
1450 "your git configuration file before ",
1451 "continuing\n";
1453 $seen{$1} = $_;
1458 # we allow more chars than remotes2config.sh...
1459 sub sanitize_remote_name {
1460 my ($name) = @_;
1461 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1462 $name;
1465 sub find_existing_remote {
1466 my ($url, $remotes) = @_;
1467 return undef if $no_reuse_existing;
1468 my $existing;
1469 foreach my $repo_id (keys %$remotes) {
1470 my $u = $remotes->{$repo_id}->{url} or next;
1471 next if $u ne $url;
1472 $existing = $repo_id;
1473 last;
1475 $existing;
1478 sub init_remote_config {
1479 my ($self, $url, $no_write) = @_;
1480 $url =~ s!/+$!!; # strip trailing slash
1481 my $r = read_all_remotes();
1482 my $existing = find_existing_remote($url, $r);
1483 if ($existing) {
1484 unless ($no_write) {
1485 print STDERR "Using existing ",
1486 "[svn-remote \"$existing\"]\n";
1488 $self->{repo_id} = $existing;
1489 } elsif ($_minimize_url) {
1490 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1491 $existing = find_existing_remote($min_url, $r);
1492 if ($existing) {
1493 unless ($no_write) {
1494 print STDERR "Using existing ",
1495 "[svn-remote \"$existing\"]\n";
1497 $self->{repo_id} = $existing;
1499 if ($min_url ne $url) {
1500 unless ($no_write) {
1501 print STDERR "Using higher level of URL: ",
1502 "$url => $min_url\n";
1504 my $old_path = $self->{path};
1505 $self->{path} = $url;
1506 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1507 if (length $old_path) {
1508 $self->{path} .= "/$old_path";
1510 $url = $min_url;
1513 my $orig_url;
1514 if (!$existing) {
1515 # verify that we aren't overwriting anything:
1516 $orig_url = eval {
1517 command_oneline('config', '--get',
1518 "svn-remote.$self->{repo_id}.url")
1520 if ($orig_url && ($orig_url ne $url)) {
1521 die "svn-remote.$self->{repo_id}.url already set: ",
1522 "$orig_url\nwanted to set to: $url\n";
1525 my ($xrepo_id, $xpath) = find_ref($self->refname);
1526 if (defined $xpath) {
1527 die "svn-remote.$xrepo_id.fetch already set to track ",
1528 "$xpath:refs/remotes/", $self->refname, "\n";
1530 unless ($no_write) {
1531 command_noisy('config',
1532 "svn-remote.$self->{repo_id}.url", $url);
1533 $self->{path} =~ s{^/}{};
1534 command_noisy('config', '--add',
1535 "svn-remote.$self->{repo_id}.fetch",
1536 "$self->{path}:".$self->refname);
1538 $self->{url} = $url;
1541 sub find_by_url { # repos_root and, path are optional
1542 my ($class, $full_url, $repos_root, $path) = @_;
1544 return undef unless defined $full_url;
1545 remove_username($full_url);
1546 remove_username($repos_root) if defined $repos_root;
1547 my $remotes = read_all_remotes();
1548 if (defined $full_url && defined $repos_root && !defined $path) {
1549 $path = $full_url;
1550 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1552 foreach my $repo_id (keys %$remotes) {
1553 my $u = $remotes->{$repo_id}->{url} or next;
1554 remove_username($u);
1555 next if defined $repos_root && $repos_root ne $u;
1557 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1558 foreach (qw/branches tags/) {
1559 resolve_local_globs($u, $fetch,
1560 $remotes->{$repo_id}->{$_});
1562 my $p = $path;
1563 my $rwr = rewrite_root({repo_id => $repo_id});
1564 unless (defined $p) {
1565 $p = $full_url;
1566 my $z = $u;
1567 if ($rwr) {
1568 $z = $rwr;
1570 $p =~ s#^\Q$z\E(?:/|$)## or next;
1572 foreach my $f (keys %$fetch) {
1573 next if $f ne $p;
1574 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1577 undef;
1580 sub init {
1581 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1582 my $self = _new($class, $repo_id, $ref_id, $path);
1583 if (defined $url) {
1584 $self->init_remote_config($url, $no_write);
1586 $self;
1589 sub find_ref {
1590 my ($ref_id) = @_;
1591 foreach (command(qw/config -l/)) {
1592 next unless m!^svn-remote\.(.+)\.fetch=
1593 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1594 my ($repo_id, $path, $ref) = ($1, $2, $3);
1595 if ($ref eq $ref_id) {
1596 $path = '' if ($path =~ m#^\./?#);
1597 return ($repo_id, $path);
1600 (undef, undef, undef);
1603 sub new {
1604 my ($class, $ref_id, $repo_id, $path) = @_;
1605 if (defined $ref_id && !defined $repo_id && !defined $path) {
1606 ($repo_id, $path) = find_ref($ref_id);
1607 if (!defined $repo_id) {
1608 die "Could not find a \"svn-remote.*.fetch\" key ",
1609 "in the repository configuration matching: ",
1610 "refs/remotes/$ref_id\n";
1613 my $self = _new($class, $repo_id, $ref_id, $path);
1614 if (!defined $self->{path} || !length $self->{path}) {
1615 my $fetch = command_oneline('config', '--get',
1616 "svn-remote.$repo_id.fetch",
1617 ":refs/remotes/$ref_id\$") or
1618 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1619 "\":refs/remotes/$ref_id\$\" in config\n";
1620 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1622 $self->{url} = command_oneline('config', '--get',
1623 "svn-remote.$repo_id.url") or
1624 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1625 $self->rebuild;
1626 $self;
1629 sub refname {
1630 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1632 # It cannot end with a slash /, we'll throw up on this because
1633 # SVN can't have directories with a slash in their name, either:
1634 if ($refname =~ m{/$}) {
1635 die "ref: '$refname' ends with a trailing slash, this is ",
1636 "not permitted by git nor Subversion\n";
1639 # It cannot have ASCII control character space, tilde ~, caret ^,
1640 # colon :, question-mark ?, asterisk *, space, or open bracket [
1641 # anywhere.
1643 # Additionally, % must be escaped because it is used for escaping
1644 # and we want our escaped refname to be reversible
1645 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1647 # no slash-separated component can begin with a dot .
1648 # /.* becomes /%2E*
1649 $refname =~ s{/\.}{/%2E}g;
1651 # It cannot have two consecutive dots .. anywhere
1652 # .. becomes %2E%2E
1653 $refname =~ s{\.\.}{%2E%2E}g;
1655 return $refname;
1658 sub desanitize_refname {
1659 my ($refname) = @_;
1660 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1661 return $refname;
1664 sub svm_uuid {
1665 my ($self) = @_;
1666 return $self->{svm}->{uuid} if $self->svm;
1667 $self->ra;
1668 unless ($self->{svm}) {
1669 die "SVM UUID not cached, and reading remotely failed\n";
1671 $self->{svm}->{uuid};
1674 sub svm {
1675 my ($self) = @_;
1676 return $self->{svm} if $self->{svm};
1677 my $svm;
1678 # see if we have it in our config, first:
1679 eval {
1680 my $section = "svn-remote.$self->{repo_id}";
1681 $svm = {
1682 source => tmp_config('--get', "$section.svm-source"),
1683 uuid => tmp_config('--get', "$section.svm-uuid"),
1684 replace => tmp_config('--get', "$section.svm-replace"),
1687 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1688 $self->{svm} = $svm;
1690 $self->{svm};
1693 sub _set_svm_vars {
1694 my ($self, $ra) = @_;
1695 return $ra if $self->svm;
1697 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1698 "(svm:source, svm:uuid) ",
1699 "from the following URLs:\n" );
1700 sub read_svm_props {
1701 my ($self, $ra, $path, $r) = @_;
1702 my $props = ($ra->get_dir($path, $r))[2];
1703 my $src = $props->{'svm:source'};
1704 my $uuid = $props->{'svm:uuid'};
1705 return undef if (!$src || !$uuid);
1707 chomp($src, $uuid);
1709 $uuid =~ m{^[0-9a-f\-]{30,}$}
1710 or die "doesn't look right - svm:uuid is '$uuid'\n";
1712 # the '!' is used to mark the repos_root!/relative/path
1713 $src =~ s{/?!/?}{/};
1714 $src =~ s{/+$}{}; # no trailing slashes please
1715 # username is of no interest
1716 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1718 my $replace = $ra->{url};
1719 $replace .= "/$path" if length $path;
1721 my $section = "svn-remote.$self->{repo_id}";
1722 tmp_config("$section.svm-source", $src);
1723 tmp_config("$section.svm-replace", $replace);
1724 tmp_config("$section.svm-uuid", $uuid);
1725 $self->{svm} = {
1726 source => $src,
1727 uuid => $uuid,
1728 replace => $replace
1732 my $r = $ra->get_latest_revnum;
1733 my $path = $self->{path};
1734 my %tried;
1735 while (length $path) {
1736 unless ($tried{"$self->{url}/$path"}) {
1737 return $ra if $self->read_svm_props($ra, $path, $r);
1738 $tried{"$self->{url}/$path"} = 1;
1740 $path =~ s#/?[^/]+$##;
1742 die "Path: '$path' should be ''\n" if $path ne '';
1743 return $ra if $self->read_svm_props($ra, $path, $r);
1744 $tried{"$self->{url}/$path"} = 1;
1746 if ($ra->{repos_root} eq $self->{url}) {
1747 die @err, (map { " $_\n" } keys %tried), "\n";
1750 # nope, make sure we're connected to the repository root:
1751 my $ok;
1752 my @tried_b;
1753 $path = $ra->{svn_path};
1754 $ra = Git::SVN::Ra->new($ra->{repos_root});
1755 while (length $path) {
1756 unless ($tried{"$ra->{url}/$path"}) {
1757 $ok = $self->read_svm_props($ra, $path, $r);
1758 last if $ok;
1759 $tried{"$ra->{url}/$path"} = 1;
1761 $path =~ s#/?[^/]+$##;
1763 die "Path: '$path' should be ''\n" if $path ne '';
1764 $ok ||= $self->read_svm_props($ra, $path, $r);
1765 $tried{"$ra->{url}/$path"} = 1;
1766 if (!$ok) {
1767 die @err, (map { " $_\n" } keys %tried), "\n";
1769 Git::SVN::Ra->new($self->{url});
1772 sub svnsync {
1773 my ($self) = @_;
1774 return $self->{svnsync} if $self->{svnsync};
1776 if ($self->no_metadata) {
1777 die "Can't have both 'noMetadata' and ",
1778 "'useSvnsyncProps' options set!\n";
1780 if ($self->rewrite_root) {
1781 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1782 "options set!\n";
1785 my $svnsync;
1786 # see if we have it in our config, first:
1787 eval {
1788 my $section = "svn-remote.$self->{repo_id}";
1790 my $url = tmp_config('--get', "$section.svnsync-url");
1791 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1792 die "doesn't look right - svn:sync-from-url is '$url'\n";
1794 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1795 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1796 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1798 $svnsync = { url => $url, uuid => $uuid }
1800 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1801 return $self->{svnsync} = $svnsync;
1804 my $err = "useSvnsyncProps set, but failed to read " .
1805 "svnsync property: svn:sync-from-";
1806 my $rp = $self->ra->rev_proplist(0);
1808 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1809 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1810 die "doesn't look right - svn:sync-from-url is '$url'\n";
1812 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1813 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1814 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1816 my $section = "svn-remote.$self->{repo_id}";
1817 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1818 tmp_config('--add', "$section.svnsync-url", $url);
1819 return $self->{svnsync} = { url => $url, uuid => $uuid };
1822 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1823 # remote lookup (useful for 'git svn log').
1824 sub ra_uuid {
1825 my ($self) = @_;
1826 unless ($self->{ra_uuid}) {
1827 my $key = "svn-remote.$self->{repo_id}.uuid";
1828 my $uuid = eval { tmp_config('--get', $key) };
1829 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1830 $self->{ra_uuid} = $uuid;
1831 } else {
1832 die "ra_uuid called without URL\n" unless $self->{url};
1833 $self->{ra_uuid} = $self->ra->get_uuid;
1834 tmp_config('--add', $key, $self->{ra_uuid});
1837 $self->{ra_uuid};
1840 sub _set_repos_root {
1841 my ($self, $repos_root) = @_;
1842 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1843 $repos_root ||= $self->ra->{repos_root};
1844 tmp_config($k, $repos_root);
1845 $repos_root;
1848 sub repos_root {
1849 my ($self) = @_;
1850 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1851 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1854 sub ra {
1855 my ($self) = shift;
1856 my $ra = Git::SVN::Ra->new($self->{url});
1857 $self->_set_repos_root($ra->{repos_root});
1858 if ($self->use_svm_props && !$self->{svm}) {
1859 if ($self->no_metadata) {
1860 die "Can't have both 'noMetadata' and ",
1861 "'useSvmProps' options set!\n";
1862 } elsif ($self->use_svnsync_props) {
1863 die "Can't have both 'useSvnsyncProps' and ",
1864 "'useSvmProps' options set!\n";
1866 $ra = $self->_set_svm_vars($ra);
1867 $self->{-want_revprops} = 1;
1869 $ra;
1872 sub rel_path {
1873 my ($self) = @_;
1874 my $repos_root = $self->ra->{repos_root};
1875 return $self->{path} if ($self->{url} eq $repos_root);
1876 my $url = $self->{url} .
1877 (length $self->{path} ? "/$self->{path}" : $self->{path});
1878 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1879 $url;
1882 # prop_walk(PATH, REV, SUB)
1883 # -------------------------
1884 # Recursively traverse PATH at revision REV and invoke SUB for each
1885 # directory that contains a SVN property. SUB will be invoked as
1886 # follows: &SUB(gs, path, props); where `gs' is this instance of
1887 # Git::SVN, `path' the path to the directory where the properties
1888 # `props' were found. The `path' will be relative to point of checkout,
1889 # that is, if url://repo/trunk is the current Git branch, and that
1890 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1891 # as `path' (note the trailing `/').
1892 sub prop_walk {
1893 my ($self, $path, $rev, $sub) = @_;
1895 $path =~ s#^/##;
1896 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1897 $path =~ s#^/*#/#g;
1898 my $p = $path;
1899 # Strip the irrelevant part of the path.
1900 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1901 # Ensure the path is terminated by a `/'.
1902 $p =~ s#/*$#/#;
1904 # The properties contain all the internal SVN stuff nobody
1905 # (usually) cares about.
1906 my $interesting_props = 0;
1907 foreach (keys %{$props}) {
1908 # If it doesn't start with `svn:', it must be a
1909 # user-defined property.
1910 ++$interesting_props and next if $_ !~ /^svn:/;
1911 # FIXME: Fragile, if SVN adds new public properties,
1912 # this needs to be updated.
1913 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1914 |eol-style|mime-type
1915 |externals|needs-lock)$/x;
1917 &$sub($self, $p, $props) if $interesting_props;
1919 foreach (sort keys %$dirent) {
1920 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1921 $self->prop_walk($p . $_, $rev, $sub);
1925 sub last_rev { ($_[0]->last_rev_commit)[0] }
1926 sub last_commit { ($_[0]->last_rev_commit)[1] }
1928 # returns the newest SVN revision number and newest commit SHA1
1929 sub last_rev_commit {
1930 my ($self) = @_;
1931 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1932 return ($self->{last_rev}, $self->{last_commit});
1934 my $c = ::verify_ref($self->refname.'^0');
1935 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1936 my $rev = (::cmt_metadata($c))[1];
1937 if (defined $rev) {
1938 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1939 return ($rev, $c);
1942 my $map_path = $self->map_path;
1943 unless (-e $map_path) {
1944 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1945 return (undef, undef);
1947 my ($rev, $commit) = $self->rev_map_max(1);
1948 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1949 return ($rev, $commit);
1952 sub get_fetch_range {
1953 my ($self, $min, $max) = @_;
1954 $max ||= $self->ra->get_latest_revnum;
1955 $min ||= $self->rev_map_max;
1956 (++$min, $max);
1959 sub tmp_config {
1960 my (@args) = @_;
1961 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1962 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1963 if (! -f $config && -f $old_def_config) {
1964 rename $old_def_config, $config or
1965 die "Failed rename $old_def_config => $config: $!\n";
1967 my $old_config = $ENV{GIT_CONFIG};
1968 $ENV{GIT_CONFIG} = $config;
1969 $@ = undef;
1970 my @ret = eval {
1971 unless (-f $config) {
1972 mkfile($config);
1973 open my $fh, '>', $config or
1974 die "Can't open $config: $!\n";
1975 print $fh "; This file is used internally by ",
1976 "git-svn\n" or die
1977 "Couldn't write to $config: $!\n";
1978 print $fh "; You should not have to edit it\n" or
1979 die "Couldn't write to $config: $!\n";
1980 close $fh or die "Couldn't close $config: $!\n";
1982 command('config', @args);
1984 my $err = $@;
1985 if (defined $old_config) {
1986 $ENV{GIT_CONFIG} = $old_config;
1987 } else {
1988 delete $ENV{GIT_CONFIG};
1990 die $err if $err;
1991 wantarray ? @ret : $ret[0];
1994 sub tmp_index_do {
1995 my ($self, $sub) = @_;
1996 my $old_index = $ENV{GIT_INDEX_FILE};
1997 $ENV{GIT_INDEX_FILE} = $self->{index};
1998 $@ = undef;
1999 my @ret = eval {
2000 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2001 mkpath([$dir]) unless -d $dir;
2002 &$sub;
2004 my $err = $@;
2005 if (defined $old_index) {
2006 $ENV{GIT_INDEX_FILE} = $old_index;
2007 } else {
2008 delete $ENV{GIT_INDEX_FILE};
2010 die $err if $err;
2011 wantarray ? @ret : $ret[0];
2014 sub assert_index_clean {
2015 my ($self, $treeish) = @_;
2017 $self->tmp_index_do(sub {
2018 command_noisy('read-tree', $treeish) unless -e $self->{index};
2019 my $x = command_oneline('write-tree');
2020 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2021 /^tree ($::sha1)/mo);
2022 return if $y eq $x;
2024 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2025 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2026 command_noisy('read-tree', $treeish);
2027 $x = command_oneline('write-tree');
2028 if ($y ne $x) {
2029 ::fatal "trees ($treeish) $y != $x\n",
2030 "Something is seriously wrong...";
2035 sub get_commit_parents {
2036 my ($self, $log_entry) = @_;
2037 my (%seen, @ret, @tmp);
2038 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2039 if (my $ip = $self->{inject_parents}) {
2040 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2041 push @tmp, $commit;
2044 if (my $cur = ::verify_ref($self->refname.'^0')) {
2045 push @tmp, $cur;
2047 if (my $ipd = $self->{inject_parents_dcommit}) {
2048 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2049 push @tmp, @$commit;
2052 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2053 while (my $p = shift @tmp) {
2054 next if $seen{$p};
2055 $seen{$p} = 1;
2056 push @ret, $p;
2057 # MAXPARENT is defined to 16 in commit-tree.c:
2058 last if @ret >= 16;
2060 if (@tmp) {
2061 die "r$log_entry->{revision}: No room for parents:\n\t",
2062 join("\n\t", @tmp), "\n";
2064 @ret;
2067 sub rewrite_root {
2068 my ($self) = @_;
2069 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2070 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2071 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2072 if ($rwr) {
2073 $rwr =~ s#/+$##;
2074 if ($rwr !~ m#^[a-z\+]+://#) {
2075 die "$rwr is not a valid URL (key: $k)\n";
2078 $self->{-rewrite_root} = $rwr;
2081 sub metadata_url {
2082 my ($self) = @_;
2083 ($self->rewrite_root || $self->{url}) .
2084 (length $self->{path} ? '/' . $self->{path} : '');
2087 sub full_url {
2088 my ($self) = @_;
2089 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2093 sub set_commit_header_env {
2094 my ($log_entry) = @_;
2095 my %env;
2096 foreach my $ned (qw/NAME EMAIL DATE/) {
2097 foreach my $ac (qw/AUTHOR COMMITTER/) {
2098 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2102 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2103 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2104 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2106 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2107 ? $log_entry->{commit_name}
2108 : $log_entry->{name};
2109 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2110 ? $log_entry->{commit_email}
2111 : $log_entry->{email};
2112 \%env;
2115 sub restore_commit_header_env {
2116 my ($env) = @_;
2117 foreach my $ned (qw/NAME EMAIL DATE/) {
2118 foreach my $ac (qw/AUTHOR COMMITTER/) {
2119 my $k = "GIT_${ac}_${ned}";
2120 if (defined $env->{$k}) {
2121 $ENV{$k} = $env->{$k};
2122 } else {
2123 delete $ENV{$k};
2129 sub gc {
2130 command_noisy('gc', '--auto');
2133 sub do_git_commit {
2134 my ($self, $log_entry) = @_;
2135 my $lr = $self->last_rev;
2136 if (defined $lr && $lr >= $log_entry->{revision}) {
2137 die "Last fetched revision of ", $self->refname,
2138 " was r$lr, but we are about to fetch: ",
2139 "r$log_entry->{revision}!\n";
2141 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2142 croak "$log_entry->{revision} = $c already exists! ",
2143 "Why are we refetching it?\n";
2145 my $old_env = set_commit_header_env($log_entry);
2146 my $tree = $log_entry->{tree};
2147 if (!defined $tree) {
2148 $tree = $self->tmp_index_do(sub {
2149 command_oneline('write-tree') });
2151 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2153 my @exec = ('git-commit-tree', $tree);
2154 foreach ($self->get_commit_parents($log_entry)) {
2155 push @exec, '-p', $_;
2157 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2158 or croak $!;
2159 print $msg_fh $log_entry->{log} or croak $!;
2160 restore_commit_header_env($old_env);
2161 unless ($self->no_metadata) {
2162 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2163 or croak $!;
2165 $msg_fh->flush == 0 or croak $!;
2166 close $msg_fh or croak $!;
2167 chomp(my $commit = do { local $/; <$out_fh> });
2168 close $out_fh or croak $!;
2169 waitpid $pid, 0;
2170 croak $? if $?;
2171 if ($commit !~ /^$::sha1$/o) {
2172 die "Failed to commit, invalid sha1: $commit\n";
2175 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2177 $self->{last_rev} = $log_entry->{revision};
2178 $self->{last_commit} = $commit;
2179 print "r$log_entry->{revision}";
2180 if (defined $log_entry->{svm_revision}) {
2181 print " (\@$log_entry->{svm_revision})";
2182 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2183 0, $self->svm_uuid);
2185 print " = $commit ($self->{ref_id})\n";
2186 if (--$_gc_nr == 0) {
2187 $_gc_nr = $_gc_period;
2188 gc();
2190 return $commit;
2193 sub match_paths {
2194 my ($self, $paths, $r) = @_;
2195 return 1 if $self->{path} eq '';
2196 if (my $path = $paths->{"/$self->{path}"}) {
2197 return ($path->{action} eq 'D') ? 0 : 1;
2199 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2200 if (grep /$self->{path_regex}/, keys %$paths) {
2201 return 1;
2203 my $c = '';
2204 foreach (split m#/#, $self->{path}) {
2205 $c .= "/$_";
2206 next unless ($paths->{$c} &&
2207 ($paths->{$c}->{action} =~ /^[AR]$/));
2208 if ($self->ra->check_path($self->{path}, $r) ==
2209 $SVN::Node::dir) {
2210 return 1;
2213 return 0;
2216 sub find_parent_branch {
2217 my ($self, $paths, $rev) = @_;
2218 return undef unless $self->follow_parent;
2219 unless (defined $paths) {
2220 my $err_handler = $SVN::Error::handler;
2221 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2222 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2223 $paths =
2224 Git::SVN::Ra::dup_changed_paths($_[0]) });
2225 $SVN::Error::handler = $err_handler;
2227 return undef unless defined $paths;
2229 # look for a parent from another branch:
2230 my @b_path_components = split m#/#, $self->rel_path;
2231 my @a_path_components;
2232 my $i;
2233 while (@b_path_components) {
2234 $i = $paths->{'/'.join('/', @b_path_components)};
2235 last if $i && defined $i->{copyfrom_path};
2236 unshift(@a_path_components, pop(@b_path_components));
2238 return undef unless defined $i && defined $i->{copyfrom_path};
2239 my $branch_from = $i->{copyfrom_path};
2240 if (@a_path_components) {
2241 print STDERR "branch_from: $branch_from => ";
2242 $branch_from .= '/'.join('/', @a_path_components);
2243 print STDERR $branch_from, "\n";
2245 my $r = $i->{copyfrom_rev};
2246 my $repos_root = $self->ra->{repos_root};
2247 my $url = $self->ra->{url};
2248 my $new_url = $repos_root . $branch_from;
2249 print STDERR "Found possible branch point: ",
2250 "$new_url => ", $self->full_url, ", $r\n";
2251 $branch_from =~ s#^/##;
2252 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2253 unless ($gs) {
2254 my $ref_id = $self->{ref_id};
2255 $ref_id =~ s/\@\d+$//;
2256 $ref_id .= "\@$r";
2257 # just grow a tail if we're not unique enough :x
2258 $ref_id .= '-' while find_ref($ref_id);
2259 print STDERR "Initializing parent: $ref_id\n";
2260 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2261 if ($u =~ s#^\Q$url\E(/|$)##) {
2262 $p = $u;
2263 $u = $url;
2264 $repo_id = $self->{repo_id};
2266 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2268 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2269 if (!defined $r0 || !defined $parent) {
2270 my ($base, $head) = parse_revision_argument(0, $r);
2271 if ($base <= $r) {
2272 $gs->fetch($base, $r);
2274 ($r0, $parent) = $gs->last_rev_commit;
2276 if (defined $r0 && defined $parent) {
2277 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2278 my $ed;
2279 if ($self->ra->can_do_switch) {
2280 $self->assert_index_clean($parent);
2281 print STDERR "Following parent with do_switch\n";
2282 # do_switch works with svn/trunk >= r22312, but that
2283 # is not included with SVN 1.4.3 (the latest version
2284 # at the moment), so we can't rely on it
2285 $self->{last_commit} = $parent;
2286 $ed = SVN::Git::Fetcher->new($self);
2287 $gs->ra->gs_do_switch($r0, $rev, $gs,
2288 $self->full_url, $ed)
2289 or die "SVN connection failed somewhere...\n";
2290 } elsif ($self->ra->trees_match($new_url, $r0,
2291 $self->full_url, $rev)) {
2292 print STDERR "Trees match:\n",
2293 " $new_url\@$r0\n",
2294 " ${\$self->full_url}\@$rev\n",
2295 "Following parent with no changes\n";
2296 $self->tmp_index_do(sub {
2297 command_noisy('read-tree', $parent);
2299 $self->{last_commit} = $parent;
2300 } else {
2301 print STDERR "Following parent with do_update\n";
2302 $ed = SVN::Git::Fetcher->new($self);
2303 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2304 or die "SVN connection failed somewhere...\n";
2306 print STDERR "Successfully followed parent\n";
2307 return $self->make_log_entry($rev, [$parent], $ed);
2309 return undef;
2312 sub do_fetch {
2313 my ($self, $paths, $rev) = @_;
2314 my $ed;
2315 my ($last_rev, @parents);
2316 if (my $lc = $self->last_commit) {
2317 # we can have a branch that was deleted, then re-added
2318 # under the same name but copied from another path, in
2319 # which case we'll have multiple parents (we don't
2320 # want to break the original ref, nor lose copypath info):
2321 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2322 push @{$log_entry->{parents}}, $lc;
2323 return $log_entry;
2325 $ed = SVN::Git::Fetcher->new($self);
2326 $last_rev = $self->{last_rev};
2327 $ed->{c} = $lc;
2328 @parents = ($lc);
2329 } else {
2330 $last_rev = $rev;
2331 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2332 return $log_entry;
2334 $ed = SVN::Git::Fetcher->new($self);
2336 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2337 die "SVN connection failed somewhere...\n";
2339 $self->make_log_entry($rev, \@parents, $ed);
2342 sub get_untracked {
2343 my ($self, $ed) = @_;
2344 my @out;
2345 my $h = $ed->{empty};
2346 foreach (sort keys %$h) {
2347 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2348 push @out, " $act: " . uri_encode($_);
2349 warn "W: $act: $_\n";
2351 foreach my $t (qw/dir_prop file_prop/) {
2352 $h = $ed->{$t} or next;
2353 foreach my $path (sort keys %$h) {
2354 my $ppath = $path eq '' ? '.' : $path;
2355 foreach my $prop (sort keys %{$h->{$path}}) {
2356 next if $SKIP_PROP{$prop};
2357 my $v = $h->{$path}->{$prop};
2358 my $t_ppath_prop = "$t: " .
2359 uri_encode($ppath) . ' ' .
2360 uri_encode($prop);
2361 if (defined $v) {
2362 push @out, " +$t_ppath_prop " .
2363 uri_encode($v);
2364 } else {
2365 push @out, " -$t_ppath_prop";
2370 foreach my $t (qw/absent_file absent_directory/) {
2371 $h = $ed->{$t} or next;
2372 foreach my $parent (sort keys %$h) {
2373 foreach my $path (sort @{$h->{$parent}}) {
2374 push @out, " $t: " .
2375 uri_encode("$parent/$path");
2376 warn "W: $t: $parent/$path ",
2377 "Insufficient permissions?\n";
2381 \@out;
2384 sub parse_svn_date {
2385 my $date = shift || return '+0000 1970-01-01 00:00:00';
2386 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2387 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2388 croak "Unable to parse date: $date\n";
2389 "+0000 $Y-$m-$d $H:$M:$S";
2392 sub check_author {
2393 my ($author) = @_;
2394 if (!defined $author || length $author == 0) {
2395 $author = '(no author)';
2396 } elsif (defined $::_authors && ! defined $::users{$author}) {
2397 die "Author: $author not defined in $::_authors file\n";
2399 $author;
2402 sub make_log_entry {
2403 my ($self, $rev, $parents, $ed) = @_;
2404 my $untracked = $self->get_untracked($ed);
2406 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2407 print $un "r$rev\n" or croak $!;
2408 print $un $_, "\n" foreach @$untracked;
2409 my %log_entry = ( parents => $parents || [], revision => $rev,
2410 log => '');
2412 my $headrev;
2413 my $logged = delete $self->{logged_rev_props};
2414 if (!$logged || $self->{-want_revprops}) {
2415 my $rp = $self->ra->rev_proplist($rev);
2416 foreach (sort keys %$rp) {
2417 my $v = $rp->{$_};
2418 if (/^svn:(author|date|log)$/) {
2419 $log_entry{$1} = $v;
2420 } elsif ($_ eq 'svm:headrev') {
2421 $headrev = $v;
2422 } else {
2423 print $un " rev_prop: ", uri_encode($_), ' ',
2424 uri_encode($v), "\n";
2427 } else {
2428 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2430 close $un or croak $!;
2432 $log_entry{date} = parse_svn_date($log_entry{date});
2433 $log_entry{log} .= "\n";
2434 my $author = $log_entry{author} = check_author($log_entry{author});
2435 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2436 : ($author, undef);
2438 my ($commit_name, $commit_email) = ($name, $email);
2439 if ($_use_log_author) {
2440 my $name_field;
2441 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2442 $name_field = $1;
2443 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2444 $name_field = $1;
2446 if (!defined $name_field) {
2447 if (!defined $email) {
2448 $email = $name;
2450 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2451 ($name, $email) = ($1, $2);
2452 } elsif ($name_field =~ /(.*)@/) {
2453 ($name, $email) = ($1, $name_field);
2454 } else {
2455 ($name, $email) = ($name_field, $name_field);
2458 if (defined $headrev && $self->use_svm_props) {
2459 if ($self->rewrite_root) {
2460 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2461 "options set!\n";
2463 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2464 # we don't want "SVM: initializing mirror for junk" ...
2465 return undef if $r == 0;
2466 my $svm = $self->svm;
2467 if ($uuid ne $svm->{uuid}) {
2468 die "UUID mismatch on SVM path:\n",
2469 "expected: $svm->{uuid}\n",
2470 " got: $uuid\n";
2472 my $full_url = $self->full_url;
2473 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2474 die "Failed to replace '$svm->{replace}' with ",
2475 "'$svm->{source}' in $full_url\n";
2476 # throw away username for storing in records
2477 remove_username($full_url);
2478 $log_entry{metadata} = "$full_url\@$r $uuid";
2479 $log_entry{svm_revision} = $r;
2480 $email ||= "$author\@$uuid";
2481 $commit_email ||= "$author\@$uuid";
2482 } elsif ($self->use_svnsync_props) {
2483 my $full_url = $self->svnsync->{url};
2484 $full_url .= "/$self->{path}" if length $self->{path};
2485 remove_username($full_url);
2486 my $uuid = $self->svnsync->{uuid};
2487 $log_entry{metadata} = "$full_url\@$rev $uuid";
2488 $email ||= "$author\@$uuid";
2489 $commit_email ||= "$author\@$uuid";
2490 } else {
2491 my $url = $self->metadata_url;
2492 remove_username($url);
2493 $log_entry{metadata} = "$url\@$rev " .
2494 $self->ra->get_uuid;
2495 $email ||= "$author\@" . $self->ra->get_uuid;
2496 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2498 $log_entry{name} = $name;
2499 $log_entry{email} = $email;
2500 $log_entry{commit_name} = $commit_name;
2501 $log_entry{commit_email} = $commit_email;
2502 \%log_entry;
2505 sub fetch {
2506 my ($self, $min_rev, $max_rev, @parents) = @_;
2507 my ($last_rev, $last_commit) = $self->last_rev_commit;
2508 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2509 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2512 sub set_tree_cb {
2513 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2514 $self->{inject_parents} = { $rev => $tree };
2515 $self->fetch(undef, undef);
2518 sub set_tree {
2519 my ($self, $tree) = (shift, shift);
2520 my $log_entry = ::get_commit_entry($tree);
2521 unless ($self->{last_rev}) {
2522 fatal("Must have an existing revision to commit");
2524 my %ed_opts = ( r => $self->{last_rev},
2525 log => $log_entry->{log},
2526 ra => $self->ra,
2527 tree_a => $self->{last_commit},
2528 tree_b => $tree,
2529 editor_cb => sub {
2530 $self->set_tree_cb($log_entry, $tree, @_) },
2531 svn_path => $self->{path} );
2532 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2533 print "No changes\nr$self->{last_rev} = $tree\n";
2537 sub rebuild_from_rev_db {
2538 my ($self, $path) = @_;
2539 my $r = -1;
2540 open my $fh, '<', $path or croak "open: $!";
2541 binmode $fh or croak "binmode: $!";
2542 while (<$fh>) {
2543 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2544 chomp($_);
2545 ++$r;
2546 next if $_ eq ('0' x 40);
2547 $self->rev_map_set($r, $_);
2548 print "r$r = $_\n";
2550 close $fh or croak "close: $!";
2551 unlink $path or croak "unlink: $!";
2554 sub rebuild {
2555 my ($self) = @_;
2556 my $map_path = $self->map_path;
2557 return if (-e $map_path && ! -z $map_path);
2558 return unless ::verify_ref($self->refname.'^0');
2559 if ($self->use_svm_props || $self->no_metadata) {
2560 my $rev_db = $self->rev_db_path;
2561 $self->rebuild_from_rev_db($rev_db);
2562 if ($self->use_svm_props) {
2563 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2564 $self->rebuild_from_rev_db($svm_rev_db);
2566 $self->unlink_rev_db_symlink;
2567 return;
2569 print "Rebuilding $map_path ...\n";
2570 my ($log, $ctx) =
2571 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2572 $self->refname, '--');
2573 my $full_url = $self->full_url;
2574 remove_username($full_url);
2575 my $svn_uuid = $self->ra_uuid;
2576 my $c;
2577 while (<$log>) {
2578 if ( m{^commit ($::sha1)$} ) {
2579 $c = $1;
2580 next;
2582 next unless s{^\s*(git-svn-id:)}{$1};
2583 my ($url, $rev, $uuid) = ::extract_metadata($_);
2584 remove_username($url);
2586 # ignore merges (from set-tree)
2587 next if (!defined $rev || !$uuid);
2589 # if we merged or otherwise started elsewhere, this is
2590 # how we break out of it
2591 if (($uuid ne $svn_uuid) ||
2592 ($full_url && $url && ($url ne $full_url))) {
2593 next;
2596 $self->rev_map_set($rev, $c);
2597 print "r$rev = $c\n";
2599 command_close_pipe($log, $ctx);
2600 print "Done rebuilding $map_path\n";
2601 my $rev_db_path = $self->rev_db_path;
2602 if (-f $self->rev_db_path) {
2603 unlink $self->rev_db_path or croak "unlink: $!";
2605 $self->unlink_rev_db_symlink;
2608 # rev_map:
2609 # Tie::File seems to be prone to offset errors if revisions get sparse,
2610 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2611 # one of my favorite modules is out :< Next up would be one of the DBM
2612 # modules, but I'm not sure which is most portable...
2614 # This is the replacement for the rev_db format, which was too big
2615 # and inefficient for large repositories with a lot of sparse history
2616 # (mainly tags)
2618 # The format is this:
2619 # - 24 bytes for every record,
2620 # * 4 bytes for the integer representing an SVN revision number
2621 # * 20 bytes representing the sha1 of a git commit
2622 # - No empty padding records like the old format
2623 # (except the last record, which can be overwritten)
2624 # - new records are written append-only since SVN revision numbers
2625 # increase monotonically
2626 # - lookups on SVN revision number are done via a binary search
2627 # - Piping the file to xxd -c24 is a good way of dumping it for
2628 # viewing or editing (piped back through xxd -r), should the need
2629 # ever arise.
2630 # - The last record can be padding revision with an all-zero sha1
2631 # This is used to optimize fetch performance when using multiple
2632 # "fetch" directives in .git/config
2634 # These files are disposable unless noMetadata or useSvmProps is set
2636 sub _rev_map_set {
2637 my ($fh, $rev, $commit) = @_;
2639 binmode $fh or croak "binmode: $!";
2640 my $size = (stat($fh))[7];
2641 ($size % 24) == 0 or croak "inconsistent size: $size";
2643 my $wr_offset = 0;
2644 if ($size > 0) {
2645 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2646 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2647 $read == 24 or croak "read only $read bytes (!= 24)";
2648 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2649 if ($last_commit eq ('0' x40)) {
2650 if ($size >= 48) {
2651 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2652 $read = sysread($fh, $buf, 24) or
2653 croak "read: $!";
2654 $read == 24 or
2655 croak "read only $read bytes (!= 24)";
2656 ($last_rev, $last_commit) =
2657 unpack(rev_map_fmt, $buf);
2658 if ($last_commit eq ('0' x40)) {
2659 croak "inconsistent .rev_map\n";
2662 if ($last_rev >= $rev) {
2663 croak "last_rev is higher!: $last_rev >= $rev";
2665 $wr_offset = -24;
2668 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2669 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2670 croak "write: $!";
2673 sub mkfile {
2674 my ($path) = @_;
2675 unless (-e $path) {
2676 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2677 mkpath([$dir]) unless -d $dir;
2678 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2679 close $fh or die "Couldn't close (create) $path: $!\n";
2683 sub rev_map_set {
2684 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2685 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2686 my $db = $self->map_path($uuid);
2687 my $db_lock = "$db.lock";
2688 my $sig;
2689 if ($update_ref) {
2690 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2691 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2693 mkfile($db);
2695 $LOCKFILES{$db_lock} = 1;
2696 my $sync;
2697 # both of these options make our .rev_db file very, very important
2698 # and we can't afford to lose it because rebuild() won't work
2699 if ($self->use_svm_props || $self->no_metadata) {
2700 $sync = 1;
2701 copy($db, $db_lock) or die "rev_map_set(@_): ",
2702 "Failed to copy: ",
2703 "$db => $db_lock ($!)\n";
2704 } else {
2705 rename $db, $db_lock or die "rev_map_set(@_): ",
2706 "Failed to rename: ",
2707 "$db => $db_lock ($!)\n";
2710 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2711 or croak "Couldn't open $db_lock: $!\n";
2712 _rev_map_set($fh, $rev, $commit);
2713 if ($sync) {
2714 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2715 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2717 close $fh or croak $!;
2718 if ($update_ref) {
2719 $_head = $self;
2720 command_noisy('update-ref', '-m', "r$rev",
2721 $self->refname, $commit);
2723 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2724 "$db_lock => $db ($!)\n";
2725 delete $LOCKFILES{$db_lock};
2726 if ($update_ref) {
2727 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2728 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2729 kill $sig, $$ if defined $sig;
2733 # If want_commit, this will return an array of (rev, commit) where
2734 # commit _must_ be a valid commit in the archive.
2735 # Otherwise, it'll return the max revision (whether or not the
2736 # commit is valid or just a 0x40 placeholder).
2737 sub rev_map_max {
2738 my ($self, $want_commit) = @_;
2739 $self->rebuild;
2740 my $map_path = $self->map_path;
2741 stat $map_path or return $want_commit ? (0, undef) : 0;
2742 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2743 binmode $fh or croak "binmode: $!";
2744 my $size = (stat($fh))[7];
2745 ($size % 24) == 0 or croak "inconsistent size: $size";
2747 if ($size == 0) {
2748 close $fh or croak "close: $!";
2749 return $want_commit ? (0, undef) : 0;
2752 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2753 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2754 my ($r, $c) = unpack(rev_map_fmt, $buf);
2755 if ($want_commit && $c eq ('0' x40)) {
2756 if ($size < 48) {
2757 return $want_commit ? (0, undef) : 0;
2759 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2760 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2761 ($r, $c) = unpack(rev_map_fmt, $buf);
2762 if ($c eq ('0'x40)) {
2763 croak "Penultimate record is all-zeroes in $map_path";
2766 close $fh or croak "close: $!";
2767 $want_commit ? ($r, $c) : $r;
2770 sub rev_map_get {
2771 my ($self, $rev, $uuid) = @_;
2772 my $map_path = $self->map_path($uuid);
2773 return undef unless -e $map_path;
2775 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2776 binmode $fh or croak "binmode: $!";
2777 my $size = (stat($fh))[7];
2778 ($size % 24) == 0 or croak "inconsistent size: $size";
2780 if ($size == 0) {
2781 close $fh or croak "close: $fh";
2782 return undef;
2785 my ($l, $u) = (0, $size - 24);
2786 my ($r, $c, $buf);
2788 while ($l <= $u) {
2789 my $i = int(($l/24 + $u/24) / 2) * 24;
2790 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2791 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2792 my ($r, $c) = unpack('NH40', $buf);
2794 if ($r < $rev) {
2795 $l = $i + 24;
2796 } elsif ($r > $rev) {
2797 $u = $i - 24;
2798 } else { # $r == $rev
2799 close($fh) or croak "close: $!";
2800 return $c eq ('0' x 40) ? undef : $c;
2803 close($fh) or croak "close: $!";
2804 undef;
2807 # Finds the first svn revision that exists on (if $eq_ok is true) or
2808 # before $rev for the current branch. It will not search any lower
2809 # than $min_rev. Returns the git commit hash and svn revision number
2810 # if found, else (undef, undef).
2811 sub find_rev_before {
2812 my ($self, $rev, $eq_ok, $min_rev) = @_;
2813 --$rev unless $eq_ok;
2814 $min_rev ||= 1;
2815 while ($rev >= $min_rev) {
2816 if (my $c = $self->rev_map_get($rev)) {
2817 return ($rev, $c);
2819 --$rev;
2821 return (undef, undef);
2824 # Finds the first svn revision that exists on (if $eq_ok is true) or
2825 # after $rev for the current branch. It will not search any higher
2826 # than $max_rev. Returns the git commit hash and svn revision number
2827 # if found, else (undef, undef).
2828 sub find_rev_after {
2829 my ($self, $rev, $eq_ok, $max_rev) = @_;
2830 ++$rev unless $eq_ok;
2831 $max_rev ||= $self->rev_map_max;
2832 while ($rev <= $max_rev) {
2833 if (my $c = $self->rev_map_get($rev)) {
2834 return ($rev, $c);
2836 ++$rev;
2838 return (undef, undef);
2841 sub _new {
2842 my ($class, $repo_id, $ref_id, $path) = @_;
2843 unless (defined $repo_id && length $repo_id) {
2844 $repo_id = $Git::SVN::default_repo_id;
2846 unless (defined $ref_id && length $ref_id) {
2847 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2849 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2850 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2851 $_[3] = $path = '' unless (defined $path);
2852 mkpath(["$ENV{GIT_DIR}/svn"]);
2853 bless {
2854 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2855 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2856 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2859 # for read-only access of old .rev_db formats
2860 sub unlink_rev_db_symlink {
2861 my ($self) = @_;
2862 my $link = $self->rev_db_path;
2863 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2864 if (-l $link) {
2865 unlink $link or croak "unlink: $link failed!";
2869 sub rev_db_path {
2870 my ($self, $uuid) = @_;
2871 my $db_path = $self->map_path($uuid);
2872 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2873 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2874 $db_path;
2877 # the new replacement for .rev_db
2878 sub map_path {
2879 my ($self, $uuid) = @_;
2880 $uuid ||= $self->ra_uuid;
2881 "$self->{map_root}.$uuid";
2884 sub uri_encode {
2885 my ($f) = @_;
2886 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2890 sub remove_username {
2891 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2894 package Git::SVN::Prompt;
2895 use strict;
2896 use warnings;
2897 require SVN::Core;
2898 use vars qw/$_no_auth_cache $_username/;
2900 sub simple {
2901 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2902 $may_save = undef if $_no_auth_cache;
2903 $default_username = $_username if defined $_username;
2904 if (defined $default_username && length $default_username) {
2905 if (defined $realm && length $realm) {
2906 print STDERR "Authentication realm: $realm\n";
2907 STDERR->flush;
2909 $cred->username($default_username);
2910 } else {
2911 username($cred, $realm, $may_save, $pool);
2913 $cred->password(_read_password("Password for '" .
2914 $cred->username . "': ", $realm));
2915 $cred->may_save($may_save);
2916 $SVN::_Core::SVN_NO_ERROR;
2919 sub ssl_server_trust {
2920 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2921 $may_save = undef if $_no_auth_cache;
2922 print STDERR "Error validating server certificate for '$realm':\n";
2924 no warnings 'once';
2925 # All variables SVN::Auth::SSL::* are used only once,
2926 # so we're shutting up Perl warnings about this.
2927 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2928 print STDERR " - The certificate is not issued ",
2929 "by a trusted authority. Use the\n",
2930 " fingerprint to validate ",
2931 "the certificate manually!\n";
2933 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2934 print STDERR " - The certificate hostname ",
2935 "does not match.\n";
2937 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2938 print STDERR " - The certificate is not yet valid.\n";
2940 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2941 print STDERR " - The certificate has expired.\n";
2943 if ($failures & $SVN::Auth::SSL::OTHER) {
2944 print STDERR " - The certificate has ",
2945 "an unknown error.\n";
2947 } # no warnings 'once'
2948 printf STDERR
2949 "Certificate information:\n".
2950 " - Hostname: %s\n".
2951 " - Valid: from %s until %s\n".
2952 " - Issuer: %s\n".
2953 " - Fingerprint: %s\n",
2954 map $cert_info->$_, qw(hostname valid_from valid_until
2955 issuer_dname fingerprint);
2956 my $choice;
2957 prompt:
2958 print STDERR $may_save ?
2959 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2960 "(R)eject or accept (t)emporarily? ";
2961 STDERR->flush;
2962 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2963 if ($choice =~ /^t$/i) {
2964 $cred->may_save(undef);
2965 } elsif ($choice =~ /^r$/i) {
2966 return -1;
2967 } elsif ($may_save && $choice =~ /^p$/i) {
2968 $cred->may_save($may_save);
2969 } else {
2970 goto prompt;
2972 $cred->accepted_failures($failures);
2973 $SVN::_Core::SVN_NO_ERROR;
2976 sub ssl_client_cert {
2977 my ($cred, $realm, $may_save, $pool) = @_;
2978 $may_save = undef if $_no_auth_cache;
2979 print STDERR "Client certificate filename: ";
2980 STDERR->flush;
2981 chomp(my $filename = <STDIN>);
2982 $cred->cert_file($filename);
2983 $cred->may_save($may_save);
2984 $SVN::_Core::SVN_NO_ERROR;
2987 sub ssl_client_cert_pw {
2988 my ($cred, $realm, $may_save, $pool) = @_;
2989 $may_save = undef if $_no_auth_cache;
2990 $cred->password(_read_password("Password: ", $realm));
2991 $cred->may_save($may_save);
2992 $SVN::_Core::SVN_NO_ERROR;
2995 sub username {
2996 my ($cred, $realm, $may_save, $pool) = @_;
2997 $may_save = undef if $_no_auth_cache;
2998 if (defined $realm && length $realm) {
2999 print STDERR "Authentication realm: $realm\n";
3001 my $username;
3002 if (defined $_username) {
3003 $username = $_username;
3004 } else {
3005 print STDERR "Username: ";
3006 STDERR->flush;
3007 chomp($username = <STDIN>);
3009 $cred->username($username);
3010 $cred->may_save($may_save);
3011 $SVN::_Core::SVN_NO_ERROR;
3014 sub _read_password {
3015 my ($prompt, $realm) = @_;
3016 print STDERR $prompt;
3017 STDERR->flush;
3018 require Term::ReadKey;
3019 Term::ReadKey::ReadMode('noecho');
3020 my $password = '';
3021 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3022 last if $key =~ /[\012\015]/; # \n\r
3023 $password .= $key;
3025 Term::ReadKey::ReadMode('restore');
3026 print STDERR "\n";
3027 STDERR->flush;
3028 $password;
3031 package SVN::Git::Fetcher;
3032 use vars qw/@ISA/;
3033 use strict;
3034 use warnings;
3035 use Carp qw/croak/;
3036 use File::Temp qw/tempfile/;
3037 use IO::File qw//;
3039 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3040 sub new {
3041 my ($class, $git_svn) = @_;
3042 my $self = SVN::Delta::Editor->new;
3043 bless $self, $class;
3044 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3045 $self->{empty} = {};
3046 $self->{dir_prop} = {};
3047 $self->{file_prop} = {};
3048 $self->{absent_dir} = {};
3049 $self->{absent_file} = {};
3050 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3051 $self;
3054 sub set_path_strip {
3055 my ($self, $path) = @_;
3056 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3059 sub open_root {
3060 { path => '' };
3063 sub open_directory {
3064 my ($self, $path, $pb, $rev) = @_;
3065 { path => $path };
3068 sub git_path {
3069 my ($self, $path) = @_;
3070 if ($self->{path_strip}) {
3071 $path =~ s!$self->{path_strip}!! or
3072 die "Failed to strip path '$path' ($self->{path_strip})\n";
3074 $path;
3077 sub delete_entry {
3078 my ($self, $path, $rev, $pb) = @_;
3080 my $gpath = $self->git_path($path);
3081 return undef if ($gpath eq '');
3083 # remove entire directories.
3084 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3085 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3086 -r --name-only -z/,
3087 $self->{c}, '--', $gpath);
3088 local $/ = "\0";
3089 while (<$ls>) {
3090 chomp;
3091 $self->{gii}->remove($_);
3092 print "\tD\t$_\n" unless $::_q;
3094 print "\tD\t$gpath/\n" unless $::_q;
3095 command_close_pipe($ls, $ctx);
3096 $self->{empty}->{$path} = 0
3097 } else {
3098 $self->{gii}->remove($gpath);
3099 print "\tD\t$gpath\n" unless $::_q;
3101 undef;
3104 sub open_file {
3105 my ($self, $path, $pb, $rev) = @_;
3106 my $gpath = $self->git_path($path);
3107 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3108 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3109 unless (defined $mode && defined $blob) {
3110 die "$path was not found in commit $self->{c} (r$rev)\n";
3112 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3113 pool => SVN::Pool->new, action => 'M' };
3116 sub add_file {
3117 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3118 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3119 delete $self->{empty}->{$dir};
3120 { path => $path, mode_a => 100644, mode_b => 100644,
3121 pool => SVN::Pool->new, action => 'A' };
3124 sub add_directory {
3125 my ($self, $path, $cp_path, $cp_rev) = @_;
3126 my $gpath = $self->git_path($path);
3127 if ($gpath eq '') {
3128 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3129 -r --name-only -z/,
3130 $self->{c});
3131 local $/ = "\0";
3132 while (<$ls>) {
3133 chomp;
3134 $self->{gii}->remove($_);
3135 print "\tD\t$_\n" unless $::_q;
3137 command_close_pipe($ls, $ctx);
3138 $self->{empty}->{$path} = 0;
3140 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3141 delete $self->{empty}->{$dir};
3142 $self->{empty}->{$path} = 1;
3143 { path => $path };
3146 sub change_dir_prop {
3147 my ($self, $db, $prop, $value) = @_;
3148 $self->{dir_prop}->{$db->{path}} ||= {};
3149 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3150 undef;
3153 sub absent_directory {
3154 my ($self, $path, $pb) = @_;
3155 $self->{absent_dir}->{$pb->{path}} ||= [];
3156 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3157 undef;
3160 sub absent_file {
3161 my ($self, $path, $pb) = @_;
3162 $self->{absent_file}->{$pb->{path}} ||= [];
3163 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3164 undef;
3167 sub change_file_prop {
3168 my ($self, $fb, $prop, $value) = @_;
3169 if ($prop eq 'svn:executable') {
3170 if ($fb->{mode_b} != 120000) {
3171 $fb->{mode_b} = defined $value ? 100755 : 100644;
3173 } elsif ($prop eq 'svn:special') {
3174 $fb->{mode_b} = defined $value ? 120000 : 100644;
3175 } else {
3176 $self->{file_prop}->{$fb->{path}} ||= {};
3177 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3179 undef;
3182 sub apply_textdelta {
3183 my ($self, $fb, $exp) = @_;
3184 my $fh = IO::File->new_tmpfile;
3185 $fh->autoflush(1);
3186 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3187 # (but $base does not,) so dup() it for reading in close_file
3188 open my $dup, '<&', $fh or croak $!;
3189 my $base = IO::File->new_tmpfile;
3190 $base->autoflush(1);
3191 if ($fb->{blob}) {
3192 print $base 'link ' if ($fb->{mode_a} == 120000);
3193 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3194 die "Failed to read object $fb->{blob}" unless $size;
3196 if (defined $exp) {
3197 seek $base, 0, 0 or croak $!;
3198 my $got = ::md5sum($base);
3199 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3200 "expected: $exp\n",
3201 " got: $got\n" if ($got ne $exp);
3204 seek $base, 0, 0 or croak $!;
3205 $fb->{fh} = $dup;
3206 $fb->{base} = $base;
3207 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3210 sub close_file {
3211 my ($self, $fb, $exp) = @_;
3212 my $hash;
3213 my $path = $self->git_path($fb->{path});
3214 if (my $fh = $fb->{fh}) {
3215 if (defined $exp) {
3216 seek($fh, 0, 0) or croak $!;
3217 my $got = ::md5sum($fh);
3218 if ($got ne $exp) {
3219 die "Checksum mismatch: $path\n",
3220 "expected: $exp\n got: $got\n";
3223 sysseek($fh, 0, 0) or croak $!;
3224 if ($fb->{mode_b} == 120000) {
3225 eval {
3226 sysread($fh, my $buf, 5) == 5 or croak $!;
3227 $buf eq 'link ' or die "$path has mode 120000",
3228 " but is not a link";
3230 if ($@) {
3231 warn "$@\n";
3232 sysseek($fh, 0, 0) or croak $!;
3236 my ($tmp_fh, $tmp_filename) = File::Temp::tempfile(UNLINK => 1);
3237 my $result;
3238 while ($result = sysread($fh, my $string, 1024)) {
3239 syswrite($tmp_fh, $string, $result);
3241 defined $result or croak $!;
3242 close $tmp_fh or croak $!;
3244 close $fh or croak $!;
3246 $hash = $::_repository->hash_and_insert_object($tmp_filename);
3247 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3248 close $fb->{base} or croak $!;
3249 } else {
3250 $hash = $fb->{blob} or die "no blob information\n";
3252 $fb->{pool}->clear;
3253 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3254 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3255 undef;
3258 sub abort_edit {
3259 my $self = shift;
3260 $self->{nr} = $self->{gii}->{nr};
3261 delete $self->{gii};
3262 $self->SUPER::abort_edit(@_);
3265 sub close_edit {
3266 my $self = shift;
3267 $self->{git_commit_ok} = 1;
3268 $self->{nr} = $self->{gii}->{nr};
3269 delete $self->{gii};
3270 $self->SUPER::close_edit(@_);
3273 package SVN::Git::Editor;
3274 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3275 use strict;
3276 use warnings;
3277 use Carp qw/croak/;
3278 use IO::File;
3280 sub new {
3281 my ($class, $opts) = @_;
3282 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3283 die "$_ required!\n" unless (defined $opts->{$_});
3286 my $pool = SVN::Pool->new;
3287 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3288 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3289 $opts->{r}, $mods);
3291 # $opts->{ra} functions should not be used after this:
3292 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3293 $opts->{editor_cb}, $pool);
3294 my $self = SVN::Delta::Editor->new(@ce, $pool);
3295 bless $self, $class;
3296 foreach (qw/svn_path r tree_a tree_b/) {
3297 $self->{$_} = $opts->{$_};
3299 $self->{url} = $opts->{ra}->{url};
3300 $self->{mods} = $mods;
3301 $self->{types} = $types;
3302 $self->{pool} = $pool;
3303 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3304 $self->{rm} = { };
3305 $self->{path_prefix} = length $self->{svn_path} ?
3306 "$self->{svn_path}/" : '';
3307 return $self;
3310 sub generate_diff {
3311 my ($tree_a, $tree_b) = @_;
3312 my @diff_tree = qw(diff-tree -z -r);
3313 if ($_cp_similarity) {
3314 push @diff_tree, "-C$_cp_similarity";
3315 } else {
3316 push @diff_tree, '-C';
3318 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3319 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3320 push @diff_tree, $tree_a, $tree_b;
3321 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3322 local $/ = "\0";
3323 my $state = 'meta';
3324 my @mods;
3325 while (<$diff_fh>) {
3326 chomp $_; # this gets rid of the trailing "\0"
3327 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3328 $::sha1\s($::sha1)\s
3329 ([MTCRAD])\d*$/xo) {
3330 push @mods, { mode_a => $1, mode_b => $2,
3331 sha1_b => $3, chg => $4 };
3332 if ($4 =~ /^(?:C|R)$/) {
3333 $state = 'file_a';
3334 } else {
3335 $state = 'file_b';
3337 } elsif ($state eq 'file_a') {
3338 my $x = $mods[$#mods] or croak "Empty array\n";
3339 if ($x->{chg} !~ /^(?:C|R)$/) {
3340 croak "Error parsing $_, $x->{chg}\n";
3342 $x->{file_a} = $_;
3343 $state = 'file_b';
3344 } elsif ($state eq 'file_b') {
3345 my $x = $mods[$#mods] or croak "Empty array\n";
3346 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3347 croak "Error parsing $_, $x->{chg}\n";
3349 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3350 croak "Error parsing $_, $x->{chg}\n";
3352 $x->{file_b} = $_;
3353 $state = 'meta';
3354 } else {
3355 croak "Error parsing $_\n";
3358 command_close_pipe($diff_fh, $ctx);
3359 \@mods;
3362 sub check_diff_paths {
3363 my ($ra, $pfx, $rev, $mods) = @_;
3364 my %types;
3365 $pfx .= '/' if length $pfx;
3367 sub type_diff_paths {
3368 my ($ra, $types, $path, $rev) = @_;
3369 my @p = split m#/+#, $path;
3370 my $c = shift @p;
3371 unless (defined $types->{$c}) {
3372 $types->{$c} = $ra->check_path($c, $rev);
3374 while (@p) {
3375 $c .= '/' . shift @p;
3376 next if defined $types->{$c};
3377 $types->{$c} = $ra->check_path($c, $rev);
3381 foreach my $m (@$mods) {
3382 foreach my $f (qw/file_a file_b/) {
3383 next unless defined $m->{$f};
3384 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3385 if (length $pfx.$dir && ! defined $types{$dir}) {
3386 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3390 \%types;
3393 sub split_path {
3394 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3397 sub repo_path {
3398 my ($self, $path) = @_;
3399 $self->{path_prefix}.(defined $path ? $path : '');
3402 sub url_path {
3403 my ($self, $path) = @_;
3404 if ($self->{url} =~ m#^https?://#) {
3405 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3407 $self->{url} . '/' . $self->repo_path($path);
3410 sub rmdirs {
3411 my ($self) = @_;
3412 my $rm = $self->{rm};
3413 delete $rm->{''}; # we never delete the url we're tracking
3414 return unless %$rm;
3416 foreach (keys %$rm) {
3417 my @d = split m#/#, $_;
3418 my $c = shift @d;
3419 $rm->{$c} = 1;
3420 while (@d) {
3421 $c .= '/' . shift @d;
3422 $rm->{$c} = 1;
3425 delete $rm->{$self->{svn_path}};
3426 delete $rm->{''}; # we never delete the url we're tracking
3427 return unless %$rm;
3429 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3430 $self->{tree_b});
3431 local $/ = "\0";
3432 while (<$fh>) {
3433 chomp;
3434 my @dn = split m#/#, $_;
3435 while (pop @dn) {
3436 delete $rm->{join '/', @dn};
3438 unless (%$rm) {
3439 close $fh;
3440 return;
3443 command_close_pipe($fh, $ctx);
3445 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3446 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3447 $self->close_directory($bat->{$d}, $p);
3448 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3449 print "\tD+\t$d/\n" unless $::_q;
3450 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3451 delete $bat->{$d};
3455 sub open_or_add_dir {
3456 my ($self, $full_path, $baton) = @_;
3457 my $t = $self->{types}->{$full_path};
3458 if (!defined $t) {
3459 die "$full_path not known in r$self->{r} or we have a bug!\n";
3462 no warnings 'once';
3463 # SVN::Node::none and SVN::Node::file are used only once,
3464 # so we're shutting up Perl's warnings about them.
3465 if ($t == $SVN::Node::none) {
3466 return $self->add_directory($full_path, $baton,
3467 undef, -1, $self->{pool});
3468 } elsif ($t == $SVN::Node::dir) {
3469 return $self->open_directory($full_path, $baton,
3470 $self->{r}, $self->{pool});
3471 } # no warnings 'once'
3472 print STDERR "$full_path already exists in repository at ",
3473 "r$self->{r} and it is not a directory (",
3474 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3475 } # no warnings 'once'
3476 exit 1;
3479 sub ensure_path {
3480 my ($self, $path) = @_;
3481 my $bat = $self->{bat};
3482 my $repo_path = $self->repo_path($path);
3483 return $bat->{''} unless (length $repo_path);
3484 my @p = split m#/+#, $repo_path;
3485 my $c = shift @p;
3486 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3487 while (@p) {
3488 my $c0 = $c;
3489 $c .= '/' . shift @p;
3490 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3492 return $bat->{$c};
3495 sub A {
3496 my ($self, $m) = @_;
3497 my ($dir, $file) = split_path($m->{file_b});
3498 my $pbat = $self->ensure_path($dir);
3499 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3500 undef, -1);
3501 print "\tA\t$m->{file_b}\n" unless $::_q;
3502 $self->chg_file($fbat, $m);
3503 $self->close_file($fbat,undef,$self->{pool});
3506 sub C {
3507 my ($self, $m) = @_;
3508 my ($dir, $file) = split_path($m->{file_b});
3509 my $pbat = $self->ensure_path($dir);
3510 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3511 $self->url_path($m->{file_a}), $self->{r});
3512 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3513 $self->chg_file($fbat, $m);
3514 $self->close_file($fbat,undef,$self->{pool});
3517 sub delete_entry {
3518 my ($self, $path, $pbat) = @_;
3519 my $rpath = $self->repo_path($path);
3520 my ($dir, $file) = split_path($rpath);
3521 $self->{rm}->{$dir} = 1;
3522 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3525 sub R {
3526 my ($self, $m) = @_;
3527 my ($dir, $file) = split_path($m->{file_b});
3528 my $pbat = $self->ensure_path($dir);
3529 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3530 $self->url_path($m->{file_a}), $self->{r});
3531 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3532 $self->chg_file($fbat, $m);
3533 $self->close_file($fbat,undef,$self->{pool});
3535 ($dir, $file) = split_path($m->{file_a});
3536 $pbat = $self->ensure_path($dir);
3537 $self->delete_entry($m->{file_a}, $pbat);
3540 sub M {
3541 my ($self, $m) = @_;
3542 my ($dir, $file) = split_path($m->{file_b});
3543 my $pbat = $self->ensure_path($dir);
3544 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3545 $pbat,$self->{r},$self->{pool});
3546 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3547 $self->chg_file($fbat, $m);
3548 $self->close_file($fbat,undef,$self->{pool});
3551 sub T { shift->M(@_) }
3553 sub change_file_prop {
3554 my ($self, $fbat, $pname, $pval) = @_;
3555 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3558 sub chg_file {
3559 my ($self, $fbat, $m) = @_;
3560 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3561 $self->change_file_prop($fbat,'svn:executable','*');
3562 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3563 $self->change_file_prop($fbat,'svn:executable',undef);
3565 my $fh = IO::File->new_tmpfile or croak $!;
3566 if ($m->{mode_b} =~ /^120/) {
3567 print $fh 'link ' or croak $!;
3568 $self->change_file_prop($fbat,'svn:special','*');
3569 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3570 $self->change_file_prop($fbat,'svn:special',undef);
3572 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
3573 croak "Failed to read object $m->{sha1_b}" unless $size;
3574 $fh->flush == 0 or croak $!;
3575 seek $fh, 0, 0 or croak $!;
3577 my $exp = ::md5sum($fh);
3578 seek $fh, 0, 0 or croak $!;
3580 my $pool = SVN::Pool->new;
3581 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3582 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3583 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3584 $pool->clear;
3586 close $fh or croak $!;
3589 sub D {
3590 my ($self, $m) = @_;
3591 my ($dir, $file) = split_path($m->{file_b});
3592 my $pbat = $self->ensure_path($dir);
3593 print "\tD\t$m->{file_b}\n" unless $::_q;
3594 $self->delete_entry($m->{file_b}, $pbat);
3597 sub close_edit {
3598 my ($self) = @_;
3599 my ($p,$bat) = ($self->{pool}, $self->{bat});
3600 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3601 next if $_ eq '';
3602 $self->close_directory($bat->{$_}, $p);
3604 $self->close_directory($bat->{''}, $p);
3605 $self->SUPER::close_edit($p);
3606 $p->clear;
3609 sub abort_edit {
3610 my ($self) = @_;
3611 $self->SUPER::abort_edit($self->{pool});
3614 sub DESTROY {
3615 my $self = shift;
3616 $self->SUPER::DESTROY(@_);
3617 $self->{pool}->clear;
3620 # this drives the editor
3621 sub apply_diff {
3622 my ($self) = @_;
3623 my $mods = $self->{mods};
3624 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3625 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3626 my $f = $m->{chg};
3627 if (defined $o{$f}) {
3628 $self->$f($m);
3629 } else {
3630 fatal("Invalid change type: $f");
3633 $self->rmdirs if $_rmdir;
3634 if (@$mods == 0) {
3635 $self->abort_edit;
3636 } else {
3637 $self->close_edit;
3639 return scalar @$mods;
3642 package Git::SVN::Ra;
3643 use vars qw/@ISA $config_dir $_log_window_size/;
3644 use strict;
3645 use warnings;
3646 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3648 BEGIN {
3649 # enforce temporary pool usage for some simple functions
3650 no strict 'refs';
3651 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3652 my $SUPER = "SUPER::$f";
3653 *$f = sub {
3654 my $self = shift;
3655 my $pool = SVN::Pool->new;
3656 my @ret = $self->$SUPER(@_,$pool);
3657 $pool->clear;
3658 wantarray ? @ret : $ret[0];
3663 sub _auth_providers () {
3665 SVN::Client::get_simple_provider(),
3666 SVN::Client::get_ssl_server_trust_file_provider(),
3667 SVN::Client::get_simple_prompt_provider(
3668 \&Git::SVN::Prompt::simple, 2),
3669 SVN::Client::get_ssl_client_cert_file_provider(),
3670 SVN::Client::get_ssl_client_cert_prompt_provider(
3671 \&Git::SVN::Prompt::ssl_client_cert, 2),
3672 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3673 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3674 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3675 SVN::Client::get_username_provider(),
3676 SVN::Client::get_ssl_server_trust_prompt_provider(
3677 \&Git::SVN::Prompt::ssl_server_trust),
3678 SVN::Client::get_username_prompt_provider(
3679 \&Git::SVN::Prompt::username, 2)
3683 sub escape_uri_only {
3684 my ($uri) = @_;
3685 my @tmp;
3686 foreach (split m{/}, $uri) {
3687 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3688 push @tmp, $_;
3690 join('/', @tmp);
3693 sub escape_url {
3694 my ($url) = @_;
3695 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3696 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3697 $url = "$scheme://$domain$uri";
3699 $url;
3702 sub new {
3703 my ($class, $url) = @_;
3704 $url =~ s!/+$!!;
3705 return $RA if ($RA && $RA->{url} eq $url);
3707 SVN::_Core::svn_config_ensure($config_dir, undef);
3708 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3709 my $config = SVN::Core::config_get_config($config_dir);
3710 $RA = undef;
3711 my $dont_store_passwords = 1;
3712 my $conf_t = ${$config}{'config'};
3714 no warnings 'once';
3715 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3716 # produces warnings that variables are used only once.
3717 # I had not found the better way to shut them up, so
3718 # the warnings of type 'once' are disabled in this block.
3719 if (SVN::_Core::svn_config_get_bool($conf_t,
3720 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3721 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3722 1) == 0) {
3723 SVN::_Core::svn_auth_set_parameter($baton,
3724 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3725 bless (\$dont_store_passwords, "_p_void"));
3727 if (SVN::_Core::svn_config_get_bool($conf_t,
3728 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3729 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3730 1) == 0) {
3731 $Git::SVN::Prompt::_no_auth_cache = 1;
3733 } # no warnings 'once'
3734 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3735 config => $config,
3736 pool => SVN::Pool->new,
3737 auth_provider_callbacks => $callbacks);
3738 $self->{url} = $url;
3739 $self->{svn_path} = $url;
3740 $self->{repos_root} = $self->get_repos_root;
3741 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3742 $self->{cache} = { check_path => { r => 0, data => {} },
3743 get_dir => { r => 0, data => {} } };
3744 $RA = bless $self, $class;
3747 sub check_path {
3748 my ($self, $path, $r) = @_;
3749 my $cache = $self->{cache}->{check_path};
3750 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3751 return $cache->{data}->{$path};
3753 my $pool = SVN::Pool->new;
3754 my $t = $self->SUPER::check_path($path, $r, $pool);
3755 $pool->clear;
3756 if ($r != $cache->{r}) {
3757 %{$cache->{data}} = ();
3758 $cache->{r} = $r;
3760 $cache->{data}->{$path} = $t;
3763 sub get_dir {
3764 my ($self, $dir, $r) = @_;
3765 my $cache = $self->{cache}->{get_dir};
3766 if ($r == $cache->{r}) {
3767 if (my $x = $cache->{data}->{$dir}) {
3768 return wantarray ? @$x : $x->[0];
3771 my $pool = SVN::Pool->new;
3772 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3773 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3774 $pool->clear;
3775 if ($r != $cache->{r}) {
3776 %{$cache->{data}} = ();
3777 $cache->{r} = $r;
3779 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3780 wantarray ? (\%dirents, $r, $props) : \%dirents;
3783 sub DESTROY {
3784 # do not call the real DESTROY since we store ourselves in $RA
3787 sub get_log {
3788 my ($self, @args) = @_;
3789 my $pool = SVN::Pool->new;
3790 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3791 my $ret = $self->SUPER::get_log(@args, $pool);
3792 $pool->clear;
3793 $ret;
3796 sub trees_match {
3797 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3798 my $ctx = SVN::Client->new(auth => _auth_providers);
3799 my $out = IO::File->new_tmpfile;
3801 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3802 # $ctx->diff(), so we'll create a default one
3803 my $pool = SVN::Pool->new_default_sub;
3805 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3806 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3807 $out->flush;
3808 my $ret = (($out->stat)[7] == 0);
3809 close $out or croak $!;
3811 $ret;
3814 sub get_commit_editor {
3815 my ($self, $log, $cb, $pool) = @_;
3816 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3817 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3820 sub gs_do_update {
3821 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3822 my $new = ($rev_a == $rev_b);
3823 my $path = $gs->{path};
3825 if ($new && -e $gs->{index}) {
3826 unlink $gs->{index} or die
3827 "Couldn't unlink index: $gs->{index}: $!\n";
3829 my $pool = SVN::Pool->new;
3830 $editor->set_path_strip($path);
3831 my (@pc) = split m#/#, $path;
3832 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3833 1, $editor, $pool);
3834 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3836 # Since we can't rely on svn_ra_reparent being available, we'll
3837 # just have to do some magic with set_path to make it so
3838 # we only want a partial path.
3839 my $sp = '';
3840 my $final = join('/', @pc);
3841 while (@pc) {
3842 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3843 $sp .= '/' if length $sp;
3844 $sp .= shift @pc;
3846 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3848 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3850 $reporter->finish_report($pool);
3851 $pool->clear;
3852 $editor->{git_commit_ok};
3855 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3856 # svn_ra_reparent didn't work before 1.4)
3857 sub gs_do_switch {
3858 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3859 my $path = $gs->{path};
3860 my $pool = SVN::Pool->new;
3862 my $full_url = $self->{url};
3863 my $old_url = $full_url;
3864 $full_url .= '/' . escape_uri_only($path) if length $path;
3865 my ($ra, $reparented);
3866 if ($old_url ne $full_url) {
3867 if ($old_url !~ m#^svn(\+ssh)?://#) {
3868 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3869 $pool);
3870 $self->{url} = $full_url;
3871 $reparented = 1;
3872 } else {
3873 $_[0] = undef;
3874 $self = undef;
3875 $RA = undef;
3876 $ra = Git::SVN::Ra->new($full_url);
3877 $ra_invalid = 1;
3880 $ra ||= $self;
3881 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3882 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3883 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3884 $reporter->finish_report($pool);
3886 if ($reparented) {
3887 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3888 $self->{url} = $old_url;
3891 $pool->clear;
3892 $editor->{git_commit_ok};
3895 sub longest_common_path {
3896 my ($gsv, $globs) = @_;
3897 my %common;
3898 my $common_max = scalar @$gsv;
3900 foreach my $gs (@$gsv) {
3901 my @tmp = split m#/#, $gs->{path};
3902 my $p = '';
3903 foreach (@tmp) {
3904 $p .= length($p) ? "/$_" : $_;
3905 $common{$p} ||= 0;
3906 $common{$p}++;
3909 $globs ||= [];
3910 $common_max += scalar @$globs;
3911 foreach my $glob (@$globs) {
3912 my @tmp = split m#/#, $glob->{path}->{left};
3913 my $p = '';
3914 foreach (@tmp) {
3915 $p .= length($p) ? "/$_" : $_;
3916 $common{$p} ||= 0;
3917 $common{$p}++;
3921 my $longest_path = '';
3922 foreach (sort {length $b <=> length $a} keys %common) {
3923 if ($common{$_} == $common_max) {
3924 $longest_path = $_;
3925 last;
3928 $longest_path;
3931 sub gs_fetch_loop_common {
3932 my ($self, $base, $head, $gsv, $globs) = @_;
3933 return if ($base > $head);
3934 my $inc = $_log_window_size;
3935 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3936 my $longest_path = longest_common_path($gsv, $globs);
3937 my $ra_url = $self->{url};
3938 while (1) {
3939 my %revs;
3940 my $err;
3941 my $err_handler = $SVN::Error::handler;
3942 $SVN::Error::handler = sub {
3943 ($err) = @_;
3944 skip_unknown_revs($err);
3946 sub _cb {
3947 my ($paths, $r, $author, $date, $log) = @_;
3948 [ dup_changed_paths($paths),
3949 { author => $author, date => $date, log => $log } ];
3951 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3952 sub { $revs{$_[1]} = _cb(@_) });
3953 if ($err && $max >= $head) {
3954 print STDERR "Path '$longest_path' ",
3955 "was probably deleted:\n",
3956 $err->expanded_message,
3957 "\nWill attempt to follow ",
3958 "revisions r$min .. r$max ",
3959 "committed before the deletion\n";
3960 my $hi = $max;
3961 while (--$hi >= $min) {
3962 my $ok;
3963 $self->get_log([$longest_path], $min, $hi,
3964 0, 1, 1, sub {
3965 $ok ||= $_[1];
3966 $revs{$_[1]} = _cb(@_) });
3967 if ($ok) {
3968 print STDERR "r$min .. r$ok OK\n";
3969 last;
3973 $SVN::Error::handler = $err_handler;
3975 my %exists = map { $_->{path} => $_ } @$gsv;
3976 foreach my $r (sort {$a <=> $b} keys %revs) {
3977 my ($paths, $logged) = @{$revs{$r}};
3979 foreach my $gs ($self->match_globs(\%exists, $paths,
3980 $globs, $r)) {
3981 if ($gs->rev_map_max >= $r) {
3982 next;
3984 next unless $gs->match_paths($paths, $r);
3985 $gs->{logged_rev_props} = $logged;
3986 if (my $last_commit = $gs->last_commit) {
3987 $gs->assert_index_clean($last_commit);
3989 my $log_entry = $gs->do_fetch($paths, $r);
3990 if ($log_entry) {
3991 $gs->do_git_commit($log_entry);
3993 $INDEX_FILES{$gs->{index}} = 1;
3995 foreach my $g (@$globs) {
3996 my $k = "svn-remote.$g->{remote}." .
3997 "$g->{t}-maxRev";
3998 Git::SVN::tmp_config($k, $r);
4000 if ($ra_invalid) {
4001 $_[0] = undef;
4002 $self = undef;
4003 $RA = undef;
4004 $self = Git::SVN::Ra->new($ra_url);
4005 $ra_invalid = undef;
4008 # pre-fill the .rev_db since it'll eventually get filled in
4009 # with '0' x40 if something new gets committed
4010 foreach my $gs (@$gsv) {
4011 next if $gs->rev_map_max >= $max;
4012 next if defined $gs->rev_map_get($max);
4013 $gs->rev_map_set($max, 0 x40);
4015 foreach my $g (@$globs) {
4016 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4017 Git::SVN::tmp_config($k, $max);
4019 last if $max >= $head;
4020 $min = $max + 1;
4021 $max += $inc;
4022 $max = $head if ($max > $head);
4024 Git::SVN::gc();
4027 sub match_globs {
4028 my ($self, $exists, $paths, $globs, $r) = @_;
4030 sub get_dir_check {
4031 my ($self, $exists, $g, $r) = @_;
4032 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
4033 return unless scalar @x == 3;
4034 my $dirents = $x[0];
4035 foreach my $de (keys %$dirents) {
4036 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4037 my $p = $g->{path}->full_path($de);
4038 next if $exists->{$p};
4039 next if (length $g->{path}->{right} &&
4040 ($self->check_path($p, $r) !=
4041 $SVN::Node::dir));
4042 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4043 $g->{ref}->full_path($de), 1);
4046 foreach my $g (@$globs) {
4047 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4048 if ($path->{action} =~ /^[AR]$/) {
4049 get_dir_check($self, $exists, $g, $r);
4052 foreach (keys %$paths) {
4053 if (/$g->{path}->{left_regex}/ &&
4054 !/$g->{path}->{regex}/) {
4055 next if $paths->{$_}->{action} !~ /^[AR]$/;
4056 get_dir_check($self, $exists, $g, $r);
4058 next unless /$g->{path}->{regex}/;
4059 my $p = $1;
4060 my $pathname = $g->{path}->full_path($p);
4061 next if $exists->{$pathname};
4062 next if ($self->check_path($pathname, $r) !=
4063 $SVN::Node::dir);
4064 $exists->{$pathname} = Git::SVN->init(
4065 $self->{url}, $pathname, undef,
4066 $g->{ref}->full_path($p), 1);
4068 my $c = '';
4069 foreach (split m#/#, $g->{path}->{left}) {
4070 $c .= "/$_";
4071 next unless ($paths->{$c} &&
4072 ($paths->{$c}->{action} =~ /^[AR]$/));
4073 get_dir_check($self, $exists, $g, $r);
4076 values %$exists;
4079 sub minimize_url {
4080 my ($self) = @_;
4081 return $self->{url} if ($self->{url} eq $self->{repos_root});
4082 my $url = $self->{repos_root};
4083 my @components = split(m!/!, $self->{svn_path});
4084 my $c = '';
4085 do {
4086 $url .= "/$c" if length $c;
4087 eval { (ref $self)->new($url)->get_latest_revnum };
4088 } while ($@ && ($c = shift @components));
4089 $url;
4092 sub can_do_switch {
4093 my $self = shift;
4094 unless (defined $can_do_switch) {
4095 my $pool = SVN::Pool->new;
4096 my $rep = eval {
4097 $self->do_switch(1, '', 0, $self->{url},
4098 SVN::Delta::Editor->new, $pool);
4100 if ($@) {
4101 $can_do_switch = 0;
4102 } else {
4103 $rep->abort_report($pool);
4104 $can_do_switch = 1;
4106 $pool->clear;
4108 $can_do_switch;
4111 sub skip_unknown_revs {
4112 my ($err) = @_;
4113 my $errno = $err->apr_err();
4114 # Maybe the branch we're tracking didn't
4115 # exist when the repo started, so it's
4116 # not an error if it doesn't, just continue
4118 # Wonderfully consistent library, eh?
4119 # 160013 - svn:// and file://
4120 # 175002 - http(s)://
4121 # 175007 - http(s):// (this repo required authorization, too...)
4122 # More codes may be discovered later...
4123 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4124 my $err_key = $err->expanded_message;
4125 # revision numbers change every time, filter them out
4126 $err_key =~ s/\d+/\0/g;
4127 $err_key = "$errno\0$err_key";
4128 unless ($ignored_err{$err_key}) {
4129 warn "W: Ignoring error from SVN, path probably ",
4130 "does not exist: ($errno): ",
4131 $err->expanded_message,"\n";
4132 warn "W: Do not be alarmed at the above message ",
4133 "git-svn is just searching aggressively for ",
4134 "old history.\n",
4135 "This may take a while on large repositories\n";
4136 $ignored_err{$err_key} = 1;
4138 return;
4140 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4143 # svn_log_changed_path_t objects passed to get_log are likely to be
4144 # overwritten even if only the refs are copied to an external variable,
4145 # so we should dup the structures in their entirety. Using an externally
4146 # passed pool (instead of our temporary and quickly cleared pool in
4147 # Git::SVN::Ra) does not help matters at all...
4148 sub dup_changed_paths {
4149 my ($paths) = @_;
4150 return undef unless $paths;
4151 my %ret;
4152 foreach my $p (keys %$paths) {
4153 my $i = $paths->{$p};
4154 my %s = map { $_ => $i->$_ }
4155 qw/copyfrom_path copyfrom_rev action/;
4156 $ret{$p} = \%s;
4158 \%ret;
4161 package Git::SVN::Log;
4162 use strict;
4163 use warnings;
4164 use POSIX qw/strftime/;
4165 use constant commit_log_separator => ('-' x 72) . "\n";
4166 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4167 %rusers $show_commit $incremental/;
4168 my $l_fmt;
4170 sub cmt_showable {
4171 my ($c) = @_;
4172 return 1 if defined $c->{r};
4174 # big commit message got truncated by the 16k pretty buffer in rev-list
4175 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4176 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4177 @{$c->{l}} = ();
4178 my @log = command(qw/cat-file commit/, $c->{c});
4180 # shift off the headers
4181 shift @log while ($log[0] ne '');
4182 shift @log;
4184 # TODO: make $c->{l} not have a trailing newline in the future
4185 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4187 (undef, $c->{r}, undef) = ::extract_metadata(
4188 (grep(/^git-svn-id: /, @log))[-1]);
4190 return defined $c->{r};
4193 sub log_use_color {
4194 return $color || Git->repository->get_colorbool('color.diff');
4197 sub git_svn_log_cmd {
4198 my ($r_min, $r_max, @args) = @_;
4199 my $head = 'HEAD';
4200 my (@files, @log_opts);
4201 foreach my $x (@args) {
4202 if ($x eq '--' || @files) {
4203 push @files, $x;
4204 } else {
4205 if (::verify_ref("$x^0")) {
4206 $head = $x;
4207 } else {
4208 push @log_opts, $x;
4213 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4214 $gs ||= Git::SVN->_new;
4215 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4216 $gs->refname);
4217 push @cmd, '-r' unless $non_recursive;
4218 push @cmd, qw/--raw --name-status/ if $verbose;
4219 push @cmd, '--color' if log_use_color();
4220 push @cmd, @log_opts;
4221 if (defined $r_max && $r_max == $r_min) {
4222 push @cmd, '--max-count=1';
4223 if (my $c = $gs->rev_map_get($r_max)) {
4224 push @cmd, $c;
4226 } elsif (defined $r_max) {
4227 if ($r_max < $r_min) {
4228 ($r_min, $r_max) = ($r_max, $r_min);
4230 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4231 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4232 # If there are no commits in the range, both $c_max and $c_min
4233 # will be undefined. If there is at least 1 commit in the
4234 # range, both will be defined.
4235 return () if !defined $c_min || !defined $c_max;
4236 if ($c_min eq $c_max) {
4237 push @cmd, '--max-count=1', $c_min;
4238 } else {
4239 push @cmd, '--boundary', "$c_min..$c_max";
4242 return (@cmd, @files);
4245 # adapted from pager.c
4246 sub config_pager {
4247 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4248 if (!defined $pager) {
4249 $pager = 'less';
4250 } elsif (length $pager == 0 || $pager eq 'cat') {
4251 $pager = undef;
4253 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4256 sub run_pager {
4257 return unless -t *STDOUT && defined $pager;
4258 pipe my $rfd, my $wfd or return;
4259 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4260 if (!$pid) {
4261 open STDOUT, '>&', $wfd or
4262 ::fatal "Can't redirect to stdout: $!";
4263 return;
4265 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4266 $ENV{LESS} ||= 'FRSX';
4267 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4270 sub format_svn_date {
4271 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4274 sub parse_git_date {
4275 my ($t, $tz) = @_;
4276 # Date::Parse isn't in the standard Perl distro :(
4277 if ($tz =~ s/^\+//) {
4278 $t += tz_to_s_offset($tz);
4279 } elsif ($tz =~ s/^\-//) {
4280 $t -= tz_to_s_offset($tz);
4282 return $t;
4285 sub set_local_timezone {
4286 if (defined $TZ) {
4287 $ENV{TZ} = $TZ;
4288 } else {
4289 delete $ENV{TZ};
4293 sub tz_to_s_offset {
4294 my ($tz) = @_;
4295 $tz =~ s/(\d\d)$//;
4296 return ($1 * 60) + ($tz * 3600);
4299 sub get_author_info {
4300 my ($dest, $author, $t, $tz) = @_;
4301 $author =~ s/(?:^\s*|\s*$)//g;
4302 $dest->{a_raw} = $author;
4303 my $au;
4304 if ($::_authors) {
4305 $au = $rusers{$author} || undef;
4307 if (!$au) {
4308 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4310 $dest->{t} = $t;
4311 $dest->{tz} = $tz;
4312 $dest->{a} = $au;
4313 $dest->{t_utc} = parse_git_date($t, $tz);
4316 sub process_commit {
4317 my ($c, $r_min, $r_max, $defer) = @_;
4318 if (defined $r_min && defined $r_max) {
4319 if ($r_min == $c->{r} && $r_min == $r_max) {
4320 show_commit($c);
4321 return 0;
4323 return 1 if $r_min == $r_max;
4324 if ($r_min < $r_max) {
4325 # we need to reverse the print order
4326 return 0 if (defined $limit && --$limit < 0);
4327 push @$defer, $c;
4328 return 1;
4330 if ($r_min != $r_max) {
4331 return 1 if ($r_min < $c->{r});
4332 return 1 if ($r_max > $c->{r});
4335 return 0 if (defined $limit && --$limit < 0);
4336 show_commit($c);
4337 return 1;
4340 sub show_commit {
4341 my $c = shift;
4342 if ($oneline) {
4343 my $x = "\n";
4344 if (my $l = $c->{l}) {
4345 while ($l->[0] =~ /^\s*$/) { shift @$l }
4346 $x = $l->[0];
4348 $l_fmt ||= 'A' . length($c->{r});
4349 print 'r',pack($l_fmt, $c->{r}),' | ';
4350 print "$c->{c} | " if $show_commit;
4351 print $x;
4352 } else {
4353 show_commit_normal($c);
4357 sub show_commit_changed_paths {
4358 my ($c) = @_;
4359 return unless $c->{changed};
4360 print "Changed paths:\n", @{$c->{changed}};
4363 sub show_commit_normal {
4364 my ($c) = @_;
4365 print commit_log_separator, "r$c->{r} | ";
4366 print "$c->{c} | " if $show_commit;
4367 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4368 my $nr_line = 0;
4370 if (my $l = $c->{l}) {
4371 while ($l->[$#$l] eq "\n" && $#$l > 0
4372 && $l->[($#$l - 1)] eq "\n") {
4373 pop @$l;
4375 $nr_line = scalar @$l;
4376 if (!$nr_line) {
4377 print "1 line\n\n\n";
4378 } else {
4379 if ($nr_line == 1) {
4380 $nr_line = '1 line';
4381 } else {
4382 $nr_line .= ' lines';
4384 print $nr_line, "\n";
4385 show_commit_changed_paths($c);
4386 print "\n";
4387 print $_ foreach @$l;
4389 } else {
4390 print "1 line\n";
4391 show_commit_changed_paths($c);
4392 print "\n";
4395 foreach my $x (qw/raw stat diff/) {
4396 if ($c->{$x}) {
4397 print "\n";
4398 print $_ foreach @{$c->{$x}}
4403 sub cmd_show_log {
4404 my (@args) = @_;
4405 my ($r_min, $r_max);
4406 my $r_last = -1; # prevent dupes
4407 set_local_timezone();
4408 if (defined $::_revision) {
4409 if ($::_revision =~ /^(\d+):(\d+)$/) {
4410 ($r_min, $r_max) = ($1, $2);
4411 } elsif ($::_revision =~ /^\d+$/) {
4412 $r_min = $r_max = $::_revision;
4413 } else {
4414 ::fatal "-r$::_revision is not supported, use ",
4415 "standard 'git log' arguments instead";
4419 config_pager();
4420 @args = git_svn_log_cmd($r_min, $r_max, @args);
4421 if (!@args) {
4422 print commit_log_separator unless $incremental || $oneline;
4423 return;
4425 my $log = command_output_pipe(@args);
4426 run_pager();
4427 my (@k, $c, $d, $stat);
4428 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4429 while (<$log>) {
4430 if (/^${esc_color}commit -?($::sha1_short)/o) {
4431 my $cmt = $1;
4432 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4433 $r_last = $c->{r};
4434 process_commit($c, $r_min, $r_max, \@k) or
4435 goto out;
4437 $d = undef;
4438 $c = { c => $cmt };
4439 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4440 get_author_info($c, $1, $2, $3);
4441 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4442 # ignore
4443 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4444 push @{$c->{raw}}, $_;
4445 } elsif (/^${esc_color}[ACRMDT]\t/) {
4446 # we could add $SVN->{svn_path} here, but that requires
4447 # remote access at the moment (repo_path_split)...
4448 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4449 push @{$c->{changed}}, $_;
4450 } elsif (/^${esc_color}diff /o) {
4451 $d = 1;
4452 push @{$c->{diff}}, $_;
4453 } elsif ($d) {
4454 push @{$c->{diff}}, $_;
4455 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4456 $esc_color*[\+\-]*$esc_color$/x) {
4457 $stat = 1;
4458 push @{$c->{stat}}, $_;
4459 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4460 push @{$c->{stat}}, $_;
4461 $stat = undef;
4462 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4463 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4464 } elsif (s/^${esc_color} //o) {
4465 push @{$c->{l}}, $_;
4468 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4469 $r_last = $c->{r};
4470 process_commit($c, $r_min, $r_max, \@k);
4472 if (@k) {
4473 ($r_min, $r_max) = ($r_max, $r_min);
4474 process_commit($_, $r_min, $r_max) foreach reverse @k;
4476 out:
4477 close $log;
4478 print commit_log_separator unless $incremental || $oneline;
4481 sub cmd_blame {
4482 my $path = pop;
4484 config_pager();
4485 run_pager();
4487 my ($fh, $ctx, $rev);
4489 if ($_git_format) {
4490 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4491 while (my $line = <$fh>) {
4492 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4493 # Uncommitted edits show up as a rev ID of
4494 # all zeros, which we can't look up with
4495 # cmt_metadata
4496 if ($1 !~ /^0+$/) {
4497 (undef, $rev, undef) =
4498 ::cmt_metadata($1);
4499 $rev = '0' if (!$rev);
4500 } else {
4501 $rev = '0';
4503 $rev = sprintf('%-10s', $rev);
4504 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4506 print $line;
4508 } else {
4509 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4510 '--', $path);
4511 my ($sha1);
4512 my %authors;
4513 while (my $line = <$fh>) {
4514 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4515 $sha1 = $1;
4516 (undef, $rev, undef) = ::cmt_metadata($1);
4517 $rev = '0' if (!$rev);
4519 elsif ($line =~ /^author (.*)/) {
4520 $authors{$rev} = $1;
4521 $authors{$rev} =~ s/\s/_/g;
4523 elsif ($line =~ /^\t(.*)$/) {
4524 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4528 command_close_pipe($fh, $ctx);
4531 package Git::SVN::Migration;
4532 # these version numbers do NOT correspond to actual version numbers
4533 # of git nor git-svn. They are just relative.
4535 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4537 # v1 layout: .git/$id/info/url, refs/remotes/$id
4539 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4541 # v3 layout: .git/svn/$id, refs/remotes/$id
4542 # - info/url may remain for backwards compatibility
4543 # - this is what we migrate up to this layout automatically,
4544 # - this will be used by git svn init on single branches
4545 # v3.1 layout (auto migrated):
4546 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4547 # for backwards compatibility
4549 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4550 # - this is only created for newly multi-init-ed
4551 # repositories. Similar in spirit to the
4552 # --use-separate-remotes option in git-clone (now default)
4553 # - we do not automatically migrate to this (following
4554 # the example set by core git)
4556 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4557 # - newer, more-efficient format that uses 24-bytes per record
4558 # with no filler space.
4559 # - use xxd -c24 < .rev_map.$UUID to view and debug
4560 # - This is a one-way migration, repositories updated to the
4561 # new format will not be able to use old git-svn without
4562 # rebuilding the .rev_db. Rebuilding the rev_db is not
4563 # possible if noMetadata or useSvmProps are set; but should
4564 # be no problem for users that use the (sensible) defaults.
4565 use strict;
4566 use warnings;
4567 use Carp qw/croak/;
4568 use File::Path qw/mkpath/;
4569 use File::Basename qw/dirname basename/;
4570 use vars qw/$_minimize/;
4572 sub migrate_from_v0 {
4573 my $git_dir = $ENV{GIT_DIR};
4574 return undef unless -d $git_dir;
4575 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4576 my $migrated = 0;
4577 while (<$fh>) {
4578 chomp;
4579 my ($id, $orig_ref) = ($_, $_);
4580 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4581 next unless -f "$git_dir/$id/info/url";
4582 my $new_ref = "refs/remotes/$id";
4583 if (::verify_ref("$new_ref^0")) {
4584 print STDERR "W: $orig_ref is probably an old ",
4585 "branch used by an ancient version of ",
4586 "git-svn.\n",
4587 "However, $new_ref also exists.\n",
4588 "We will not be able ",
4589 "to use this branch until this ",
4590 "ambiguity is resolved.\n";
4591 next;
4593 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4594 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4595 command_noisy('update-ref', $new_ref, $orig_ref);
4596 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4597 $migrated++;
4599 command_close_pipe($fh, $ctx);
4600 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4601 $migrated;
4604 sub migrate_from_v1 {
4605 my $git_dir = $ENV{GIT_DIR};
4606 my $migrated = 0;
4607 return $migrated unless -d $git_dir;
4608 my $svn_dir = "$git_dir/svn";
4610 # just in case somebody used 'svn' as their $id at some point...
4611 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4613 print STDERR "Migrating from a git-svn v1 layout...\n";
4614 mkpath([$svn_dir]);
4615 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4616 "$svn_dir\n\t(required for this version ",
4617 "($::VERSION) of git-svn) does not. exist\n";
4618 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4619 while (<$fh>) {
4620 my $x = $_;
4621 next unless $x =~ s#^refs/remotes/##;
4622 chomp $x;
4623 next unless -f "$git_dir/$x/info/url";
4624 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4625 next unless $u;
4626 my $dn = dirname("$git_dir/svn/$x");
4627 mkpath([$dn]) unless -d $dn;
4628 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4629 mkpath(["$git_dir/svn/svn"]);
4630 print STDERR " - $git_dir/$x/info => ",
4631 "$git_dir/svn/$x/info\n";
4632 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4633 croak "$!: $x";
4634 # don't worry too much about these, they probably
4635 # don't exist with repos this old (save for index,
4636 # and we can easily regenerate that)
4637 foreach my $f (qw/unhandled.log index .rev_db/) {
4638 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4640 } else {
4641 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4642 rename "$git_dir/$x", "$git_dir/svn/$x" or
4643 croak "$!: $x";
4645 $migrated++;
4647 command_close_pipe($fh, $ctx);
4648 print STDERR "Done migrating from a git-svn v1 layout\n";
4649 $migrated;
4652 sub read_old_urls {
4653 my ($l_map, $pfx, $path) = @_;
4654 my @dir;
4655 foreach (<$path/*>) {
4656 if (-r "$_/info/url") {
4657 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4658 my $ref_id = $pfx . basename $_;
4659 my $url = ::file_to_s("$_/info/url");
4660 $l_map->{$ref_id} = $url;
4661 } elsif (-d $_) {
4662 push @dir, $_;
4665 foreach (@dir) {
4666 my $x = $_;
4667 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4668 read_old_urls($l_map, $x, $_);
4672 sub migrate_from_v2 {
4673 my @cfg = command(qw/config -l/);
4674 return if grep /^svn-remote\..+\.url=/, @cfg;
4675 my %l_map;
4676 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4677 my $migrated = 0;
4679 foreach my $ref_id (sort keys %l_map) {
4680 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4681 if ($@) {
4682 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4684 $migrated++;
4686 $migrated;
4689 sub minimize_connections {
4690 my $r = Git::SVN::read_all_remotes();
4691 my $new_urls = {};
4692 my $root_repos = {};
4693 foreach my $repo_id (keys %$r) {
4694 my $url = $r->{$repo_id}->{url} or next;
4695 my $fetch = $r->{$repo_id}->{fetch} or next;
4696 my $ra = Git::SVN::Ra->new($url);
4698 # skip existing cases where we already connect to the root
4699 if (($ra->{url} eq $ra->{repos_root}) ||
4700 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4701 $repo_id)) {
4702 $root_repos->{$ra->{url}} = $repo_id;
4703 next;
4706 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4707 my $root_path = $ra->{url};
4708 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4709 foreach my $path (keys %$fetch) {
4710 my $ref_id = $fetch->{$path};
4711 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4713 # make sure we can read when connecting to
4714 # a higher level of a repository
4715 my ($last_rev, undef) = $gs->last_rev_commit;
4716 if (!defined $last_rev) {
4717 $last_rev = eval {
4718 $root_ra->get_latest_revnum;
4720 next if $@;
4722 my $new = $root_path;
4723 $new .= length $path ? "/$path" : '';
4724 eval {
4725 $root_ra->get_log([$new], $last_rev, $last_rev,
4726 0, 0, 1, sub { });
4728 next if $@;
4729 $new_urls->{$ra->{repos_root}}->{$new} =
4730 { ref_id => $ref_id,
4731 old_repo_id => $repo_id,
4732 old_path => $path };
4736 my @emptied;
4737 foreach my $url (keys %$new_urls) {
4738 # see if we can re-use an existing [svn-remote "repo_id"]
4739 # instead of creating a(n ugly) new section:
4740 my $repo_id = $root_repos->{$url} ||
4741 Git::SVN::sanitize_remote_name($url);
4743 my $fetch = $new_urls->{$url};
4744 foreach my $path (keys %$fetch) {
4745 my $x = $fetch->{$path};
4746 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4747 my $pfx = "svn-remote.$x->{old_repo_id}";
4749 my $old_fetch = quotemeta("$x->{old_path}:".
4750 "refs/remotes/$x->{ref_id}");
4751 command_noisy(qw/config --unset/,
4752 "$pfx.fetch", '^'. $old_fetch . '$');
4753 delete $r->{$x->{old_repo_id}}->
4754 {fetch}->{$x->{old_path}};
4755 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4756 command_noisy(qw/config --unset/,
4757 "$pfx.url");
4758 push @emptied, $x->{old_repo_id}
4762 if (@emptied) {
4763 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4764 "$ENV{GIT_DIR}/config";
4765 print STDERR <<EOF;
4766 The following [svn-remote] sections in your config file ($file) are empty
4767 and can be safely removed:
4769 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4773 sub migration_check {
4774 migrate_from_v0();
4775 migrate_from_v1();
4776 migrate_from_v2();
4777 minimize_connections() if $_minimize;
4780 package Git::IndexInfo;
4781 use strict;
4782 use warnings;
4783 use Git qw/command_input_pipe command_close_pipe/;
4785 sub new {
4786 my ($class) = @_;
4787 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4788 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4791 sub remove {
4792 my ($self, $path) = @_;
4793 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4794 return ++$self->{nr};
4796 undef;
4799 sub update {
4800 my ($self, $mode, $hash, $path) = @_;
4801 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4802 return ++$self->{nr};
4804 undef;
4807 sub DESTROY {
4808 my ($self) = @_;
4809 command_close_pipe($self->{gui}, $self->{ctx});
4812 package Git::SVN::GlobSpec;
4813 use strict;
4814 use warnings;
4816 sub new {
4817 my ($class, $glob) = @_;
4818 my $re = $glob;
4819 $re =~ s!/+$!!g; # no need for trailing slashes
4820 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4821 my ($left, $right) = ($1, $2);
4822 if ($nr > 1) {
4823 die "Only one '*' wildcard expansion ",
4824 "is supported (got $nr): '$glob'\n";
4825 } elsif ($nr == 0) {
4826 die "One '*' is needed for glob: '$glob'\n";
4828 $re = quotemeta($left) . $re . quotemeta($right);
4829 if (length $left && !($left =~ s!/+$!!g)) {
4830 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4832 if (length $right && !($right =~ s!^/+!!g)) {
4833 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4835 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4836 bless { left => $left, right => $right, left_regex => $left_re,
4837 regex => qr/$re/, glob => $glob }, $class;
4840 sub full_path {
4841 my ($self, $path) = @_;
4842 return (length $self->{left} ? "$self->{left}/" : '') .
4843 $path . (length $self->{right} ? "/$self->{right}" : '');
4846 __END__
4848 Data structures:
4851 $remotes = { # returned by read_all_remotes()
4852 'svn' => {
4853 # svn-remote.svn.url=https://svn.musicpd.org
4854 url => 'https://svn.musicpd.org',
4855 # svn-remote.svn.fetch=mpd/trunk:trunk
4856 fetch => {
4857 'mpd/trunk' => 'trunk',
4859 # svn-remote.svn.tags=mpd/tags/*:tags/*
4860 tags => {
4861 path => {
4862 left => 'mpd/tags',
4863 right => '',
4864 regex => qr!mpd/tags/([^/]+)$!,
4865 glob => 'tags/*',
4867 ref => {
4868 left => 'tags',
4869 right => '',
4870 regex => qr!tags/([^/]+)$!,
4871 glob => 'tags/*',
4877 $log_entry hashref as returned by libsvn_log_entry()
4879 log => 'whitespace-formatted log entry
4880 ', # trailing newline is preserved
4881 revision => '8', # integer
4882 date => '2004-02-24T17:01:44.108345Z', # commit date
4883 author => 'committer name'
4887 # this is generated by generate_diff();
4888 @mods = array of diff-index line hashes, each element represents one line
4889 of diff-index output
4891 diff-index line ($m hash)
4893 mode_a => first column of diff-index output, no leading ':',
4894 mode_b => second column of diff-index output,
4895 sha1_b => sha1sum of the final blob,
4896 chg => change type [MCRADT],
4897 file_a => original file name of a file (iff chg is 'C' or 'R')
4898 file_b => new/current file name of a file (any chg)
4902 # retval of read_url_paths{,_all}();
4903 $l_map = {
4904 # repository root url
4905 'https://svn.musicpd.org' => {
4906 # repository path # GIT_SVN_ID
4907 'mpd/trunk' => 'trunk',
4908 'mpd/tags/0.11.5' => 'tags/0.11.5',
4912 Notes:
4913 I don't trust the each() function on unless I created %hash myself
4914 because the internal iterator may not have started at base.