Use '-f' option to point to the .gitmodules file
[git/gitweb.git] / git-svn.perl
blob2c53f39aefa0131cb15ab679e6b2633622c000a1
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # 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 %remote_opts );
88 my ($_trunk, $_tags, $_branches, $_stdlayout);
89 my %icv;
90 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
91 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
92 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
93 'stdlayout|s' => \$_stdlayout,
94 'minimize-url|m' => \$Git::SVN::_minimize_url,
95 'no-metadata' => sub { $icv{noMetadata} = 1 },
96 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
97 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
98 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
99 %remote_opts );
100 my %cmt_opts = ( 'edit|e' => \$_edit,
101 'rmdir' => \$SVN::Git::Editor::_rmdir,
102 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
103 'l=i' => \$SVN::Git::Editor::_rename_limit,
104 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
107 my %cmd = (
108 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
109 { 'revision|r=s' => \$_revision,
110 'fetch-all|all' => \$_fetch_all,
111 %fc_opts } ],
112 clone => [ \&cmd_clone, "Initialize and fetch revisions",
113 { 'revision|r=s' => \$_revision,
114 %fc_opts, %init_opts } ],
115 init => [ \&cmd_init, "Initialize a repo for tracking" .
116 " (requires URL argument)",
117 \%init_opts ],
118 'multi-init' => [ \&cmd_multi_init,
119 "Deprecated alias for ".
120 "'$0 init -T<trunk> -b<branches> -t<tags>'",
121 \%init_opts ],
122 dcommit => [ \&cmd_dcommit,
123 'Commit several diffs to merge with upstream',
124 { 'merge|m|M' => \$_merge,
125 'strategy|s=s' => \$_strategy,
126 'verbose|v' => \$_verbose,
127 'dry-run|n' => \$_dry_run,
128 'fetch-all|all' => \$_fetch_all,
129 'no-rebase' => \$_no_rebase,
130 %cmt_opts, %fc_opts } ],
131 'set-tree' => [ \&cmd_set_tree,
132 "Set an SVN repository to a git tree-ish",
133 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
134 'create-ignore' => [ \&cmd_create_ignore,
135 'Create a .gitignore per svn:ignore',
136 { 'revision|r=i' => \$_revision
137 } ],
138 'propget' => [ \&cmd_propget,
139 'Print the value of a property on a file or directory',
140 { 'revision|r=i' => \$_revision } ],
141 'proplist' => [ \&cmd_proplist,
142 'List all properties of a file or directory',
143 { 'revision|r=i' => \$_revision } ],
144 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
145 { 'revision|r=i' => \$_revision
146 } ],
147 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
148 { 'revision|r=i' => \$_revision
149 } ],
150 'multi-fetch' => [ \&cmd_multi_fetch,
151 "Deprecated alias for $0 fetch --all",
152 { 'revision|r=s' => \$_revision, %fc_opts } ],
153 'migrate' => [ sub { },
154 # no-op, we automatically run this anyways,
155 'Migrate configuration/metadata/layout from
156 previous versions of git-svn',
157 { 'minimize' => \$Git::SVN::Migration::_minimize,
158 %remote_opts } ],
159 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
160 { 'limit=i' => \$Git::SVN::Log::limit,
161 'revision|r=s' => \$_revision,
162 'verbose|v' => \$Git::SVN::Log::verbose,
163 'incremental' => \$Git::SVN::Log::incremental,
164 'oneline' => \$Git::SVN::Log::oneline,
165 'show-commit' => \$Git::SVN::Log::show_commit,
166 'non-recursive' => \$Git::SVN::Log::non_recursive,
167 'authors-file|A=s' => \$_authors,
168 'color' => \$Git::SVN::Log::color,
169 'pager=s' => \$Git::SVN::Log::pager
170 } ],
171 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
172 {} ],
173 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
174 { 'merge|m|M' => \$_merge,
175 'verbose|v' => \$_verbose,
176 'strategy|s=s' => \$_strategy,
177 'local|l' => \$_local,
178 'fetch-all|all' => \$_fetch_all,
179 %fc_opts } ],
180 'commit-diff' => [ \&cmd_commit_diff,
181 'Commit a diff between two trees',
182 { 'message|m=s' => \$_message,
183 'file|F=s' => \$_file,
184 'revision|r=s' => \$_revision,
185 %cmt_opts } ],
186 'info' => [ \&cmd_info,
187 "Show info about the latest SVN revision
188 on the current branch",
189 { 'url' => \$_url, } ],
190 'blame' => [ \&Git::SVN::Log::cmd_blame,
191 "Show what revision and author last modified each line of a file",
192 { 'git-format' => \$_git_format } ],
195 my $cmd;
196 for (my $i = 0; $i < @ARGV; $i++) {
197 if (defined $cmd{$ARGV[$i]}) {
198 $cmd = $ARGV[$i];
199 splice @ARGV, $i, 1;
200 last;
204 # make sure we're always running at the top-level working directory
205 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
206 unless (-d $ENV{GIT_DIR}) {
207 if ($git_dir_user_set) {
208 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
209 "but it is not a directory\n";
211 my $git_dir = delete $ENV{GIT_DIR};
212 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
213 unless (length $cdup) {
214 die "Already at toplevel, but $git_dir ",
215 "not found '$cdup'\n";
217 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
218 unless (-d $git_dir) {
219 die "$git_dir still not found after going to ",
220 "'$cdup'\n";
222 $ENV{GIT_DIR} = $git_dir;
226 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
228 read_repo_config(\%opts);
229 Getopt::Long::Configure('pass_through') if ($cmd && ($cmd eq 'log' || $cmd eq 'blame'));
230 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
231 'minimize-connections' => \$Git::SVN::Migration::_minimize,
232 'id|i=s' => \$Git::SVN::default_ref_id,
233 'svn-remote|remote|R=s' => sub {
234 $Git::SVN::no_reuse_existing = 1;
235 $Git::SVN::default_repo_id = $_[1] });
236 exit 1 if (!$rv && $cmd && $cmd ne 'log');
238 usage(0) if $_help;
239 version() if $_version;
240 usage(1) unless defined $cmd;
241 load_authors() if $_authors;
243 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
244 Git::SVN::Migration::migration_check();
246 Git::SVN::init_vars();
247 eval {
248 Git::SVN::verify_remotes_sanity();
249 $cmd{$cmd}->[0]->(@ARGV);
251 fatal $@ if $@;
252 post_fetch_checkout();
253 exit 0;
255 ####################### primary functions ######################
256 sub usage {
257 my $exit = shift || 0;
258 my $fd = $exit ? \*STDERR : \*STDOUT;
259 print $fd <<"";
260 git-svn - bidirectional operations between a single Subversion tree and git
261 Usage: $0 <command> [options] [arguments]\n
263 print $fd "Available commands:\n" unless $cmd;
265 foreach (sort keys %cmd) {
266 next if $cmd && $cmd ne $_;
267 next if /^multi-/; # don't show deprecated commands
268 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
269 foreach (sort keys %{$cmd{$_}->[2]}) {
270 # mixed-case options are for .git/config only
271 next if /[A-Z]/ && /^[a-z]+$/i;
272 # prints out arguments as they should be passed:
273 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
274 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
275 "--$_" : "-$_" }
276 split /\|/,$_)," $x\n";
279 print $fd <<"";
280 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
281 arbitrary identifier if you're tracking multiple SVN branches/repositories in
282 one git repository and want to keep them separate. See git-svn(1) for more
283 information.
285 exit $exit;
288 sub version {
289 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
290 exit 0;
293 sub do_git_init_db {
294 unless (-d $ENV{GIT_DIR}) {
295 my @init_db = ('init');
296 push @init_db, "--template=$_template" if defined $_template;
297 if (defined $_shared) {
298 if ($_shared =~ /[a-z]/) {
299 push @init_db, "--shared=$_shared";
300 } else {
301 push @init_db, "--shared";
304 command_noisy(@init_db);
306 my $set;
307 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
308 foreach my $i (keys %icv) {
309 die "'$set' and '$i' cannot both be set\n" if $set;
310 next unless defined $icv{$i};
311 command_noisy('config', "$pfx.$i", $icv{$i});
312 $set = $i;
316 sub init_subdir {
317 my $repo_path = shift or return;
318 mkpath([$repo_path]) unless -d $repo_path;
319 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
320 $ENV{GIT_DIR} = '.git';
323 sub cmd_clone {
324 my ($url, $path) = @_;
325 if (!defined $path &&
326 (defined $_trunk || defined $_branches || defined $_tags ||
327 defined $_stdlayout) &&
328 $url !~ m#^[a-z\+]+://#) {
329 $path = $url;
331 $path = basename($url) if !defined $path || !length $path;
332 cmd_init($url, $path);
333 Git::SVN::fetch_all($Git::SVN::default_repo_id);
336 sub cmd_init {
337 if (defined $_stdlayout) {
338 $_trunk = 'trunk' if (!defined $_trunk);
339 $_tags = 'tags' if (!defined $_tags);
340 $_branches = 'branches' if (!defined $_branches);
342 if (defined $_trunk || defined $_branches || defined $_tags) {
343 return cmd_multi_init(@_);
345 my $url = shift or die "SVN repository location required ",
346 "as a command-line argument\n";
347 init_subdir(@_);
348 do_git_init_db();
350 Git::SVN->init($url);
353 sub cmd_fetch {
354 if (grep /^\d+=./, @_) {
355 die "'<rev>=<commit>' fetch arguments are ",
356 "no longer supported.\n";
358 my ($remote) = @_;
359 if (@_ > 1) {
360 die "Usage: $0 fetch [--all] [svn-remote]\n";
362 $remote ||= $Git::SVN::default_repo_id;
363 if ($_fetch_all) {
364 cmd_multi_fetch();
365 } else {
366 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
370 sub cmd_set_tree {
371 my (@commits) = @_;
372 if ($_stdin || !@commits) {
373 print "Reading from stdin...\n";
374 @commits = ();
375 while (<STDIN>) {
376 if (/\b($sha1_short)\b/o) {
377 unshift @commits, $1;
381 my @revs;
382 foreach my $c (@commits) {
383 my @tmp = command('rev-parse',$c);
384 if (scalar @tmp == 1) {
385 push @revs, $tmp[0];
386 } elsif (scalar @tmp > 1) {
387 push @revs, reverse(command('rev-list',@tmp));
388 } else {
389 fatal "Failed to rev-parse $c";
392 my $gs = Git::SVN->new;
393 my ($r_last, $cmt_last) = $gs->last_rev_commit;
394 $gs->fetch;
395 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
396 fatal "There are new revisions that were fetched ",
397 "and need to be merged (or acknowledged) ",
398 "before committing.\nlast rev: $r_last\n",
399 " current: $gs->{last_rev}";
401 $gs->set_tree($_) foreach @revs;
402 print "Done committing ",scalar @revs," revisions to SVN\n";
403 unlink $gs->{index};
406 sub cmd_dcommit {
407 my $head = shift;
408 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
409 'Cannot dcommit with a dirty index. Commit your changes first, '
410 . "or stash them with `git stash'.\n";
411 $head ||= 'HEAD';
412 my @refs;
413 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
414 if ($url) {
415 print "Committing to $url ...\n";
417 unless ($gs) {
418 die "Unable to determine upstream SVN information from ",
419 "$head history.\nPerhaps the repository is empty.";
421 my $last_rev;
422 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
423 if ($_no_rebase && scalar(@$linear_refs) > 1) {
424 warn "Attempting to commit more than one change while ",
425 "--no-rebase is enabled.\n",
426 "If these changes depend on each other, re-running ",
427 "without --no-rebase may be required."
429 while (1) {
430 my $d = shift @$linear_refs or last;
431 unless (defined $last_rev) {
432 (undef, $last_rev, undef) = cmt_metadata("$d~1");
433 unless (defined $last_rev) {
434 fatal "Unable to extract revision information ",
435 "from commit $d~1";
438 if ($_dry_run) {
439 print "diff-tree $d~1 $d\n";
440 } else {
441 my $cmt_rev;
442 my %ed_opts = ( r => $last_rev,
443 log => get_commit_entry($d)->{log},
444 ra => Git::SVN::Ra->new($gs->full_url),
445 config => SVN::Core::config_get_config(
446 $Git::SVN::Ra::config_dir
448 tree_a => "$d~1",
449 tree_b => $d,
450 editor_cb => sub {
451 print "Committed r$_[0]\n";
452 $cmt_rev = $_[0];
454 svn_path => '');
455 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
456 print "No changes\n$d~1 == $d\n";
457 } elsif ($parents->{$d} && @{$parents->{$d}}) {
458 $gs->{inject_parents_dcommit}->{$cmt_rev} =
459 $parents->{$d};
461 $_fetch_all ? $gs->fetch_all : $gs->fetch;
462 $last_rev = $cmt_rev;
463 next if $_no_rebase;
465 # we always want to rebase against the current HEAD,
466 # not any head that was passed to us
467 my @diff = command('diff-tree', $d,
468 $gs->refname, '--');
469 my @finish;
470 if (@diff) {
471 @finish = rebase_cmd();
472 print STDERR "W: $d and ", $gs->refname,
473 " differ, using @finish:\n",
474 join("\n", @diff), "\n";
475 } else {
476 print "No changes between current HEAD and ",
477 $gs->refname,
478 "\nResetting to the latest ",
479 $gs->refname, "\n";
480 @finish = qw/reset --mixed/;
482 command_noisy(@finish, $gs->refname);
483 if (@diff) {
484 @refs = ();
485 my ($url_, $rev_, $uuid_, $gs_) =
486 working_head_info($head, \@refs);
487 my ($linear_refs_, $parents_) =
488 linearize_history($gs_, \@refs);
489 if (scalar(@$linear_refs) !=
490 scalar(@$linear_refs_)) {
491 fatal "# of revisions changed ",
492 "\nbefore:\n",
493 join("\n", @$linear_refs),
494 "\n\nafter:\n",
495 join("\n", @$linear_refs_), "\n",
496 'If you are attempting to commit ',
497 "merges, try running:\n\t",
498 'git rebase --interactive',
499 '--preserve-merges ',
500 $gs->refname,
501 "\nBefore dcommitting";
503 if ($url_ ne $url) {
504 fatal "URL mismatch after rebase: ",
505 "$url_ != $url";
507 if ($uuid_ ne $uuid) {
508 fatal "uuid mismatch after rebase: ",
509 "$uuid_ != $uuid";
511 # remap parents
512 my (%p, @l, $i);
513 for ($i = 0; $i < scalar @$linear_refs; $i++) {
514 my $new = $linear_refs_->[$i] or next;
515 $p{$new} =
516 $parents->{$linear_refs->[$i]};
517 push @l, $new;
519 $parents = \%p;
520 $linear_refs = \@l;
524 unlink $gs->{index};
527 sub cmd_find_rev {
528 my $revision_or_hash = shift or die "SVN or git revision required ",
529 "as a command-line argument\n";
530 my $result;
531 if ($revision_or_hash =~ /^r\d+$/) {
532 my $head = shift;
533 $head ||= 'HEAD';
534 my @refs;
535 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
536 unless ($gs) {
537 die "Unable to determine upstream SVN information from ",
538 "$head history\n";
540 my $desired_revision = substr($revision_or_hash, 1);
541 $result = $gs->rev_map_get($desired_revision);
542 } else {
543 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
544 $result = $rev;
546 print "$result\n" if $result;
549 sub cmd_rebase {
550 command_noisy(qw/update-index --refresh/);
551 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
552 unless ($gs) {
553 die "Unable to determine upstream SVN information from ",
554 "working tree history\n";
556 if (command(qw/diff-index HEAD --/)) {
557 print STDERR "Cannot rebase with uncommited changes:\n";
558 command_noisy('status');
559 exit 1;
561 unless ($_local) {
562 # rebase will checkout for us, so no need to do it explicitly
563 $_no_checkout = 'true';
564 $_fetch_all ? $gs->fetch_all : $gs->fetch;
566 command_noisy(rebase_cmd(), $gs->refname);
569 sub cmd_show_ignore {
570 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
571 $gs ||= Git::SVN->new;
572 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
573 $gs->prop_walk($gs->{path}, $r, sub {
574 my ($gs, $path, $props) = @_;
575 print STDOUT "\n# $path\n";
576 my $s = $props->{'svn:ignore'} or return;
577 $s =~ s/[\r\n]+/\n/g;
578 chomp $s;
579 $s =~ s#^#$path#gm;
580 print STDOUT "$s\n";
584 sub cmd_show_externals {
585 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
586 $gs ||= Git::SVN->new;
587 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
588 $gs->prop_walk($gs->{path}, $r, sub {
589 my ($gs, $path, $props) = @_;
590 print STDOUT "\n# $path\n";
591 my $s = $props->{'svn:externals'} or return;
592 $s =~ s/[\r\n]+/\n/g;
593 chomp $s;
594 $s =~ s#^#$path#gm;
595 print STDOUT "$s\n";
599 sub cmd_create_ignore {
600 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
601 $gs ||= Git::SVN->new;
602 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
603 $gs->prop_walk($gs->{path}, $r, sub {
604 my ($gs, $path, $props) = @_;
605 # $path is of the form /path/to/dir/
606 my $ignore = '.' . $path . '.gitignore';
607 my $s = $props->{'svn:ignore'} or return;
608 open(GITIGNORE, '>', $ignore)
609 or fatal("Failed to open `$ignore' for writing: $!");
610 $s =~ s/[\r\n]+/\n/g;
611 chomp $s;
612 # Prefix all patterns so that the ignore doesn't apply
613 # to sub-directories.
614 $s =~ s#^#/#gm;
615 print GITIGNORE "$s\n";
616 close(GITIGNORE)
617 or fatal("Failed to close `$ignore': $!");
618 command_noisy('add', '-f', $ignore);
622 sub canonicalize_path {
623 my ($path) = @_;
624 my $dot_slash_added = 0;
625 if (substr($path, 0, 1) ne "/") {
626 $path = "./" . $path;
627 $dot_slash_added = 1;
629 # File::Spec->canonpath doesn't collapse x/../y into y (for a
630 # good reason), so let's do this manually.
631 $path =~ s#/+#/#g;
632 $path =~ s#/\.(?:/|$)#/#g;
633 $path =~ s#/[^/]+/\.\.##g;
634 $path =~ s#/$##g;
635 $path =~ s#^\./## if $dot_slash_added;
636 return $path;
639 # get_svnprops(PATH)
640 # ------------------
641 # Helper for cmd_propget and cmd_proplist below.
642 sub get_svnprops {
643 my $path = shift;
644 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
645 $gs ||= Git::SVN->new;
647 # prefix THE PATH by the sub-directory from which the user
648 # invoked us.
649 $path = $cmd_dir_prefix . $path;
650 fatal("No such file or directory: $path") unless -e $path;
651 my $is_dir = -d $path ? 1 : 0;
652 $path = $gs->{path} . '/' . $path;
654 # canonicalize the path (otherwise libsvn will abort or fail to
655 # find the file)
656 $path = canonicalize_path($path);
658 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
659 my $props;
660 if ($is_dir) {
661 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
663 else {
664 (undef, $props) = $gs->ra->get_file($path, $r, undef);
666 return $props;
669 # cmd_propget (PROP, PATH)
670 # ------------------------
671 # Print the SVN property PROP for PATH.
672 sub cmd_propget {
673 my ($prop, $path) = @_;
674 $path = '.' if not defined $path;
675 usage(1) if not defined $prop;
676 my $props = get_svnprops($path);
677 if (not defined $props->{$prop}) {
678 fatal("`$path' does not have a `$prop' SVN property.");
680 print $props->{$prop} . "\n";
683 # cmd_proplist (PATH)
684 # -------------------
685 # Print the list of SVN properties for PATH.
686 sub cmd_proplist {
687 my $path = shift;
688 $path = '.' if not defined $path;
689 my $props = get_svnprops($path);
690 print "Properties on '$path':\n";
691 foreach (sort keys %{$props}) {
692 print " $_\n";
696 sub cmd_multi_init {
697 my $url = shift;
698 unless (defined $_trunk || defined $_branches || defined $_tags) {
699 usage(1);
702 # there are currently some bugs that prevent multi-init/multi-fetch
703 # setups from working well without this.
704 $Git::SVN::_minimize_url = 1;
706 $_prefix = '' unless defined $_prefix;
707 if (defined $url) {
708 $url =~ s#/+$##;
709 init_subdir(@_);
711 do_git_init_db();
712 if (defined $_trunk) {
713 my $trunk_ref = $_prefix . 'trunk';
714 # try both old-style and new-style lookups:
715 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
716 unless ($gs_trunk) {
717 my ($trunk_url, $trunk_path) =
718 complete_svn_url($url, $_trunk);
719 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
720 undef, $trunk_ref);
723 return unless defined $_branches || defined $_tags;
724 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
725 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
726 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
729 sub cmd_multi_fetch {
730 my $remotes = Git::SVN::read_all_remotes();
731 foreach my $repo_id (sort keys %$remotes) {
732 if ($remotes->{$repo_id}->{url}) {
733 Git::SVN::fetch_all($repo_id, $remotes);
738 # this command is special because it requires no metadata
739 sub cmd_commit_diff {
740 my ($ta, $tb, $url) = @_;
741 my $usage = "Usage: $0 commit-diff -r<revision> ".
742 "<tree-ish> <tree-ish> [<URL>]";
743 fatal($usage) if (!defined $ta || !defined $tb);
744 my $svn_path;
745 if (!defined $url) {
746 my $gs = eval { Git::SVN->new };
747 if (!$gs) {
748 fatal("Needed URL or usable git-svn --id in ",
749 "the command-line\n", $usage);
751 $url = $gs->{url};
752 $svn_path = $gs->{path};
754 unless (defined $_revision) {
755 fatal("-r|--revision is a required argument\n", $usage);
757 if (defined $_message && defined $_file) {
758 fatal("Both --message/-m and --file/-F specified ",
759 "for the commit message.\n",
760 "I have no idea what you mean");
762 if (defined $_file) {
763 $_message = file_to_s($_file);
764 } else {
765 $_message ||= get_commit_entry($tb)->{log};
767 my $ra ||= Git::SVN::Ra->new($url);
768 $svn_path ||= $ra->{svn_path};
769 my $r = $_revision;
770 if ($r eq 'HEAD') {
771 $r = $ra->get_latest_revnum;
772 } elsif ($r !~ /^\d+$/) {
773 die "revision argument: $r not understood by git-svn\n";
775 my %ed_opts = ( r => $r,
776 log => $_message,
777 ra => $ra,
778 tree_a => $ta,
779 tree_b => $tb,
780 editor_cb => sub { print "Committed r$_[0]\n" },
781 svn_path => $svn_path );
782 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
783 print "No changes\n$ta == $tb\n";
787 sub cmd_info {
788 my $path = canonicalize_path(shift or ".");
789 unless (scalar(@_) == 0) {
790 die "Too many arguments specified\n";
793 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
795 if (!$file_type && !$diff_status) {
796 print STDERR "$path: (Not a versioned resource)\n\n";
797 return;
800 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
801 unless ($gs) {
802 die "Unable to determine upstream SVN information from ",
803 "working tree history\n";
805 my $full_url = $url . ($path eq "." ? "" : "/$path");
807 if ($_url) {
808 print $full_url, "\n";
809 return;
812 my $result = "Path: $path\n";
813 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
814 $result .= "URL: " . $full_url . "\n";
816 eval {
817 my $repos_root = $gs->repos_root;
818 Git::SVN::remove_username($repos_root);
819 $result .= "Repository Root: $repos_root\n";
821 if ($@) {
822 $result .= "Repository Root: (offline)\n";
824 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
825 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
827 $result .= "Node Kind: " .
828 ($file_type eq "dir" ? "directory" : "file") . "\n";
830 my $schedule = $diff_status eq "A"
831 ? "add"
832 : ($diff_status eq "D" ? "delete" : "normal");
833 $result .= "Schedule: $schedule\n";
835 if ($diff_status eq "A") {
836 print $result, "\n";
837 return;
840 my ($lc_author, $lc_rev, $lc_date_utc);
841 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
842 my $log = command_output_pipe(@args);
843 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
844 while (<$log>) {
845 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
846 $lc_author = $1;
847 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
848 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
849 (undef, $lc_rev, undef) = ::extract_metadata($1);
852 close $log;
854 Git::SVN::Log::set_local_timezone();
856 $result .= "Last Changed Author: $lc_author\n";
857 $result .= "Last Changed Rev: $lc_rev\n";
858 $result .= "Last Changed Date: " .
859 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
861 if ($file_type ne "dir") {
862 my $text_last_updated_date =
863 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
864 $result .=
865 "Text Last Updated: " .
866 Git::SVN::Log::format_svn_date($text_last_updated_date) .
867 "\n";
868 my $checksum;
869 if ($diff_status eq "D") {
870 my ($fh, $ctx) =
871 command_output_pipe(qw(cat-file blob), "HEAD:$path");
872 if ($file_type eq "link") {
873 my $file_name = <$fh>;
874 $checksum = md5sum("link $file_name");
875 } else {
876 $checksum = md5sum($fh);
878 command_close_pipe($fh, $ctx);
879 } elsif ($file_type eq "link") {
880 my $file_name =
881 command(qw(cat-file blob), "HEAD:$path");
882 $checksum =
883 md5sum("link " . $file_name);
884 } else {
885 open FILE, "<", $path or die $!;
886 $checksum = md5sum(\*FILE);
887 close FILE or die $!;
889 $result .= "Checksum: " . $checksum . "\n";
892 print $result, "\n";
895 ########################### utility functions #########################
897 sub rebase_cmd {
898 my @cmd = qw/rebase/;
899 push @cmd, '-v' if $_verbose;
900 push @cmd, qw/--merge/ if $_merge;
901 push @cmd, "--strategy=$_strategy" if $_strategy;
902 @cmd;
905 sub post_fetch_checkout {
906 return if $_no_checkout;
907 my $gs = $Git::SVN::_head or return;
908 return if verify_ref('refs/heads/master^0');
910 my $valid_head = verify_ref('HEAD^0');
911 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
912 return if ($valid_head || !verify_ref('HEAD^0'));
914 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
915 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
916 return if -f $index;
918 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
919 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
920 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
921 print STDERR "Checked out HEAD:\n ",
922 $gs->full_url, " r", $gs->last_rev, "\n";
925 sub complete_svn_url {
926 my ($url, $path) = @_;
927 $path =~ s#/+$##;
928 if ($path !~ m#^[a-z\+]+://#) {
929 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
930 fatal("E: '$path' is not a complete URL ",
931 "and a separate URL is not specified");
933 return ($url, $path);
935 return ($path, '');
938 sub complete_url_ls_init {
939 my ($ra, $repo_path, $switch, $pfx) = @_;
940 unless ($repo_path) {
941 print STDERR "W: $switch not specified\n";
942 return;
944 $repo_path =~ s#/+$##;
945 if ($repo_path =~ m#^[a-z\+]+://#) {
946 $ra = Git::SVN::Ra->new($repo_path);
947 $repo_path = '';
948 } else {
949 $repo_path =~ s#^/+##;
950 unless ($ra) {
951 fatal("E: '$repo_path' is not a complete URL ",
952 "and a separate URL is not specified");
955 my $url = $ra->{url};
956 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
957 my $k = "svn-remote.$gs->{repo_id}.url";
958 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
959 if ($orig_url && ($orig_url ne $gs->{url})) {
960 die "$k already set: $orig_url\n",
961 "wanted to set to: $gs->{url}\n";
963 command_oneline('config', $k, $gs->{url}) unless $orig_url;
964 my $remote_path = "$ra->{svn_path}/$repo_path";
965 $remote_path =~ s#/+#/#g;
966 $remote_path =~ s#^/##g;
967 $remote_path .= "/*" if $remote_path !~ /\*/;
968 my ($n) = ($switch =~ /^--(\w+)/);
969 if (length $pfx && $pfx !~ m#/$#) {
970 die "--prefix='$pfx' must have a trailing slash '/'\n";
972 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
973 "$remote_path:refs/remotes/$pfx*");
976 sub verify_ref {
977 my ($ref) = @_;
978 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
979 { STDERR => 0 }); };
982 sub get_tree_from_treeish {
983 my ($treeish) = @_;
984 # $treeish can be a symbolic ref, too:
985 my $type = command_oneline(qw/cat-file -t/, $treeish);
986 my $expected;
987 while ($type eq 'tag') {
988 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
990 if ($type eq 'commit') {
991 $expected = (grep /^tree /, command(qw/cat-file commit/,
992 $treeish))[0];
993 ($expected) = ($expected =~ /^tree ($sha1)$/o);
994 die "Unable to get tree from $treeish\n" unless $expected;
995 } elsif ($type eq 'tree') {
996 $expected = $treeish;
997 } else {
998 die "$treeish is a $type, expected tree, tag or commit\n";
1000 return $expected;
1003 sub get_commit_entry {
1004 my ($treeish) = shift;
1005 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1006 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1007 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1008 open my $log_fh, '>', $commit_editmsg or croak $!;
1010 my $type = command_oneline(qw/cat-file -t/, $treeish);
1011 if ($type eq 'commit' || $type eq 'tag') {
1012 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1013 $type, $treeish);
1014 my $in_msg = 0;
1015 while (<$msg_fh>) {
1016 if (!$in_msg) {
1017 $in_msg = 1 if (/^\s*$/);
1018 } elsif (/^git-svn-id: /) {
1019 # skip this for now, we regenerate the
1020 # correct one on re-fetch anyways
1021 # TODO: set *:merge properties or like...
1022 } else {
1023 print $log_fh $_ or croak $!;
1026 command_close_pipe($msg_fh, $ctx);
1028 close $log_fh or croak $!;
1030 if ($_edit || ($type eq 'tree')) {
1031 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1032 # TODO: strip out spaces, comments, like git-commit.sh
1033 system($editor, $commit_editmsg);
1035 rename $commit_editmsg, $commit_msg or croak $!;
1036 open $log_fh, '<', $commit_msg or croak $!;
1037 { local $/; chomp($log_entry{log} = <$log_fh>); }
1038 close $log_fh or croak $!;
1039 unlink $commit_msg;
1040 \%log_entry;
1043 sub s_to_file {
1044 my ($str, $file, $mode) = @_;
1045 open my $fd,'>',$file or croak $!;
1046 print $fd $str,"\n" or croak $!;
1047 close $fd or croak $!;
1048 chmod ($mode &~ umask, $file) if (defined $mode);
1051 sub file_to_s {
1052 my $file = shift;
1053 open my $fd,'<',$file or croak "$!: file: $file\n";
1054 local $/;
1055 my $ret = <$fd>;
1056 close $fd or croak $!;
1057 $ret =~ s/\s*$//s;
1058 return $ret;
1061 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1062 sub load_authors {
1063 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1064 my $log = $cmd eq 'log';
1065 while (<$authors>) {
1066 chomp;
1067 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1068 my ($user, $name, $email) = ($1, $2, $3);
1069 if ($log) {
1070 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1071 } else {
1072 $users{$user} = [$name, $email];
1075 close $authors or croak $!;
1078 # convert GetOpt::Long specs for use by git-config
1079 sub read_repo_config {
1080 return unless -d $ENV{GIT_DIR};
1081 my $opts = shift;
1082 my @config_only;
1083 foreach my $o (keys %$opts) {
1084 # if we have mixedCase and a long option-only, then
1085 # it's a config-only variable that we don't need for
1086 # the command-line.
1087 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1088 my $v = $opts->{$o};
1089 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1090 $key =~ s/-//g;
1091 my $arg = 'git-config';
1092 $arg .= ' --int' if ($o =~ /[:=]i$/);
1093 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1094 if (ref $v eq 'ARRAY') {
1095 chomp(my @tmp = `$arg --get-all svn.$key`);
1096 @$v = @tmp if @tmp;
1097 } else {
1098 chomp(my $tmp = `$arg --get svn.$key`);
1099 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1100 $$v = $tmp;
1104 delete @$opts{@config_only} if @config_only;
1107 sub extract_metadata {
1108 my $id = shift or return (undef, undef, undef);
1109 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1110 \s([a-f\d\-]+)$/x);
1111 if (!defined $rev || !$uuid || !$url) {
1112 # some of the original repositories I made had
1113 # identifiers like this:
1114 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1116 return ($url, $rev, $uuid);
1119 sub cmt_metadata {
1120 return extract_metadata((grep(/^git-svn-id: /,
1121 command(qw/cat-file commit/, shift)))[-1]);
1124 sub working_head_info {
1125 my ($head, $refs) = @_;
1126 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1127 my ($fh, $ctx) = command_output_pipe(@args, $head);
1128 my $hash;
1129 my %max;
1130 while (<$fh>) {
1131 if ( m{^commit ($::sha1)$} ) {
1132 unshift @$refs, $hash if $hash and $refs;
1133 $hash = $1;
1134 next;
1136 next unless s{^\s*(git-svn-id:)}{$1};
1137 my ($url, $rev, $uuid) = extract_metadata($_);
1138 if (defined $url && defined $rev) {
1139 next if $max{$url} and $max{$url} < $rev;
1140 if (my $gs = Git::SVN->find_by_url($url)) {
1141 my $c = $gs->rev_map_get($rev);
1142 if ($c && $c eq $hash) {
1143 close $fh; # break the pipe
1144 return ($url, $rev, $uuid, $gs);
1145 } else {
1146 $max{$url} ||= $gs->rev_map_max;
1151 command_close_pipe($fh, $ctx);
1152 (undef, undef, undef, undef);
1155 sub read_commit_parents {
1156 my ($parents, $c) = @_;
1157 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1158 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1159 @{$parents->{$c}} = split(/ /, $p);
1162 sub linearize_history {
1163 my ($gs, $refs) = @_;
1164 my %parents;
1165 foreach my $c (@$refs) {
1166 read_commit_parents(\%parents, $c);
1169 my @linear_refs;
1170 my %skip = ();
1171 my $last_svn_commit = $gs->last_commit;
1172 foreach my $c (reverse @$refs) {
1173 next if $c eq $last_svn_commit;
1174 last if $skip{$c};
1176 unshift @linear_refs, $c;
1177 $skip{$c} = 1;
1179 # we only want the first parent to diff against for linear
1180 # history, we save the rest to inject when we finalize the
1181 # svn commit
1182 my $fp_a = verify_ref("$c~1");
1183 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1184 if (!$fp_a || !$fp_b) {
1185 die "Commit $c\n",
1186 "has no parent commit, and therefore ",
1187 "nothing to diff against.\n",
1188 "You should be working from a repository ",
1189 "originally created by git-svn\n";
1191 if ($fp_a ne $fp_b) {
1192 die "$c~1 = $fp_a, however parsing commit $c ",
1193 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1196 foreach my $p (@{$parents{$c}}) {
1197 $skip{$p} = 1;
1200 (\@linear_refs, \%parents);
1203 sub find_file_type_and_diff_status {
1204 my ($path) = @_;
1205 return ('dir', '') if $path eq '.';
1207 my $diff_output =
1208 command_oneline(qw(diff --cached --name-status --), $path) || "";
1209 my $diff_status = (split(' ', $diff_output))[0] || "";
1211 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1213 return (undef, undef) if !$diff_status && !$ls_tree;
1215 if ($diff_status eq "A") {
1216 return ("link", $diff_status) if -l $path;
1217 return ("dir", $diff_status) if -d $path;
1218 return ("file", $diff_status);
1221 my $mode = (split(' ', $ls_tree))[0] || "";
1223 return ("link", $diff_status) if $mode eq "120000";
1224 return ("dir", $diff_status) if $mode eq "040000";
1225 return ("file", $diff_status);
1228 sub md5sum {
1229 my $arg = shift;
1230 my $ref = ref $arg;
1231 my $md5 = Digest::MD5->new();
1232 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1233 $md5->addfile($arg) or croak $!;
1234 } elsif ($ref eq 'SCALAR') {
1235 $md5->add($$arg) or croak $!;
1236 } elsif (!$ref) {
1237 $md5->add($arg) or croak $!;
1238 } else {
1239 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1241 return $md5->hexdigest();
1244 package Git::SVN;
1245 use strict;
1246 use warnings;
1247 use Fcntl qw/:DEFAULT :seek/;
1248 use constant rev_map_fmt => 'NH40';
1249 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1250 $_repack $_repack_flags $_use_svm_props $_head
1251 $_use_svnsync_props $no_reuse_existing $_minimize_url
1252 $_use_log_author/;
1253 use Carp qw/croak/;
1254 use File::Path qw/mkpath/;
1255 use File::Copy qw/copy/;
1256 use IPC::Open3;
1258 my ($_gc_nr, $_gc_period);
1260 # properties that we do not log:
1261 my %SKIP_PROP;
1262 BEGIN {
1263 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1264 svn:special svn:executable
1265 svn:entry:committed-rev
1266 svn:entry:last-author
1267 svn:entry:uuid
1268 svn:entry:committed-date/;
1270 # some options are read globally, but can be overridden locally
1271 # per [svn-remote "..."] section. Command-line options will *NOT*
1272 # override options set in an [svn-remote "..."] section
1273 no strict 'refs';
1274 for my $option (qw/follow_parent no_metadata use_svm_props
1275 use_svnsync_props/) {
1276 my $key = $option;
1277 $key =~ tr/_//d;
1278 my $prop = "-$option";
1279 *$option = sub {
1280 my ($self) = @_;
1281 return $self->{$prop} if exists $self->{$prop};
1282 my $k = "svn-remote.$self->{repo_id}.$key";
1283 eval { command_oneline(qw/config --get/, $k) };
1284 if ($@) {
1285 $self->{$prop} = ${"Git::SVN::_$option"};
1286 } else {
1287 my $v = command_oneline(qw/config --bool/,$k);
1288 $self->{$prop} = $v eq 'false' ? 0 : 1;
1290 return $self->{$prop};
1295 my (%LOCKFILES, %INDEX_FILES);
1296 END {
1297 unlink keys %LOCKFILES if %LOCKFILES;
1298 unlink keys %INDEX_FILES if %INDEX_FILES;
1301 sub resolve_local_globs {
1302 my ($url, $fetch, $glob_spec) = @_;
1303 return unless defined $glob_spec;
1304 my $ref = $glob_spec->{ref};
1305 my $path = $glob_spec->{path};
1306 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1307 next unless m#^refs/remotes/$ref->{regex}$#;
1308 my $p = $1;
1309 my $pathname = desanitize_refname($path->full_path($p));
1310 my $refname = desanitize_refname($ref->full_path($p));
1311 if (my $existing = $fetch->{$pathname}) {
1312 if ($existing ne $refname) {
1313 die "Refspec conflict:\n",
1314 "existing: refs/remotes/$existing\n",
1315 " globbed: refs/remotes/$refname\n";
1317 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1318 $u =~ s!^\Q$url\E(/|$)!! or die
1319 "refs/remotes/$refname: '$url' not found in '$u'\n";
1320 if ($pathname ne $u) {
1321 warn "W: Refspec glob conflict ",
1322 "(ref: refs/remotes/$refname):\n",
1323 "expected path: $pathname\n",
1324 " real path: $u\n",
1325 "Continuing ahead with $u\n";
1326 next;
1328 } else {
1329 $fetch->{$pathname} = $refname;
1334 sub parse_revision_argument {
1335 my ($base, $head) = @_;
1336 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1337 return ($base, $head);
1339 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1340 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1341 return ($head, $head) if ($::_revision eq 'HEAD');
1342 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1343 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1344 die "revision argument: $::_revision not understood by git-svn\n";
1347 sub fetch_all {
1348 my ($repo_id, $remotes) = @_;
1349 if (ref $repo_id) {
1350 my $gs = $repo_id;
1351 $repo_id = undef;
1352 $repo_id = $gs->{repo_id};
1354 $remotes ||= read_all_remotes();
1355 my $remote = $remotes->{$repo_id} or
1356 die "[svn-remote \"$repo_id\"] unknown\n";
1357 my $fetch = $remote->{fetch};
1358 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1359 my (@gs, @globs);
1360 my $ra = Git::SVN::Ra->new($url);
1361 my $uuid = $ra->get_uuid;
1362 my $head = $ra->get_latest_revnum;
1363 my $base = defined $fetch ? $head : 0;
1365 # read the max revs for wildcard expansion (branches/*, tags/*)
1366 foreach my $t (qw/branches tags/) {
1367 defined $remote->{$t} or next;
1368 push @globs, $remote->{$t};
1369 my $max_rev = eval { tmp_config(qw/--int --get/,
1370 "svn-remote.$repo_id.${t}-maxRev") };
1371 if (defined $max_rev && ($max_rev < $base)) {
1372 $base = $max_rev;
1373 } elsif (!defined $max_rev) {
1374 $base = 0;
1378 if ($fetch) {
1379 foreach my $p (sort keys %$fetch) {
1380 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1381 my $lr = $gs->rev_map_max;
1382 if (defined $lr) {
1383 $base = $lr if ($lr < $base);
1385 push @gs, $gs;
1389 ($base, $head) = parse_revision_argument($base, $head);
1390 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1393 sub read_all_remotes {
1394 my $r = {};
1395 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1396 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1397 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1398 $local_ref =~ s{^/}{};
1399 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1400 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1401 $r->{$1}->{url} = $2;
1402 } elsif (m!^(.+)\.(branches|tags)=
1403 (.*):refs/remotes/(.+)\s*$/!x) {
1404 my ($p, $g) = ($3, $4);
1405 my $rs = $r->{$1}->{$2} = {
1406 t => $2,
1407 remote => $1,
1408 path => Git::SVN::GlobSpec->new($p),
1409 ref => Git::SVN::GlobSpec->new($g) };
1410 if (length($rs->{ref}->{right}) != 0) {
1411 die "The '*' glob character must be the last ",
1412 "character of '$g'\n";
1419 sub init_vars {
1420 $_gc_nr = $_gc_period = 1000;
1421 if (defined $_repack || defined $_repack_flags) {
1422 warn "Repack options are obsolete; they have no effect.\n";
1426 sub verify_remotes_sanity {
1427 return unless -d $ENV{GIT_DIR};
1428 my %seen;
1429 foreach (command(qw/config -l/)) {
1430 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1431 if ($seen{$1}) {
1432 die "Remote ref refs/remote/$1 is tracked by",
1433 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1434 "Please resolve this ambiguity in ",
1435 "your git configuration file before ",
1436 "continuing\n";
1438 $seen{$1} = $_;
1443 # we allow more chars than remotes2config.sh...
1444 sub sanitize_remote_name {
1445 my ($name) = @_;
1446 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1447 $name;
1450 sub find_existing_remote {
1451 my ($url, $remotes) = @_;
1452 return undef if $no_reuse_existing;
1453 my $existing;
1454 foreach my $repo_id (keys %$remotes) {
1455 my $u = $remotes->{$repo_id}->{url} or next;
1456 next if $u ne $url;
1457 $existing = $repo_id;
1458 last;
1460 $existing;
1463 sub init_remote_config {
1464 my ($self, $url, $no_write) = @_;
1465 $url =~ s!/+$!!; # strip trailing slash
1466 my $r = read_all_remotes();
1467 my $existing = find_existing_remote($url, $r);
1468 if ($existing) {
1469 unless ($no_write) {
1470 print STDERR "Using existing ",
1471 "[svn-remote \"$existing\"]\n";
1473 $self->{repo_id} = $existing;
1474 } elsif ($_minimize_url) {
1475 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1476 $existing = find_existing_remote($min_url, $r);
1477 if ($existing) {
1478 unless ($no_write) {
1479 print STDERR "Using existing ",
1480 "[svn-remote \"$existing\"]\n";
1482 $self->{repo_id} = $existing;
1484 if ($min_url ne $url) {
1485 unless ($no_write) {
1486 print STDERR "Using higher level of URL: ",
1487 "$url => $min_url\n";
1489 my $old_path = $self->{path};
1490 $self->{path} = $url;
1491 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1492 if (length $old_path) {
1493 $self->{path} .= "/$old_path";
1495 $url = $min_url;
1498 my $orig_url;
1499 if (!$existing) {
1500 # verify that we aren't overwriting anything:
1501 $orig_url = eval {
1502 command_oneline('config', '--get',
1503 "svn-remote.$self->{repo_id}.url")
1505 if ($orig_url && ($orig_url ne $url)) {
1506 die "svn-remote.$self->{repo_id}.url already set: ",
1507 "$orig_url\nwanted to set to: $url\n";
1510 my ($xrepo_id, $xpath) = find_ref($self->refname);
1511 if (defined $xpath) {
1512 die "svn-remote.$xrepo_id.fetch already set to track ",
1513 "$xpath:refs/remotes/", $self->refname, "\n";
1515 unless ($no_write) {
1516 command_noisy('config',
1517 "svn-remote.$self->{repo_id}.url", $url);
1518 $self->{path} =~ s{^/}{};
1519 command_noisy('config', '--add',
1520 "svn-remote.$self->{repo_id}.fetch",
1521 "$self->{path}:".$self->refname);
1523 $self->{url} = $url;
1526 sub find_by_url { # repos_root and, path are optional
1527 my ($class, $full_url, $repos_root, $path) = @_;
1529 return undef unless defined $full_url;
1530 remove_username($full_url);
1531 remove_username($repos_root) if defined $repos_root;
1532 my $remotes = read_all_remotes();
1533 if (defined $full_url && defined $repos_root && !defined $path) {
1534 $path = $full_url;
1535 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1537 foreach my $repo_id (keys %$remotes) {
1538 my $u = $remotes->{$repo_id}->{url} or next;
1539 remove_username($u);
1540 next if defined $repos_root && $repos_root ne $u;
1542 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1543 foreach (qw/branches tags/) {
1544 resolve_local_globs($u, $fetch,
1545 $remotes->{$repo_id}->{$_});
1547 my $p = $path;
1548 my $rwr = rewrite_root({repo_id => $repo_id});
1549 unless (defined $p) {
1550 $p = $full_url;
1551 my $z = $u;
1552 if ($rwr) {
1553 $z = $rwr;
1555 $p =~ s#^\Q$z\E(?:/|$)## or next;
1557 foreach my $f (keys %$fetch) {
1558 next if $f ne $p;
1559 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1562 undef;
1565 sub init {
1566 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1567 my $self = _new($class, $repo_id, $ref_id, $path);
1568 if (defined $url) {
1569 $self->init_remote_config($url, $no_write);
1571 $self;
1574 sub find_ref {
1575 my ($ref_id) = @_;
1576 foreach (command(qw/config -l/)) {
1577 next unless m!^svn-remote\.(.+)\.fetch=
1578 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1579 my ($repo_id, $path, $ref) = ($1, $2, $3);
1580 if ($ref eq $ref_id) {
1581 $path = '' if ($path =~ m#^\./?#);
1582 return ($repo_id, $path);
1585 (undef, undef, undef);
1588 sub new {
1589 my ($class, $ref_id, $repo_id, $path) = @_;
1590 if (defined $ref_id && !defined $repo_id && !defined $path) {
1591 ($repo_id, $path) = find_ref($ref_id);
1592 if (!defined $repo_id) {
1593 die "Could not find a \"svn-remote.*.fetch\" key ",
1594 "in the repository configuration matching: ",
1595 "refs/remotes/$ref_id\n";
1598 my $self = _new($class, $repo_id, $ref_id, $path);
1599 if (!defined $self->{path} || !length $self->{path}) {
1600 my $fetch = command_oneline('config', '--get',
1601 "svn-remote.$repo_id.fetch",
1602 ":refs/remotes/$ref_id\$") or
1603 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1604 "\":refs/remotes/$ref_id\$\" in config\n";
1605 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1607 $self->{url} = command_oneline('config', '--get',
1608 "svn-remote.$repo_id.url") or
1609 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1610 $self->rebuild;
1611 $self;
1614 sub refname {
1615 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1617 # It cannot end with a slash /, we'll throw up on this because
1618 # SVN can't have directories with a slash in their name, either:
1619 if ($refname =~ m{/$}) {
1620 die "ref: '$refname' ends with a trailing slash, this is ",
1621 "not permitted by git nor Subversion\n";
1624 # It cannot have ASCII control character space, tilde ~, caret ^,
1625 # colon :, question-mark ?, asterisk *, space, or open bracket [
1626 # anywhere.
1628 # Additionally, % must be escaped because it is used for escaping
1629 # and we want our escaped refname to be reversible
1630 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1632 # no slash-separated component can begin with a dot .
1633 # /.* becomes /%2E*
1634 $refname =~ s{/\.}{/%2E}g;
1636 # It cannot have two consecutive dots .. anywhere
1637 # .. becomes %2E%2E
1638 $refname =~ s{\.\.}{%2E%2E}g;
1640 return $refname;
1643 sub desanitize_refname {
1644 my ($refname) = @_;
1645 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1646 return $refname;
1649 sub svm_uuid {
1650 my ($self) = @_;
1651 return $self->{svm}->{uuid} if $self->svm;
1652 $self->ra;
1653 unless ($self->{svm}) {
1654 die "SVM UUID not cached, and reading remotely failed\n";
1656 $self->{svm}->{uuid};
1659 sub svm {
1660 my ($self) = @_;
1661 return $self->{svm} if $self->{svm};
1662 my $svm;
1663 # see if we have it in our config, first:
1664 eval {
1665 my $section = "svn-remote.$self->{repo_id}";
1666 $svm = {
1667 source => tmp_config('--get', "$section.svm-source"),
1668 uuid => tmp_config('--get', "$section.svm-uuid"),
1669 replace => tmp_config('--get', "$section.svm-replace"),
1672 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1673 $self->{svm} = $svm;
1675 $self->{svm};
1678 sub _set_svm_vars {
1679 my ($self, $ra) = @_;
1680 return $ra if $self->svm;
1682 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1683 "(svm:source, svm:uuid) ",
1684 "from the following URLs:\n" );
1685 sub read_svm_props {
1686 my ($self, $ra, $path, $r) = @_;
1687 my $props = ($ra->get_dir($path, $r))[2];
1688 my $src = $props->{'svm:source'};
1689 my $uuid = $props->{'svm:uuid'};
1690 return undef if (!$src || !$uuid);
1692 chomp($src, $uuid);
1694 $uuid =~ m{^[0-9a-f\-]{30,}$}
1695 or die "doesn't look right - svm:uuid is '$uuid'\n";
1697 # the '!' is used to mark the repos_root!/relative/path
1698 $src =~ s{/?!/?}{/};
1699 $src =~ s{/+$}{}; # no trailing slashes please
1700 # username is of no interest
1701 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1703 my $replace = $ra->{url};
1704 $replace .= "/$path" if length $path;
1706 my $section = "svn-remote.$self->{repo_id}";
1707 tmp_config("$section.svm-source", $src);
1708 tmp_config("$section.svm-replace", $replace);
1709 tmp_config("$section.svm-uuid", $uuid);
1710 $self->{svm} = {
1711 source => $src,
1712 uuid => $uuid,
1713 replace => $replace
1717 my $r = $ra->get_latest_revnum;
1718 my $path = $self->{path};
1719 my %tried;
1720 while (length $path) {
1721 unless ($tried{"$self->{url}/$path"}) {
1722 return $ra if $self->read_svm_props($ra, $path, $r);
1723 $tried{"$self->{url}/$path"} = 1;
1725 $path =~ s#/?[^/]+$##;
1727 die "Path: '$path' should be ''\n" if $path ne '';
1728 return $ra if $self->read_svm_props($ra, $path, $r);
1729 $tried{"$self->{url}/$path"} = 1;
1731 if ($ra->{repos_root} eq $self->{url}) {
1732 die @err, (map { " $_\n" } keys %tried), "\n";
1735 # nope, make sure we're connected to the repository root:
1736 my $ok;
1737 my @tried_b;
1738 $path = $ra->{svn_path};
1739 $ra = Git::SVN::Ra->new($ra->{repos_root});
1740 while (length $path) {
1741 unless ($tried{"$ra->{url}/$path"}) {
1742 $ok = $self->read_svm_props($ra, $path, $r);
1743 last if $ok;
1744 $tried{"$ra->{url}/$path"} = 1;
1746 $path =~ s#/?[^/]+$##;
1748 die "Path: '$path' should be ''\n" if $path ne '';
1749 $ok ||= $self->read_svm_props($ra, $path, $r);
1750 $tried{"$ra->{url}/$path"} = 1;
1751 if (!$ok) {
1752 die @err, (map { " $_\n" } keys %tried), "\n";
1754 Git::SVN::Ra->new($self->{url});
1757 sub svnsync {
1758 my ($self) = @_;
1759 return $self->{svnsync} if $self->{svnsync};
1761 if ($self->no_metadata) {
1762 die "Can't have both 'noMetadata' and ",
1763 "'useSvnsyncProps' options set!\n";
1765 if ($self->rewrite_root) {
1766 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1767 "options set!\n";
1770 my $svnsync;
1771 # see if we have it in our config, first:
1772 eval {
1773 my $section = "svn-remote.$self->{repo_id}";
1775 my $url = tmp_config('--get', "$section.svnsync-url");
1776 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1777 die "doesn't look right - svn:sync-from-url is '$url'\n";
1779 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1780 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1781 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1783 $svnsync = { url => $url, uuid => $uuid }
1785 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1786 return $self->{svnsync} = $svnsync;
1789 my $err = "useSvnsyncProps set, but failed to read " .
1790 "svnsync property: svn:sync-from-";
1791 my $rp = $self->ra->rev_proplist(0);
1793 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1794 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1795 die "doesn't look right - svn:sync-from-url is '$url'\n";
1797 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1798 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1799 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1801 my $section = "svn-remote.$self->{repo_id}";
1802 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1803 tmp_config('--add', "$section.svnsync-url", $url);
1804 return $self->{svnsync} = { url => $url, uuid => $uuid };
1807 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1808 # remote lookup (useful for 'git svn log').
1809 sub ra_uuid {
1810 my ($self) = @_;
1811 unless ($self->{ra_uuid}) {
1812 my $key = "svn-remote.$self->{repo_id}.uuid";
1813 my $uuid = eval { tmp_config('--get', $key) };
1814 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1815 $self->{ra_uuid} = $uuid;
1816 } else {
1817 die "ra_uuid called without URL\n" unless $self->{url};
1818 $self->{ra_uuid} = $self->ra->get_uuid;
1819 tmp_config('--add', $key, $self->{ra_uuid});
1822 $self->{ra_uuid};
1825 sub _set_repos_root {
1826 my ($self, $repos_root) = @_;
1827 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1828 $repos_root ||= $self->ra->{repos_root};
1829 tmp_config($k, $repos_root);
1830 $repos_root;
1833 sub repos_root {
1834 my ($self) = @_;
1835 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1836 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1839 sub ra {
1840 my ($self) = shift;
1841 my $ra = Git::SVN::Ra->new($self->{url});
1842 $self->_set_repos_root($ra->{repos_root});
1843 if ($self->use_svm_props && !$self->{svm}) {
1844 if ($self->no_metadata) {
1845 die "Can't have both 'noMetadata' and ",
1846 "'useSvmProps' options set!\n";
1847 } elsif ($self->use_svnsync_props) {
1848 die "Can't have both 'useSvnsyncProps' and ",
1849 "'useSvmProps' options set!\n";
1851 $ra = $self->_set_svm_vars($ra);
1852 $self->{-want_revprops} = 1;
1854 $ra;
1857 sub rel_path {
1858 my ($self) = @_;
1859 my $repos_root = $self->ra->{repos_root};
1860 return $self->{path} if ($self->{url} eq $repos_root);
1861 my $url = $self->{url} .
1862 (length $self->{path} ? "/$self->{path}" : $self->{path});
1863 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1864 $url;
1867 # prop_walk(PATH, REV, SUB)
1868 # -------------------------
1869 # Recursively traverse PATH at revision REV and invoke SUB for each
1870 # directory that contains a SVN property. SUB will be invoked as
1871 # follows: &SUB(gs, path, props); where `gs' is this instance of
1872 # Git::SVN, `path' the path to the directory where the properties
1873 # `props' were found. The `path' will be relative to point of checkout,
1874 # that is, if url://repo/trunk is the current Git branch, and that
1875 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1876 # as `path' (note the trailing `/').
1877 sub prop_walk {
1878 my ($self, $path, $rev, $sub) = @_;
1880 $path =~ s#^/##;
1881 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1882 $path =~ s#^/*#/#g;
1883 my $p = $path;
1884 # Strip the irrelevant part of the path.
1885 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1886 # Ensure the path is terminated by a `/'.
1887 $p =~ s#/*$#/#;
1889 # The properties contain all the internal SVN stuff nobody
1890 # (usually) cares about.
1891 my $interesting_props = 0;
1892 foreach (keys %{$props}) {
1893 # If it doesn't start with `svn:', it must be a
1894 # user-defined property.
1895 ++$interesting_props and next if $_ !~ /^svn:/;
1896 # FIXME: Fragile, if SVN adds new public properties,
1897 # this needs to be updated.
1898 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1899 |eol-style|mime-type
1900 |externals|needs-lock)$/x;
1902 &$sub($self, $p, $props) if $interesting_props;
1904 foreach (sort keys %$dirent) {
1905 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1906 $self->prop_walk($p . $_, $rev, $sub);
1910 sub last_rev { ($_[0]->last_rev_commit)[0] }
1911 sub last_commit { ($_[0]->last_rev_commit)[1] }
1913 # returns the newest SVN revision number and newest commit SHA1
1914 sub last_rev_commit {
1915 my ($self) = @_;
1916 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1917 return ($self->{last_rev}, $self->{last_commit});
1919 my $c = ::verify_ref($self->refname.'^0');
1920 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1921 my $rev = (::cmt_metadata($c))[1];
1922 if (defined $rev) {
1923 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1924 return ($rev, $c);
1927 my $map_path = $self->map_path;
1928 unless (-e $map_path) {
1929 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1930 return (undef, undef);
1932 my ($rev, $commit) = $self->rev_map_max(1);
1933 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1934 return ($rev, $commit);
1937 sub get_fetch_range {
1938 my ($self, $min, $max) = @_;
1939 $max ||= $self->ra->get_latest_revnum;
1940 $min ||= $self->rev_map_max;
1941 (++$min, $max);
1944 sub tmp_config {
1945 my (@args) = @_;
1946 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1947 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1948 if (! -f $config && -f $old_def_config) {
1949 rename $old_def_config, $config or
1950 die "Failed rename $old_def_config => $config: $!\n";
1952 my $old_config = $ENV{GIT_CONFIG};
1953 $ENV{GIT_CONFIG} = $config;
1954 $@ = undef;
1955 my @ret = eval {
1956 unless (-f $config) {
1957 mkfile($config);
1958 open my $fh, '>', $config or
1959 die "Can't open $config: $!\n";
1960 print $fh "; This file is used internally by ",
1961 "git-svn\n" or die
1962 "Couldn't write to $config: $!\n";
1963 print $fh "; You should not have to edit it\n" or
1964 die "Couldn't write to $config: $!\n";
1965 close $fh or die "Couldn't close $config: $!\n";
1967 command('config', @args);
1969 my $err = $@;
1970 if (defined $old_config) {
1971 $ENV{GIT_CONFIG} = $old_config;
1972 } else {
1973 delete $ENV{GIT_CONFIG};
1975 die $err if $err;
1976 wantarray ? @ret : $ret[0];
1979 sub tmp_index_do {
1980 my ($self, $sub) = @_;
1981 my $old_index = $ENV{GIT_INDEX_FILE};
1982 $ENV{GIT_INDEX_FILE} = $self->{index};
1983 $@ = undef;
1984 my @ret = eval {
1985 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1986 mkpath([$dir]) unless -d $dir;
1987 &$sub;
1989 my $err = $@;
1990 if (defined $old_index) {
1991 $ENV{GIT_INDEX_FILE} = $old_index;
1992 } else {
1993 delete $ENV{GIT_INDEX_FILE};
1995 die $err if $err;
1996 wantarray ? @ret : $ret[0];
1999 sub assert_index_clean {
2000 my ($self, $treeish) = @_;
2002 $self->tmp_index_do(sub {
2003 command_noisy('read-tree', $treeish) unless -e $self->{index};
2004 my $x = command_oneline('write-tree');
2005 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2006 /^tree ($::sha1)/mo);
2007 return if $y eq $x;
2009 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2010 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2011 command_noisy('read-tree', $treeish);
2012 $x = command_oneline('write-tree');
2013 if ($y ne $x) {
2014 ::fatal "trees ($treeish) $y != $x\n",
2015 "Something is seriously wrong...";
2020 sub get_commit_parents {
2021 my ($self, $log_entry) = @_;
2022 my (%seen, @ret, @tmp);
2023 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2024 if (my $ip = $self->{inject_parents}) {
2025 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2026 push @tmp, $commit;
2029 if (my $cur = ::verify_ref($self->refname.'^0')) {
2030 push @tmp, $cur;
2032 if (my $ipd = $self->{inject_parents_dcommit}) {
2033 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2034 push @tmp, @$commit;
2037 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2038 while (my $p = shift @tmp) {
2039 next if $seen{$p};
2040 $seen{$p} = 1;
2041 push @ret, $p;
2042 # MAXPARENT is defined to 16 in commit-tree.c:
2043 last if @ret >= 16;
2045 if (@tmp) {
2046 die "r$log_entry->{revision}: No room for parents:\n\t",
2047 join("\n\t", @tmp), "\n";
2049 @ret;
2052 sub rewrite_root {
2053 my ($self) = @_;
2054 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2055 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2056 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2057 if ($rwr) {
2058 $rwr =~ s#/+$##;
2059 if ($rwr !~ m#^[a-z\+]+://#) {
2060 die "$rwr is not a valid URL (key: $k)\n";
2063 $self->{-rewrite_root} = $rwr;
2066 sub metadata_url {
2067 my ($self) = @_;
2068 ($self->rewrite_root || $self->{url}) .
2069 (length $self->{path} ? '/' . $self->{path} : '');
2072 sub full_url {
2073 my ($self) = @_;
2074 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2078 sub set_commit_header_env {
2079 my ($log_entry) = @_;
2080 my %env;
2081 foreach my $ned (qw/NAME EMAIL DATE/) {
2082 foreach my $ac (qw/AUTHOR COMMITTER/) {
2083 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2087 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2088 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2089 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2091 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2092 ? $log_entry->{commit_name}
2093 : $log_entry->{name};
2094 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2095 ? $log_entry->{commit_email}
2096 : $log_entry->{email};
2097 \%env;
2100 sub restore_commit_header_env {
2101 my ($env) = @_;
2102 foreach my $ned (qw/NAME EMAIL DATE/) {
2103 foreach my $ac (qw/AUTHOR COMMITTER/) {
2104 my $k = "GIT_${ac}_${ned}";
2105 if (defined $env->{$k}) {
2106 $ENV{$k} = $env->{$k};
2107 } else {
2108 delete $ENV{$k};
2114 sub gc {
2115 command_noisy('gc', '--auto');
2118 sub do_git_commit {
2119 my ($self, $log_entry) = @_;
2120 my $lr = $self->last_rev;
2121 if (defined $lr && $lr >= $log_entry->{revision}) {
2122 die "Last fetched revision of ", $self->refname,
2123 " was r$lr, but we are about to fetch: ",
2124 "r$log_entry->{revision}!\n";
2126 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2127 croak "$log_entry->{revision} = $c already exists! ",
2128 "Why are we refetching it?\n";
2130 my $old_env = set_commit_header_env($log_entry);
2131 my $tree = $log_entry->{tree};
2132 if (!defined $tree) {
2133 $tree = $self->tmp_index_do(sub {
2134 command_oneline('write-tree') });
2136 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2138 my @exec = ('git-commit-tree', $tree);
2139 foreach ($self->get_commit_parents($log_entry)) {
2140 push @exec, '-p', $_;
2142 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2143 or croak $!;
2144 print $msg_fh $log_entry->{log} or croak $!;
2145 restore_commit_header_env($old_env);
2146 unless ($self->no_metadata) {
2147 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2148 or croak $!;
2150 $msg_fh->flush == 0 or croak $!;
2151 close $msg_fh or croak $!;
2152 chomp(my $commit = do { local $/; <$out_fh> });
2153 close $out_fh or croak $!;
2154 waitpid $pid, 0;
2155 croak $? if $?;
2156 if ($commit !~ /^$::sha1$/o) {
2157 die "Failed to commit, invalid sha1: $commit\n";
2160 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2162 $self->{last_rev} = $log_entry->{revision};
2163 $self->{last_commit} = $commit;
2164 print "r$log_entry->{revision}";
2165 if (defined $log_entry->{svm_revision}) {
2166 print " (\@$log_entry->{svm_revision})";
2167 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2168 0, $self->svm_uuid);
2170 print " = $commit ($self->{ref_id})\n";
2171 if (--$_gc_nr == 0) {
2172 $_gc_nr = $_gc_period;
2173 gc();
2175 return $commit;
2178 sub match_paths {
2179 my ($self, $paths, $r) = @_;
2180 return 1 if $self->{path} eq '';
2181 if (my $path = $paths->{"/$self->{path}"}) {
2182 return ($path->{action} eq 'D') ? 0 : 1;
2184 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2185 if (grep /$self->{path_regex}/, keys %$paths) {
2186 return 1;
2188 my $c = '';
2189 foreach (split m#/#, $self->{path}) {
2190 $c .= "/$_";
2191 next unless ($paths->{$c} &&
2192 ($paths->{$c}->{action} =~ /^[AR]$/));
2193 if ($self->ra->check_path($self->{path}, $r) ==
2194 $SVN::Node::dir) {
2195 return 1;
2198 return 0;
2201 sub find_parent_branch {
2202 my ($self, $paths, $rev) = @_;
2203 return undef unless $self->follow_parent;
2204 unless (defined $paths) {
2205 my $err_handler = $SVN::Error::handler;
2206 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2207 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2208 $paths =
2209 Git::SVN::Ra::dup_changed_paths($_[0]) });
2210 $SVN::Error::handler = $err_handler;
2212 return undef unless defined $paths;
2214 # look for a parent from another branch:
2215 my @b_path_components = split m#/#, $self->rel_path;
2216 my @a_path_components;
2217 my $i;
2218 while (@b_path_components) {
2219 $i = $paths->{'/'.join('/', @b_path_components)};
2220 last if $i && defined $i->{copyfrom_path};
2221 unshift(@a_path_components, pop(@b_path_components));
2223 return undef unless defined $i && defined $i->{copyfrom_path};
2224 my $branch_from = $i->{copyfrom_path};
2225 if (@a_path_components) {
2226 print STDERR "branch_from: $branch_from => ";
2227 $branch_from .= '/'.join('/', @a_path_components);
2228 print STDERR $branch_from, "\n";
2230 my $r = $i->{copyfrom_rev};
2231 my $repos_root = $self->ra->{repos_root};
2232 my $url = $self->ra->{url};
2233 my $new_url = $repos_root . $branch_from;
2234 print STDERR "Found possible branch point: ",
2235 "$new_url => ", $self->full_url, ", $r\n";
2236 $branch_from =~ s#^/##;
2237 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2238 unless ($gs) {
2239 my $ref_id = $self->{ref_id};
2240 $ref_id =~ s/\@\d+$//;
2241 $ref_id .= "\@$r";
2242 # just grow a tail if we're not unique enough :x
2243 $ref_id .= '-' while find_ref($ref_id);
2244 print STDERR "Initializing parent: $ref_id\n";
2245 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2246 if ($u =~ s#^\Q$url\E(/|$)##) {
2247 $p = $u;
2248 $u = $url;
2249 $repo_id = $self->{repo_id};
2251 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2253 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2254 if (!defined $r0 || !defined $parent) {
2255 my ($base, $head) = parse_revision_argument(0, $r);
2256 if ($base <= $r) {
2257 $gs->fetch($base, $r);
2259 ($r0, $parent) = $gs->last_rev_commit;
2261 if (defined $r0 && defined $parent) {
2262 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2263 my $ed;
2264 if ($self->ra->can_do_switch) {
2265 $self->assert_index_clean($parent);
2266 print STDERR "Following parent with do_switch\n";
2267 # do_switch works with svn/trunk >= r22312, but that
2268 # is not included with SVN 1.4.3 (the latest version
2269 # at the moment), so we can't rely on it
2270 $self->{last_commit} = $parent;
2271 $ed = SVN::Git::Fetcher->new($self);
2272 $gs->ra->gs_do_switch($r0, $rev, $gs,
2273 $self->full_url, $ed)
2274 or die "SVN connection failed somewhere...\n";
2275 } elsif ($self->ra->trees_match($new_url, $r0,
2276 $self->full_url, $rev)) {
2277 print STDERR "Trees match:\n",
2278 " $new_url\@$r0\n",
2279 " ${\$self->full_url}\@$rev\n",
2280 "Following parent with no changes\n";
2281 $self->tmp_index_do(sub {
2282 command_noisy('read-tree', $parent);
2284 $self->{last_commit} = $parent;
2285 } else {
2286 print STDERR "Following parent with do_update\n";
2287 $ed = SVN::Git::Fetcher->new($self);
2288 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2289 or die "SVN connection failed somewhere...\n";
2291 print STDERR "Successfully followed parent\n";
2292 return $self->make_log_entry($rev, [$parent], $ed);
2294 return undef;
2297 sub do_fetch {
2298 my ($self, $paths, $rev) = @_;
2299 my $ed;
2300 my ($last_rev, @parents);
2301 if (my $lc = $self->last_commit) {
2302 # we can have a branch that was deleted, then re-added
2303 # under the same name but copied from another path, in
2304 # which case we'll have multiple parents (we don't
2305 # want to break the original ref, nor lose copypath info):
2306 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2307 push @{$log_entry->{parents}}, $lc;
2308 return $log_entry;
2310 $ed = SVN::Git::Fetcher->new($self);
2311 $last_rev = $self->{last_rev};
2312 $ed->{c} = $lc;
2313 @parents = ($lc);
2314 } else {
2315 $last_rev = $rev;
2316 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2317 return $log_entry;
2319 $ed = SVN::Git::Fetcher->new($self);
2321 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2322 die "SVN connection failed somewhere...\n";
2324 $self->make_log_entry($rev, \@parents, $ed);
2327 sub get_untracked {
2328 my ($self, $ed) = @_;
2329 my @out;
2330 my $h = $ed->{empty};
2331 foreach (sort keys %$h) {
2332 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2333 push @out, " $act: " . uri_encode($_);
2334 warn "W: $act: $_\n";
2336 foreach my $t (qw/dir_prop file_prop/) {
2337 $h = $ed->{$t} or next;
2338 foreach my $path (sort keys %$h) {
2339 my $ppath = $path eq '' ? '.' : $path;
2340 foreach my $prop (sort keys %{$h->{$path}}) {
2341 next if $SKIP_PROP{$prop};
2342 my $v = $h->{$path}->{$prop};
2343 my $t_ppath_prop = "$t: " .
2344 uri_encode($ppath) . ' ' .
2345 uri_encode($prop);
2346 if (defined $v) {
2347 push @out, " +$t_ppath_prop " .
2348 uri_encode($v);
2349 } else {
2350 push @out, " -$t_ppath_prop";
2355 foreach my $t (qw/absent_file absent_directory/) {
2356 $h = $ed->{$t} or next;
2357 foreach my $parent (sort keys %$h) {
2358 foreach my $path (sort @{$h->{$parent}}) {
2359 push @out, " $t: " .
2360 uri_encode("$parent/$path");
2361 warn "W: $t: $parent/$path ",
2362 "Insufficient permissions?\n";
2366 \@out;
2369 sub parse_svn_date {
2370 my $date = shift || return '+0000 1970-01-01 00:00:00';
2371 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2372 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2373 croak "Unable to parse date: $date\n";
2374 "+0000 $Y-$m-$d $H:$M:$S";
2377 sub check_author {
2378 my ($author) = @_;
2379 if (!defined $author || length $author == 0) {
2380 $author = '(no author)';
2381 } elsif (defined $::_authors && ! defined $::users{$author}) {
2382 die "Author: $author not defined in $::_authors file\n";
2384 $author;
2387 sub make_log_entry {
2388 my ($self, $rev, $parents, $ed) = @_;
2389 my $untracked = $self->get_untracked($ed);
2391 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2392 print $un "r$rev\n" or croak $!;
2393 print $un $_, "\n" foreach @$untracked;
2394 my %log_entry = ( parents => $parents || [], revision => $rev,
2395 log => '');
2397 my $headrev;
2398 my $logged = delete $self->{logged_rev_props};
2399 if (!$logged || $self->{-want_revprops}) {
2400 my $rp = $self->ra->rev_proplist($rev);
2401 foreach (sort keys %$rp) {
2402 my $v = $rp->{$_};
2403 if (/^svn:(author|date|log)$/) {
2404 $log_entry{$1} = $v;
2405 } elsif ($_ eq 'svm:headrev') {
2406 $headrev = $v;
2407 } else {
2408 print $un " rev_prop: ", uri_encode($_), ' ',
2409 uri_encode($v), "\n";
2412 } else {
2413 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2415 close $un or croak $!;
2417 $log_entry{date} = parse_svn_date($log_entry{date});
2418 $log_entry{log} .= "\n";
2419 my $author = $log_entry{author} = check_author($log_entry{author});
2420 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2421 : ($author, undef);
2423 my ($commit_name, $commit_email) = ($name, $email);
2424 if ($_use_log_author) {
2425 my $name_field;
2426 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2427 $name_field = $1;
2428 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2429 $name_field = $1;
2431 if (!defined $name_field) {
2432 if (!defined $email) {
2433 $email = $name;
2435 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2436 ($name, $email) = ($1, $2);
2437 } elsif ($name_field =~ /(.*)@/) {
2438 ($name, $email) = ($1, $name_field);
2439 } else {
2440 ($name, $email) = ($name_field, $name_field);
2443 if (defined $headrev && $self->use_svm_props) {
2444 if ($self->rewrite_root) {
2445 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2446 "options set!\n";
2448 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2449 # we don't want "SVM: initializing mirror for junk" ...
2450 return undef if $r == 0;
2451 my $svm = $self->svm;
2452 if ($uuid ne $svm->{uuid}) {
2453 die "UUID mismatch on SVM path:\n",
2454 "expected: $svm->{uuid}\n",
2455 " got: $uuid\n";
2457 my $full_url = $self->full_url;
2458 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2459 die "Failed to replace '$svm->{replace}' with ",
2460 "'$svm->{source}' in $full_url\n";
2461 # throw away username for storing in records
2462 remove_username($full_url);
2463 $log_entry{metadata} = "$full_url\@$r $uuid";
2464 $log_entry{svm_revision} = $r;
2465 $email ||= "$author\@$uuid";
2466 $commit_email ||= "$author\@$uuid";
2467 } elsif ($self->use_svnsync_props) {
2468 my $full_url = $self->svnsync->{url};
2469 $full_url .= "/$self->{path}" if length $self->{path};
2470 remove_username($full_url);
2471 my $uuid = $self->svnsync->{uuid};
2472 $log_entry{metadata} = "$full_url\@$rev $uuid";
2473 $email ||= "$author\@$uuid";
2474 $commit_email ||= "$author\@$uuid";
2475 } else {
2476 my $url = $self->metadata_url;
2477 remove_username($url);
2478 $log_entry{metadata} = "$url\@$rev " .
2479 $self->ra->get_uuid;
2480 $email ||= "$author\@" . $self->ra->get_uuid;
2481 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2483 $log_entry{name} = $name;
2484 $log_entry{email} = $email;
2485 $log_entry{commit_name} = $commit_name;
2486 $log_entry{commit_email} = $commit_email;
2487 \%log_entry;
2490 sub fetch {
2491 my ($self, $min_rev, $max_rev, @parents) = @_;
2492 my ($last_rev, $last_commit) = $self->last_rev_commit;
2493 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2494 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2497 sub set_tree_cb {
2498 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2499 $self->{inject_parents} = { $rev => $tree };
2500 $self->fetch(undef, undef);
2503 sub set_tree {
2504 my ($self, $tree) = (shift, shift);
2505 my $log_entry = ::get_commit_entry($tree);
2506 unless ($self->{last_rev}) {
2507 fatal("Must have an existing revision to commit");
2509 my %ed_opts = ( r => $self->{last_rev},
2510 log => $log_entry->{log},
2511 ra => $self->ra,
2512 tree_a => $self->{last_commit},
2513 tree_b => $tree,
2514 editor_cb => sub {
2515 $self->set_tree_cb($log_entry, $tree, @_) },
2516 svn_path => $self->{path} );
2517 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2518 print "No changes\nr$self->{last_rev} = $tree\n";
2522 sub rebuild_from_rev_db {
2523 my ($self, $path) = @_;
2524 my $r = -1;
2525 open my $fh, '<', $path or croak "open: $!";
2526 binmode $fh or croak "binmode: $!";
2527 while (<$fh>) {
2528 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2529 chomp($_);
2530 ++$r;
2531 next if $_ eq ('0' x 40);
2532 $self->rev_map_set($r, $_);
2533 print "r$r = $_\n";
2535 close $fh or croak "close: $!";
2536 unlink $path or croak "unlink: $!";
2539 sub rebuild {
2540 my ($self) = @_;
2541 my $map_path = $self->map_path;
2542 return if (-e $map_path && ! -z $map_path);
2543 return unless ::verify_ref($self->refname.'^0');
2544 if ($self->use_svm_props || $self->no_metadata) {
2545 my $rev_db = $self->rev_db_path;
2546 $self->rebuild_from_rev_db($rev_db);
2547 if ($self->use_svm_props) {
2548 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2549 $self->rebuild_from_rev_db($svm_rev_db);
2551 $self->unlink_rev_db_symlink;
2552 return;
2554 print "Rebuilding $map_path ...\n";
2555 my ($log, $ctx) =
2556 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2557 $self->refname, '--');
2558 my $full_url = $self->full_url;
2559 remove_username($full_url);
2560 my $svn_uuid = $self->ra_uuid;
2561 my $c;
2562 while (<$log>) {
2563 if ( m{^commit ($::sha1)$} ) {
2564 $c = $1;
2565 next;
2567 next unless s{^\s*(git-svn-id:)}{$1};
2568 my ($url, $rev, $uuid) = ::extract_metadata($_);
2569 remove_username($url);
2571 # ignore merges (from set-tree)
2572 next if (!defined $rev || !$uuid);
2574 # if we merged or otherwise started elsewhere, this is
2575 # how we break out of it
2576 if (($uuid ne $svn_uuid) ||
2577 ($full_url && $url && ($url ne $full_url))) {
2578 next;
2581 $self->rev_map_set($rev, $c);
2582 print "r$rev = $c\n";
2584 command_close_pipe($log, $ctx);
2585 print "Done rebuilding $map_path\n";
2586 my $rev_db_path = $self->rev_db_path;
2587 if (-f $self->rev_db_path) {
2588 unlink $self->rev_db_path or croak "unlink: $!";
2590 $self->unlink_rev_db_symlink;
2593 # rev_map:
2594 # Tie::File seems to be prone to offset errors if revisions get sparse,
2595 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2596 # one of my favorite modules is out :< Next up would be one of the DBM
2597 # modules, but I'm not sure which is most portable...
2599 # This is the replacement for the rev_db format, which was too big
2600 # and inefficient for large repositories with a lot of sparse history
2601 # (mainly tags)
2603 # The format is this:
2604 # - 24 bytes for every record,
2605 # * 4 bytes for the integer representing an SVN revision number
2606 # * 20 bytes representing the sha1 of a git commit
2607 # - No empty padding records like the old format
2608 # (except the last record, which can be overwritten)
2609 # - new records are written append-only since SVN revision numbers
2610 # increase monotonically
2611 # - lookups on SVN revision number are done via a binary search
2612 # - Piping the file to xxd -c24 is a good way of dumping it for
2613 # viewing or editing (piped back through xxd -r), should the need
2614 # ever arise.
2615 # - The last record can be padding revision with an all-zero sha1
2616 # This is used to optimize fetch performance when using multiple
2617 # "fetch" directives in .git/config
2619 # These files are disposable unless noMetadata or useSvmProps is set
2621 sub _rev_map_set {
2622 my ($fh, $rev, $commit) = @_;
2624 binmode $fh or croak "binmode: $!";
2625 my $size = (stat($fh))[7];
2626 ($size % 24) == 0 or croak "inconsistent size: $size";
2628 my $wr_offset = 0;
2629 if ($size > 0) {
2630 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2631 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2632 $read == 24 or croak "read only $read bytes (!= 24)";
2633 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2634 if ($last_commit eq ('0' x40)) {
2635 if ($size >= 48) {
2636 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2637 $read = sysread($fh, $buf, 24) or
2638 croak "read: $!";
2639 $read == 24 or
2640 croak "read only $read bytes (!= 24)";
2641 ($last_rev, $last_commit) =
2642 unpack(rev_map_fmt, $buf);
2643 if ($last_commit eq ('0' x40)) {
2644 croak "inconsistent .rev_map\n";
2647 if ($last_rev >= $rev) {
2648 croak "last_rev is higher!: $last_rev >= $rev";
2650 $wr_offset = -24;
2653 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2654 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2655 croak "write: $!";
2658 sub mkfile {
2659 my ($path) = @_;
2660 unless (-e $path) {
2661 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2662 mkpath([$dir]) unless -d $dir;
2663 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2664 close $fh or die "Couldn't close (create) $path: $!\n";
2668 sub rev_map_set {
2669 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2670 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2671 my $db = $self->map_path($uuid);
2672 my $db_lock = "$db.lock";
2673 my $sig;
2674 if ($update_ref) {
2675 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2676 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2678 mkfile($db);
2680 $LOCKFILES{$db_lock} = 1;
2681 my $sync;
2682 # both of these options make our .rev_db file very, very important
2683 # and we can't afford to lose it because rebuild() won't work
2684 if ($self->use_svm_props || $self->no_metadata) {
2685 $sync = 1;
2686 copy($db, $db_lock) or die "rev_map_set(@_): ",
2687 "Failed to copy: ",
2688 "$db => $db_lock ($!)\n";
2689 } else {
2690 rename $db, $db_lock or die "rev_map_set(@_): ",
2691 "Failed to rename: ",
2692 "$db => $db_lock ($!)\n";
2695 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2696 or croak "Couldn't open $db_lock: $!\n";
2697 _rev_map_set($fh, $rev, $commit);
2698 if ($sync) {
2699 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2700 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2702 close $fh or croak $!;
2703 if ($update_ref) {
2704 $_head = $self;
2705 command_noisy('update-ref', '-m', "r$rev",
2706 $self->refname, $commit);
2708 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2709 "$db_lock => $db ($!)\n";
2710 delete $LOCKFILES{$db_lock};
2711 if ($update_ref) {
2712 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2713 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2714 kill $sig, $$ if defined $sig;
2718 # If want_commit, this will return an array of (rev, commit) where
2719 # commit _must_ be a valid commit in the archive.
2720 # Otherwise, it'll return the max revision (whether or not the
2721 # commit is valid or just a 0x40 placeholder).
2722 sub rev_map_max {
2723 my ($self, $want_commit) = @_;
2724 $self->rebuild;
2725 my $map_path = $self->map_path;
2726 stat $map_path or return $want_commit ? (0, undef) : 0;
2727 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2728 binmode $fh or croak "binmode: $!";
2729 my $size = (stat($fh))[7];
2730 ($size % 24) == 0 or croak "inconsistent size: $size";
2732 if ($size == 0) {
2733 close $fh or croak "close: $!";
2734 return $want_commit ? (0, undef) : 0;
2737 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2738 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2739 my ($r, $c) = unpack(rev_map_fmt, $buf);
2740 if ($want_commit && $c eq ('0' x40)) {
2741 if ($size < 48) {
2742 return $want_commit ? (0, undef) : 0;
2744 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2745 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2746 ($r, $c) = unpack(rev_map_fmt, $buf);
2747 if ($c eq ('0'x40)) {
2748 croak "Penultimate record is all-zeroes in $map_path";
2751 close $fh or croak "close: $!";
2752 $want_commit ? ($r, $c) : $r;
2755 sub rev_map_get {
2756 my ($self, $rev, $uuid) = @_;
2757 my $map_path = $self->map_path($uuid);
2758 return undef unless -e $map_path;
2760 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2761 binmode $fh or croak "binmode: $!";
2762 my $size = (stat($fh))[7];
2763 ($size % 24) == 0 or croak "inconsistent size: $size";
2765 if ($size == 0) {
2766 close $fh or croak "close: $fh";
2767 return undef;
2770 my ($l, $u) = (0, $size - 24);
2771 my ($r, $c, $buf);
2773 while ($l <= $u) {
2774 my $i = int(($l/24 + $u/24) / 2) * 24;
2775 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2776 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2777 my ($r, $c) = unpack('NH40', $buf);
2779 if ($r < $rev) {
2780 $l = $i + 24;
2781 } elsif ($r > $rev) {
2782 $u = $i - 24;
2783 } else { # $r == $rev
2784 close($fh) or croak "close: $!";
2785 return $c eq ('0' x 40) ? undef : $c;
2788 close($fh) or croak "close: $!";
2789 undef;
2792 # Finds the first svn revision that exists on (if $eq_ok is true) or
2793 # before $rev for the current branch. It will not search any lower
2794 # than $min_rev. Returns the git commit hash and svn revision number
2795 # if found, else (undef, undef).
2796 sub find_rev_before {
2797 my ($self, $rev, $eq_ok, $min_rev) = @_;
2798 --$rev unless $eq_ok;
2799 $min_rev ||= 1;
2800 while ($rev >= $min_rev) {
2801 if (my $c = $self->rev_map_get($rev)) {
2802 return ($rev, $c);
2804 --$rev;
2806 return (undef, undef);
2809 # Finds the first svn revision that exists on (if $eq_ok is true) or
2810 # after $rev for the current branch. It will not search any higher
2811 # than $max_rev. Returns the git commit hash and svn revision number
2812 # if found, else (undef, undef).
2813 sub find_rev_after {
2814 my ($self, $rev, $eq_ok, $max_rev) = @_;
2815 ++$rev unless $eq_ok;
2816 $max_rev ||= $self->rev_map_max;
2817 while ($rev <= $max_rev) {
2818 if (my $c = $self->rev_map_get($rev)) {
2819 return ($rev, $c);
2821 ++$rev;
2823 return (undef, undef);
2826 sub _new {
2827 my ($class, $repo_id, $ref_id, $path) = @_;
2828 unless (defined $repo_id && length $repo_id) {
2829 $repo_id = $Git::SVN::default_repo_id;
2831 unless (defined $ref_id && length $ref_id) {
2832 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2834 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2835 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2836 $_[3] = $path = '' unless (defined $path);
2837 mkpath(["$ENV{GIT_DIR}/svn"]);
2838 bless {
2839 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2840 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2841 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2844 # for read-only access of old .rev_db formats
2845 sub unlink_rev_db_symlink {
2846 my ($self) = @_;
2847 my $link = $self->rev_db_path;
2848 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2849 if (-l $link) {
2850 unlink $link or croak "unlink: $link failed!";
2854 sub rev_db_path {
2855 my ($self, $uuid) = @_;
2856 my $db_path = $self->map_path($uuid);
2857 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2858 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2859 $db_path;
2862 # the new replacement for .rev_db
2863 sub map_path {
2864 my ($self, $uuid) = @_;
2865 $uuid ||= $self->ra_uuid;
2866 "$self->{map_root}.$uuid";
2869 sub uri_encode {
2870 my ($f) = @_;
2871 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2875 sub remove_username {
2876 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2879 package Git::SVN::Prompt;
2880 use strict;
2881 use warnings;
2882 require SVN::Core;
2883 use vars qw/$_no_auth_cache $_username/;
2885 sub simple {
2886 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2887 $may_save = undef if $_no_auth_cache;
2888 $default_username = $_username if defined $_username;
2889 if (defined $default_username && length $default_username) {
2890 if (defined $realm && length $realm) {
2891 print STDERR "Authentication realm: $realm\n";
2892 STDERR->flush;
2894 $cred->username($default_username);
2895 } else {
2896 username($cred, $realm, $may_save, $pool);
2898 $cred->password(_read_password("Password for '" .
2899 $cred->username . "': ", $realm));
2900 $cred->may_save($may_save);
2901 $SVN::_Core::SVN_NO_ERROR;
2904 sub ssl_server_trust {
2905 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2906 $may_save = undef if $_no_auth_cache;
2907 print STDERR "Error validating server certificate for '$realm':\n";
2909 no warnings 'once';
2910 # All variables SVN::Auth::SSL::* are used only once,
2911 # so we're shutting up Perl warnings about this.
2912 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2913 print STDERR " - The certificate is not issued ",
2914 "by a trusted authority. Use the\n",
2915 " fingerprint to validate ",
2916 "the certificate manually!\n";
2918 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2919 print STDERR " - The certificate hostname ",
2920 "does not match.\n";
2922 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2923 print STDERR " - The certificate is not yet valid.\n";
2925 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2926 print STDERR " - The certificate has expired.\n";
2928 if ($failures & $SVN::Auth::SSL::OTHER) {
2929 print STDERR " - The certificate has ",
2930 "an unknown error.\n";
2932 } # no warnings 'once'
2933 printf STDERR
2934 "Certificate information:\n".
2935 " - Hostname: %s\n".
2936 " - Valid: from %s until %s\n".
2937 " - Issuer: %s\n".
2938 " - Fingerprint: %s\n",
2939 map $cert_info->$_, qw(hostname valid_from valid_until
2940 issuer_dname fingerprint);
2941 my $choice;
2942 prompt:
2943 print STDERR $may_save ?
2944 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2945 "(R)eject or accept (t)emporarily? ";
2946 STDERR->flush;
2947 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2948 if ($choice =~ /^t$/i) {
2949 $cred->may_save(undef);
2950 } elsif ($choice =~ /^r$/i) {
2951 return -1;
2952 } elsif ($may_save && $choice =~ /^p$/i) {
2953 $cred->may_save($may_save);
2954 } else {
2955 goto prompt;
2957 $cred->accepted_failures($failures);
2958 $SVN::_Core::SVN_NO_ERROR;
2961 sub ssl_client_cert {
2962 my ($cred, $realm, $may_save, $pool) = @_;
2963 $may_save = undef if $_no_auth_cache;
2964 print STDERR "Client certificate filename: ";
2965 STDERR->flush;
2966 chomp(my $filename = <STDIN>);
2967 $cred->cert_file($filename);
2968 $cred->may_save($may_save);
2969 $SVN::_Core::SVN_NO_ERROR;
2972 sub ssl_client_cert_pw {
2973 my ($cred, $realm, $may_save, $pool) = @_;
2974 $may_save = undef if $_no_auth_cache;
2975 $cred->password(_read_password("Password: ", $realm));
2976 $cred->may_save($may_save);
2977 $SVN::_Core::SVN_NO_ERROR;
2980 sub username {
2981 my ($cred, $realm, $may_save, $pool) = @_;
2982 $may_save = undef if $_no_auth_cache;
2983 if (defined $realm && length $realm) {
2984 print STDERR "Authentication realm: $realm\n";
2986 my $username;
2987 if (defined $_username) {
2988 $username = $_username;
2989 } else {
2990 print STDERR "Username: ";
2991 STDERR->flush;
2992 chomp($username = <STDIN>);
2994 $cred->username($username);
2995 $cred->may_save($may_save);
2996 $SVN::_Core::SVN_NO_ERROR;
2999 sub _read_password {
3000 my ($prompt, $realm) = @_;
3001 print STDERR $prompt;
3002 STDERR->flush;
3003 require Term::ReadKey;
3004 Term::ReadKey::ReadMode('noecho');
3005 my $password = '';
3006 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3007 last if $key =~ /[\012\015]/; # \n\r
3008 $password .= $key;
3010 Term::ReadKey::ReadMode('restore');
3011 print STDERR "\n";
3012 STDERR->flush;
3013 $password;
3016 package SVN::Git::Fetcher;
3017 use vars qw/@ISA/;
3018 use strict;
3019 use warnings;
3020 use Carp qw/croak/;
3021 use IO::File qw//;
3023 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3024 sub new {
3025 my ($class, $git_svn) = @_;
3026 my $self = SVN::Delta::Editor->new;
3027 bless $self, $class;
3028 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3029 $self->{empty} = {};
3030 $self->{dir_prop} = {};
3031 $self->{file_prop} = {};
3032 $self->{absent_dir} = {};
3033 $self->{absent_file} = {};
3034 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3035 $self;
3038 sub set_path_strip {
3039 my ($self, $path) = @_;
3040 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3043 sub open_root {
3044 { path => '' };
3047 sub open_directory {
3048 my ($self, $path, $pb, $rev) = @_;
3049 { path => $path };
3052 sub git_path {
3053 my ($self, $path) = @_;
3054 if ($self->{path_strip}) {
3055 $path =~ s!$self->{path_strip}!! or
3056 die "Failed to strip path '$path' ($self->{path_strip})\n";
3058 $path;
3061 sub delete_entry {
3062 my ($self, $path, $rev, $pb) = @_;
3064 my $gpath = $self->git_path($path);
3065 return undef if ($gpath eq '');
3067 # remove entire directories.
3068 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3069 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3070 -r --name-only -z/,
3071 $self->{c}, '--', $gpath);
3072 local $/ = "\0";
3073 while (<$ls>) {
3074 chomp;
3075 $self->{gii}->remove($_);
3076 print "\tD\t$_\n" unless $::_q;
3078 print "\tD\t$gpath/\n" unless $::_q;
3079 command_close_pipe($ls, $ctx);
3080 $self->{empty}->{$path} = 0
3081 } else {
3082 $self->{gii}->remove($gpath);
3083 print "\tD\t$gpath\n" unless $::_q;
3085 undef;
3088 sub open_file {
3089 my ($self, $path, $pb, $rev) = @_;
3090 my $gpath = $self->git_path($path);
3091 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3092 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3093 unless (defined $mode && defined $blob) {
3094 die "$path was not found in commit $self->{c} (r$rev)\n";
3096 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3097 pool => SVN::Pool->new, action => 'M' };
3100 sub add_file {
3101 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3102 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3103 delete $self->{empty}->{$dir};
3104 { path => $path, mode_a => 100644, mode_b => 100644,
3105 pool => SVN::Pool->new, action => 'A' };
3108 sub add_directory {
3109 my ($self, $path, $cp_path, $cp_rev) = @_;
3110 my $gpath = $self->git_path($path);
3111 if ($gpath eq '') {
3112 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3113 -r --name-only -z/,
3114 $self->{c});
3115 local $/ = "\0";
3116 while (<$ls>) {
3117 chomp;
3118 $self->{gii}->remove($_);
3119 print "\tD\t$_\n" unless $::_q;
3121 command_close_pipe($ls, $ctx);
3122 $self->{empty}->{$path} = 0;
3124 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3125 delete $self->{empty}->{$dir};
3126 $self->{empty}->{$path} = 1;
3127 { path => $path };
3130 sub change_dir_prop {
3131 my ($self, $db, $prop, $value) = @_;
3132 $self->{dir_prop}->{$db->{path}} ||= {};
3133 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3134 undef;
3137 sub absent_directory {
3138 my ($self, $path, $pb) = @_;
3139 $self->{absent_dir}->{$pb->{path}} ||= [];
3140 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3141 undef;
3144 sub absent_file {
3145 my ($self, $path, $pb) = @_;
3146 $self->{absent_file}->{$pb->{path}} ||= [];
3147 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3148 undef;
3151 sub change_file_prop {
3152 my ($self, $fb, $prop, $value) = @_;
3153 if ($prop eq 'svn:executable') {
3154 if ($fb->{mode_b} != 120000) {
3155 $fb->{mode_b} = defined $value ? 100755 : 100644;
3157 } elsif ($prop eq 'svn:special') {
3158 $fb->{mode_b} = defined $value ? 120000 : 100644;
3159 } else {
3160 $self->{file_prop}->{$fb->{path}} ||= {};
3161 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3163 undef;
3166 sub apply_textdelta {
3167 my ($self, $fb, $exp) = @_;
3168 my $fh = IO::File->new_tmpfile;
3169 $fh->autoflush(1);
3170 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3171 # (but $base does not,) so dup() it for reading in close_file
3172 open my $dup, '<&', $fh or croak $!;
3173 my $base = IO::File->new_tmpfile;
3174 $base->autoflush(1);
3175 if ($fb->{blob}) {
3176 defined (my $pid = fork) or croak $!;
3177 if (!$pid) {
3178 open STDOUT, '>&', $base or croak $!;
3179 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
3180 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
3182 waitpid $pid, 0;
3183 croak $? if $?;
3185 if (defined $exp) {
3186 seek $base, 0, 0 or croak $!;
3187 my $got = ::md5sum($base);
3188 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3189 "expected: $exp\n",
3190 " got: $got\n" if ($got ne $exp);
3193 seek $base, 0, 0 or croak $!;
3194 $fb->{fh} = $dup;
3195 $fb->{base} = $base;
3196 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3199 sub close_file {
3200 my ($self, $fb, $exp) = @_;
3201 my $hash;
3202 my $path = $self->git_path($fb->{path});
3203 if (my $fh = $fb->{fh}) {
3204 if (defined $exp) {
3205 seek($fh, 0, 0) or croak $!;
3206 my $got = ::md5sum($fh);
3207 if ($got ne $exp) {
3208 die "Checksum mismatch: $path\n",
3209 "expected: $exp\n got: $got\n";
3212 sysseek($fh, 0, 0) or croak $!;
3213 if ($fb->{mode_b} == 120000) {
3214 eval {
3215 sysread($fh, my $buf, 5) == 5 or croak $!;
3216 $buf eq 'link ' or die "$path has mode 120000",
3217 " but is not a link";
3219 if ($@) {
3220 warn "$@\n";
3221 sysseek($fh, 0, 0) or croak $!;
3224 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3225 if (!$pid) {
3226 open STDIN, '<&', $fh or croak $!;
3227 exec qw/git-hash-object -w --stdin/ or croak $!;
3229 chomp($hash = do { local $/; <$out> });
3230 close $out or croak $!;
3231 close $fh or croak $!;
3232 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3233 close $fb->{base} or croak $!;
3234 } else {
3235 $hash = $fb->{blob} or die "no blob information\n";
3237 $fb->{pool}->clear;
3238 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3239 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3240 undef;
3243 sub abort_edit {
3244 my $self = shift;
3245 $self->{nr} = $self->{gii}->{nr};
3246 delete $self->{gii};
3247 $self->SUPER::abort_edit(@_);
3250 sub close_edit {
3251 my $self = shift;
3252 $self->{git_commit_ok} = 1;
3253 $self->{nr} = $self->{gii}->{nr};
3254 delete $self->{gii};
3255 $self->SUPER::close_edit(@_);
3258 package SVN::Git::Editor;
3259 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3260 use strict;
3261 use warnings;
3262 use Carp qw/croak/;
3263 use IO::File;
3265 sub new {
3266 my ($class, $opts) = @_;
3267 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3268 die "$_ required!\n" unless (defined $opts->{$_});
3271 my $pool = SVN::Pool->new;
3272 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3273 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3274 $opts->{r}, $mods);
3276 # $opts->{ra} functions should not be used after this:
3277 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3278 $opts->{editor_cb}, $pool);
3279 my $self = SVN::Delta::Editor->new(@ce, $pool);
3280 bless $self, $class;
3281 foreach (qw/svn_path r tree_a tree_b/) {
3282 $self->{$_} = $opts->{$_};
3284 $self->{url} = $opts->{ra}->{url};
3285 $self->{mods} = $mods;
3286 $self->{types} = $types;
3287 $self->{pool} = $pool;
3288 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3289 $self->{rm} = { };
3290 $self->{path_prefix} = length $self->{svn_path} ?
3291 "$self->{svn_path}/" : '';
3292 return $self;
3295 sub generate_diff {
3296 my ($tree_a, $tree_b) = @_;
3297 my @diff_tree = qw(diff-tree -z -r);
3298 if ($_cp_similarity) {
3299 push @diff_tree, "-C$_cp_similarity";
3300 } else {
3301 push @diff_tree, '-C';
3303 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3304 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3305 push @diff_tree, $tree_a, $tree_b;
3306 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3307 local $/ = "\0";
3308 my $state = 'meta';
3309 my @mods;
3310 while (<$diff_fh>) {
3311 chomp $_; # this gets rid of the trailing "\0"
3312 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3313 $::sha1\s($::sha1)\s
3314 ([MTCRAD])\d*$/xo) {
3315 push @mods, { mode_a => $1, mode_b => $2,
3316 sha1_b => $3, chg => $4 };
3317 if ($4 =~ /^(?:C|R)$/) {
3318 $state = 'file_a';
3319 } else {
3320 $state = 'file_b';
3322 } elsif ($state eq 'file_a') {
3323 my $x = $mods[$#mods] or croak "Empty array\n";
3324 if ($x->{chg} !~ /^(?:C|R)$/) {
3325 croak "Error parsing $_, $x->{chg}\n";
3327 $x->{file_a} = $_;
3328 $state = 'file_b';
3329 } elsif ($state eq 'file_b') {
3330 my $x = $mods[$#mods] or croak "Empty array\n";
3331 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3332 croak "Error parsing $_, $x->{chg}\n";
3334 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3335 croak "Error parsing $_, $x->{chg}\n";
3337 $x->{file_b} = $_;
3338 $state = 'meta';
3339 } else {
3340 croak "Error parsing $_\n";
3343 command_close_pipe($diff_fh, $ctx);
3344 \@mods;
3347 sub check_diff_paths {
3348 my ($ra, $pfx, $rev, $mods) = @_;
3349 my %types;
3350 $pfx .= '/' if length $pfx;
3352 sub type_diff_paths {
3353 my ($ra, $types, $path, $rev) = @_;
3354 my @p = split m#/+#, $path;
3355 my $c = shift @p;
3356 unless (defined $types->{$c}) {
3357 $types->{$c} = $ra->check_path($c, $rev);
3359 while (@p) {
3360 $c .= '/' . shift @p;
3361 next if defined $types->{$c};
3362 $types->{$c} = $ra->check_path($c, $rev);
3366 foreach my $m (@$mods) {
3367 foreach my $f (qw/file_a file_b/) {
3368 next unless defined $m->{$f};
3369 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3370 if (length $pfx.$dir && ! defined $types{$dir}) {
3371 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3375 \%types;
3378 sub split_path {
3379 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3382 sub repo_path {
3383 my ($self, $path) = @_;
3384 $self->{path_prefix}.(defined $path ? $path : '');
3387 sub url_path {
3388 my ($self, $path) = @_;
3389 if ($self->{url} =~ m#^https?://#) {
3390 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3392 $self->{url} . '/' . $self->repo_path($path);
3395 sub rmdirs {
3396 my ($self) = @_;
3397 my $rm = $self->{rm};
3398 delete $rm->{''}; # we never delete the url we're tracking
3399 return unless %$rm;
3401 foreach (keys %$rm) {
3402 my @d = split m#/#, $_;
3403 my $c = shift @d;
3404 $rm->{$c} = 1;
3405 while (@d) {
3406 $c .= '/' . shift @d;
3407 $rm->{$c} = 1;
3410 delete $rm->{$self->{svn_path}};
3411 delete $rm->{''}; # we never delete the url we're tracking
3412 return unless %$rm;
3414 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3415 $self->{tree_b});
3416 local $/ = "\0";
3417 while (<$fh>) {
3418 chomp;
3419 my @dn = split m#/#, $_;
3420 while (pop @dn) {
3421 delete $rm->{join '/', @dn};
3423 unless (%$rm) {
3424 close $fh;
3425 return;
3428 command_close_pipe($fh, $ctx);
3430 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3431 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3432 $self->close_directory($bat->{$d}, $p);
3433 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3434 print "\tD+\t$d/\n" unless $::_q;
3435 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3436 delete $bat->{$d};
3440 sub open_or_add_dir {
3441 my ($self, $full_path, $baton) = @_;
3442 my $t = $self->{types}->{$full_path};
3443 if (!defined $t) {
3444 die "$full_path not known in r$self->{r} or we have a bug!\n";
3447 no warnings 'once';
3448 # SVN::Node::none and SVN::Node::file are used only once,
3449 # so we're shutting up Perl's warnings about them.
3450 if ($t == $SVN::Node::none) {
3451 return $self->add_directory($full_path, $baton,
3452 undef, -1, $self->{pool});
3453 } elsif ($t == $SVN::Node::dir) {
3454 return $self->open_directory($full_path, $baton,
3455 $self->{r}, $self->{pool});
3456 } # no warnings 'once'
3457 print STDERR "$full_path already exists in repository at ",
3458 "r$self->{r} and it is not a directory (",
3459 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3460 } # no warnings 'once'
3461 exit 1;
3464 sub ensure_path {
3465 my ($self, $path) = @_;
3466 my $bat = $self->{bat};
3467 my $repo_path = $self->repo_path($path);
3468 return $bat->{''} unless (length $repo_path);
3469 my @p = split m#/+#, $repo_path;
3470 my $c = shift @p;
3471 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3472 while (@p) {
3473 my $c0 = $c;
3474 $c .= '/' . shift @p;
3475 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3477 return $bat->{$c};
3480 sub A {
3481 my ($self, $m) = @_;
3482 my ($dir, $file) = split_path($m->{file_b});
3483 my $pbat = $self->ensure_path($dir);
3484 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3485 undef, -1);
3486 print "\tA\t$m->{file_b}\n" unless $::_q;
3487 $self->chg_file($fbat, $m);
3488 $self->close_file($fbat,undef,$self->{pool});
3491 sub C {
3492 my ($self, $m) = @_;
3493 my ($dir, $file) = split_path($m->{file_b});
3494 my $pbat = $self->ensure_path($dir);
3495 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3496 $self->url_path($m->{file_a}), $self->{r});
3497 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3498 $self->chg_file($fbat, $m);
3499 $self->close_file($fbat,undef,$self->{pool});
3502 sub delete_entry {
3503 my ($self, $path, $pbat) = @_;
3504 my $rpath = $self->repo_path($path);
3505 my ($dir, $file) = split_path($rpath);
3506 $self->{rm}->{$dir} = 1;
3507 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3510 sub R {
3511 my ($self, $m) = @_;
3512 my ($dir, $file) = split_path($m->{file_b});
3513 my $pbat = $self->ensure_path($dir);
3514 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3515 $self->url_path($m->{file_a}), $self->{r});
3516 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3517 $self->chg_file($fbat, $m);
3518 $self->close_file($fbat,undef,$self->{pool});
3520 ($dir, $file) = split_path($m->{file_a});
3521 $pbat = $self->ensure_path($dir);
3522 $self->delete_entry($m->{file_a}, $pbat);
3525 sub M {
3526 my ($self, $m) = @_;
3527 my ($dir, $file) = split_path($m->{file_b});
3528 my $pbat = $self->ensure_path($dir);
3529 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3530 $pbat,$self->{r},$self->{pool});
3531 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3532 $self->chg_file($fbat, $m);
3533 $self->close_file($fbat,undef,$self->{pool});
3536 sub T { shift->M(@_) }
3538 sub change_file_prop {
3539 my ($self, $fbat, $pname, $pval) = @_;
3540 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3543 sub chg_file {
3544 my ($self, $fbat, $m) = @_;
3545 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3546 $self->change_file_prop($fbat,'svn:executable','*');
3547 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3548 $self->change_file_prop($fbat,'svn:executable',undef);
3550 my $fh = IO::File->new_tmpfile or croak $!;
3551 if ($m->{mode_b} =~ /^120/) {
3552 print $fh 'link ' or croak $!;
3553 $self->change_file_prop($fbat,'svn:special','*');
3554 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3555 $self->change_file_prop($fbat,'svn:special',undef);
3557 defined(my $pid = fork) or croak $!;
3558 if (!$pid) {
3559 open STDOUT, '>&', $fh or croak $!;
3560 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3562 waitpid $pid, 0;
3563 croak $? if $?;
3564 $fh->flush == 0 or croak $!;
3565 seek $fh, 0, 0 or croak $!;
3567 my $exp = ::md5sum($fh);
3568 seek $fh, 0, 0 or croak $!;
3570 my $pool = SVN::Pool->new;
3571 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3572 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3573 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3574 $pool->clear;
3576 close $fh or croak $!;
3579 sub D {
3580 my ($self, $m) = @_;
3581 my ($dir, $file) = split_path($m->{file_b});
3582 my $pbat = $self->ensure_path($dir);
3583 print "\tD\t$m->{file_b}\n" unless $::_q;
3584 $self->delete_entry($m->{file_b}, $pbat);
3587 sub close_edit {
3588 my ($self) = @_;
3589 my ($p,$bat) = ($self->{pool}, $self->{bat});
3590 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3591 next if $_ eq '';
3592 $self->close_directory($bat->{$_}, $p);
3594 $self->close_directory($bat->{''}, $p);
3595 $self->SUPER::close_edit($p);
3596 $p->clear;
3599 sub abort_edit {
3600 my ($self) = @_;
3601 $self->SUPER::abort_edit($self->{pool});
3604 sub DESTROY {
3605 my $self = shift;
3606 $self->SUPER::DESTROY(@_);
3607 $self->{pool}->clear;
3610 # this drives the editor
3611 sub apply_diff {
3612 my ($self) = @_;
3613 my $mods = $self->{mods};
3614 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3615 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3616 my $f = $m->{chg};
3617 if (defined $o{$f}) {
3618 $self->$f($m);
3619 } else {
3620 fatal("Invalid change type: $f");
3623 $self->rmdirs if $_rmdir;
3624 if (@$mods == 0) {
3625 $self->abort_edit;
3626 } else {
3627 $self->close_edit;
3629 return scalar @$mods;
3632 package Git::SVN::Ra;
3633 use vars qw/@ISA $config_dir $_log_window_size/;
3634 use strict;
3635 use warnings;
3636 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3638 BEGIN {
3639 # enforce temporary pool usage for some simple functions
3640 no strict 'refs';
3641 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3642 my $SUPER = "SUPER::$f";
3643 *$f = sub {
3644 my $self = shift;
3645 my $pool = SVN::Pool->new;
3646 my @ret = $self->$SUPER(@_,$pool);
3647 $pool->clear;
3648 wantarray ? @ret : $ret[0];
3653 sub _auth_providers () {
3655 SVN::Client::get_simple_provider(),
3656 SVN::Client::get_ssl_server_trust_file_provider(),
3657 SVN::Client::get_simple_prompt_provider(
3658 \&Git::SVN::Prompt::simple, 2),
3659 SVN::Client::get_ssl_client_cert_file_provider(),
3660 SVN::Client::get_ssl_client_cert_prompt_provider(
3661 \&Git::SVN::Prompt::ssl_client_cert, 2),
3662 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3663 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3664 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3665 SVN::Client::get_username_provider(),
3666 SVN::Client::get_ssl_server_trust_prompt_provider(
3667 \&Git::SVN::Prompt::ssl_server_trust),
3668 SVN::Client::get_username_prompt_provider(
3669 \&Git::SVN::Prompt::username, 2)
3673 sub escape_uri_only {
3674 my ($uri) = @_;
3675 my @tmp;
3676 foreach (split m{/}, $uri) {
3677 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3678 push @tmp, $_;
3680 join('/', @tmp);
3683 sub escape_url {
3684 my ($url) = @_;
3685 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3686 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3687 $url = "$scheme://$domain$uri";
3689 $url;
3692 sub new {
3693 my ($class, $url) = @_;
3694 $url =~ s!/+$!!;
3695 return $RA if ($RA && $RA->{url} eq $url);
3697 SVN::_Core::svn_config_ensure($config_dir, undef);
3698 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3699 my $config = SVN::Core::config_get_config($config_dir);
3700 $RA = undef;
3701 my $dont_store_passwords = 1;
3702 my $conf_t = ${$config}{'config'};
3704 no warnings 'once';
3705 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3706 # produces warnings that variables are used only once.
3707 # I had not found the better way to shut them up, so
3708 # the warnings of type 'once' are disabled in this block.
3709 if (SVN::_Core::svn_config_get_bool($conf_t,
3710 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3711 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3712 1) == 0) {
3713 SVN::_Core::svn_auth_set_parameter($baton,
3714 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3715 bless (\$dont_store_passwords, "_p_void"));
3717 if (SVN::_Core::svn_config_get_bool($conf_t,
3718 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3719 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3720 1) == 0) {
3721 $Git::SVN::Prompt::_no_auth_cache = 1;
3723 } # no warnings 'once'
3724 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3725 config => $config,
3726 pool => SVN::Pool->new,
3727 auth_provider_callbacks => $callbacks);
3728 $self->{url} = $url;
3729 $self->{svn_path} = $url;
3730 $self->{repos_root} = $self->get_repos_root;
3731 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3732 $self->{cache} = { check_path => { r => 0, data => {} },
3733 get_dir => { r => 0, data => {} } };
3734 $RA = bless $self, $class;
3737 sub check_path {
3738 my ($self, $path, $r) = @_;
3739 my $cache = $self->{cache}->{check_path};
3740 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3741 return $cache->{data}->{$path};
3743 my $pool = SVN::Pool->new;
3744 my $t = $self->SUPER::check_path($path, $r, $pool);
3745 $pool->clear;
3746 if ($r != $cache->{r}) {
3747 %{$cache->{data}} = ();
3748 $cache->{r} = $r;
3750 $cache->{data}->{$path} = $t;
3753 sub get_dir {
3754 my ($self, $dir, $r) = @_;
3755 my $cache = $self->{cache}->{get_dir};
3756 if ($r == $cache->{r}) {
3757 if (my $x = $cache->{data}->{$dir}) {
3758 return wantarray ? @$x : $x->[0];
3761 my $pool = SVN::Pool->new;
3762 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3763 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3764 $pool->clear;
3765 if ($r != $cache->{r}) {
3766 %{$cache->{data}} = ();
3767 $cache->{r} = $r;
3769 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3770 wantarray ? (\%dirents, $r, $props) : \%dirents;
3773 sub DESTROY {
3774 # do not call the real DESTROY since we store ourselves in $RA
3777 sub get_log {
3778 my ($self, @args) = @_;
3779 my $pool = SVN::Pool->new;
3780 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3781 my $ret = $self->SUPER::get_log(@args, $pool);
3782 $pool->clear;
3783 $ret;
3786 sub trees_match {
3787 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3788 my $ctx = SVN::Client->new(auth => _auth_providers);
3789 my $out = IO::File->new_tmpfile;
3791 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3792 # $ctx->diff(), so we'll create a default one
3793 my $pool = SVN::Pool->new_default_sub;
3795 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3796 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3797 $out->flush;
3798 my $ret = (($out->stat)[7] == 0);
3799 close $out or croak $!;
3801 $ret;
3804 sub get_commit_editor {
3805 my ($self, $log, $cb, $pool) = @_;
3806 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3807 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3810 sub gs_do_update {
3811 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3812 my $new = ($rev_a == $rev_b);
3813 my $path = $gs->{path};
3815 if ($new && -e $gs->{index}) {
3816 unlink $gs->{index} or die
3817 "Couldn't unlink index: $gs->{index}: $!\n";
3819 my $pool = SVN::Pool->new;
3820 $editor->set_path_strip($path);
3821 my (@pc) = split m#/#, $path;
3822 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3823 1, $editor, $pool);
3824 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3826 # Since we can't rely on svn_ra_reparent being available, we'll
3827 # just have to do some magic with set_path to make it so
3828 # we only want a partial path.
3829 my $sp = '';
3830 my $final = join('/', @pc);
3831 while (@pc) {
3832 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3833 $sp .= '/' if length $sp;
3834 $sp .= shift @pc;
3836 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3838 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3840 $reporter->finish_report($pool);
3841 $pool->clear;
3842 $editor->{git_commit_ok};
3845 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3846 # svn_ra_reparent didn't work before 1.4)
3847 sub gs_do_switch {
3848 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3849 my $path = $gs->{path};
3850 my $pool = SVN::Pool->new;
3852 my $full_url = $self->{url};
3853 my $old_url = $full_url;
3854 $full_url .= '/' . escape_uri_only($path) if length $path;
3855 my ($ra, $reparented);
3856 if ($old_url ne $full_url) {
3857 if ($old_url !~ m#^svn(\+ssh)?://#) {
3858 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3859 $pool);
3860 $self->{url} = $full_url;
3861 $reparented = 1;
3862 } else {
3863 $_[0] = undef;
3864 $self = undef;
3865 $RA = undef;
3866 $ra = Git::SVN::Ra->new($full_url);
3867 $ra_invalid = 1;
3870 $ra ||= $self;
3871 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3872 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3873 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3874 $reporter->finish_report($pool);
3876 if ($reparented) {
3877 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3878 $self->{url} = $old_url;
3881 $pool->clear;
3882 $editor->{git_commit_ok};
3885 sub longest_common_path {
3886 my ($gsv, $globs) = @_;
3887 my %common;
3888 my $common_max = scalar @$gsv;
3890 foreach my $gs (@$gsv) {
3891 my @tmp = split m#/#, $gs->{path};
3892 my $p = '';
3893 foreach (@tmp) {
3894 $p .= length($p) ? "/$_" : $_;
3895 $common{$p} ||= 0;
3896 $common{$p}++;
3899 $globs ||= [];
3900 $common_max += scalar @$globs;
3901 foreach my $glob (@$globs) {
3902 my @tmp = split m#/#, $glob->{path}->{left};
3903 my $p = '';
3904 foreach (@tmp) {
3905 $p .= length($p) ? "/$_" : $_;
3906 $common{$p} ||= 0;
3907 $common{$p}++;
3911 my $longest_path = '';
3912 foreach (sort {length $b <=> length $a} keys %common) {
3913 if ($common{$_} == $common_max) {
3914 $longest_path = $_;
3915 last;
3918 $longest_path;
3921 sub gs_fetch_loop_common {
3922 my ($self, $base, $head, $gsv, $globs) = @_;
3923 return if ($base > $head);
3924 my $inc = $_log_window_size;
3925 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3926 my $longest_path = longest_common_path($gsv, $globs);
3927 my $ra_url = $self->{url};
3928 while (1) {
3929 my %revs;
3930 my $err;
3931 my $err_handler = $SVN::Error::handler;
3932 $SVN::Error::handler = sub {
3933 ($err) = @_;
3934 skip_unknown_revs($err);
3936 sub _cb {
3937 my ($paths, $r, $author, $date, $log) = @_;
3938 [ dup_changed_paths($paths),
3939 { author => $author, date => $date, log => $log } ];
3941 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3942 sub { $revs{$_[1]} = _cb(@_) });
3943 if ($err && $max >= $head) {
3944 print STDERR "Path '$longest_path' ",
3945 "was probably deleted:\n",
3946 $err->expanded_message,
3947 "\nWill attempt to follow ",
3948 "revisions r$min .. r$max ",
3949 "committed before the deletion\n";
3950 my $hi = $max;
3951 while (--$hi >= $min) {
3952 my $ok;
3953 $self->get_log([$longest_path], $min, $hi,
3954 0, 1, 1, sub {
3955 $ok ||= $_[1];
3956 $revs{$_[1]} = _cb(@_) });
3957 if ($ok) {
3958 print STDERR "r$min .. r$ok OK\n";
3959 last;
3963 $SVN::Error::handler = $err_handler;
3965 my %exists = map { $_->{path} => $_ } @$gsv;
3966 foreach my $r (sort {$a <=> $b} keys %revs) {
3967 my ($paths, $logged) = @{$revs{$r}};
3969 foreach my $gs ($self->match_globs(\%exists, $paths,
3970 $globs, $r)) {
3971 if ($gs->rev_map_max >= $r) {
3972 next;
3974 next unless $gs->match_paths($paths, $r);
3975 $gs->{logged_rev_props} = $logged;
3976 if (my $last_commit = $gs->last_commit) {
3977 $gs->assert_index_clean($last_commit);
3979 my $log_entry = $gs->do_fetch($paths, $r);
3980 if ($log_entry) {
3981 $gs->do_git_commit($log_entry);
3983 $INDEX_FILES{$gs->{index}} = 1;
3985 foreach my $g (@$globs) {
3986 my $k = "svn-remote.$g->{remote}." .
3987 "$g->{t}-maxRev";
3988 Git::SVN::tmp_config($k, $r);
3990 if ($ra_invalid) {
3991 $_[0] = undef;
3992 $self = undef;
3993 $RA = undef;
3994 $self = Git::SVN::Ra->new($ra_url);
3995 $ra_invalid = undef;
3998 # pre-fill the .rev_db since it'll eventually get filled in
3999 # with '0' x40 if something new gets committed
4000 foreach my $gs (@$gsv) {
4001 next if $gs->rev_map_max >= $max;
4002 next if defined $gs->rev_map_get($max);
4003 $gs->rev_map_set($max, 0 x40);
4005 foreach my $g (@$globs) {
4006 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4007 Git::SVN::tmp_config($k, $max);
4009 last if $max >= $head;
4010 $min = $max + 1;
4011 $max += $inc;
4012 $max = $head if ($max > $head);
4014 Git::SVN::gc();
4017 sub match_globs {
4018 my ($self, $exists, $paths, $globs, $r) = @_;
4020 sub get_dir_check {
4021 my ($self, $exists, $g, $r) = @_;
4022 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
4023 return unless scalar @x == 3;
4024 my $dirents = $x[0];
4025 foreach my $de (keys %$dirents) {
4026 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4027 my $p = $g->{path}->full_path($de);
4028 next if $exists->{$p};
4029 next if (length $g->{path}->{right} &&
4030 ($self->check_path($p, $r) !=
4031 $SVN::Node::dir));
4032 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4033 $g->{ref}->full_path($de), 1);
4036 foreach my $g (@$globs) {
4037 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4038 if ($path->{action} =~ /^[AR]$/) {
4039 get_dir_check($self, $exists, $g, $r);
4042 foreach (keys %$paths) {
4043 if (/$g->{path}->{left_regex}/ &&
4044 !/$g->{path}->{regex}/) {
4045 next if $paths->{$_}->{action} !~ /^[AR]$/;
4046 get_dir_check($self, $exists, $g, $r);
4048 next unless /$g->{path}->{regex}/;
4049 my $p = $1;
4050 my $pathname = $g->{path}->full_path($p);
4051 next if $exists->{$pathname};
4052 next if ($self->check_path($pathname, $r) !=
4053 $SVN::Node::dir);
4054 $exists->{$pathname} = Git::SVN->init(
4055 $self->{url}, $pathname, undef,
4056 $g->{ref}->full_path($p), 1);
4058 my $c = '';
4059 foreach (split m#/#, $g->{path}->{left}) {
4060 $c .= "/$_";
4061 next unless ($paths->{$c} &&
4062 ($paths->{$c}->{action} =~ /^[AR]$/));
4063 get_dir_check($self, $exists, $g, $r);
4066 values %$exists;
4069 sub minimize_url {
4070 my ($self) = @_;
4071 return $self->{url} if ($self->{url} eq $self->{repos_root});
4072 my $url = $self->{repos_root};
4073 my @components = split(m!/!, $self->{svn_path});
4074 my $c = '';
4075 do {
4076 $url .= "/$c" if length $c;
4077 eval { (ref $self)->new($url)->get_latest_revnum };
4078 } while ($@ && ($c = shift @components));
4079 $url;
4082 sub can_do_switch {
4083 my $self = shift;
4084 unless (defined $can_do_switch) {
4085 my $pool = SVN::Pool->new;
4086 my $rep = eval {
4087 $self->do_switch(1, '', 0, $self->{url},
4088 SVN::Delta::Editor->new, $pool);
4090 if ($@) {
4091 $can_do_switch = 0;
4092 } else {
4093 $rep->abort_report($pool);
4094 $can_do_switch = 1;
4096 $pool->clear;
4098 $can_do_switch;
4101 sub skip_unknown_revs {
4102 my ($err) = @_;
4103 my $errno = $err->apr_err();
4104 # Maybe the branch we're tracking didn't
4105 # exist when the repo started, so it's
4106 # not an error if it doesn't, just continue
4108 # Wonderfully consistent library, eh?
4109 # 160013 - svn:// and file://
4110 # 175002 - http(s)://
4111 # 175007 - http(s):// (this repo required authorization, too...)
4112 # More codes may be discovered later...
4113 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4114 my $err_key = $err->expanded_message;
4115 # revision numbers change every time, filter them out
4116 $err_key =~ s/\d+/\0/g;
4117 $err_key = "$errno\0$err_key";
4118 unless ($ignored_err{$err_key}) {
4119 warn "W: Ignoring error from SVN, path probably ",
4120 "does not exist: ($errno): ",
4121 $err->expanded_message,"\n";
4122 warn "W: Do not be alarmed at the above message ",
4123 "git-svn is just searching aggressively for ",
4124 "old history.\n",
4125 "This may take a while on large repositories\n";
4126 $ignored_err{$err_key} = 1;
4128 return;
4130 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4133 # svn_log_changed_path_t objects passed to get_log are likely to be
4134 # overwritten even if only the refs are copied to an external variable,
4135 # so we should dup the structures in their entirety. Using an externally
4136 # passed pool (instead of our temporary and quickly cleared pool in
4137 # Git::SVN::Ra) does not help matters at all...
4138 sub dup_changed_paths {
4139 my ($paths) = @_;
4140 return undef unless $paths;
4141 my %ret;
4142 foreach my $p (keys %$paths) {
4143 my $i = $paths->{$p};
4144 my %s = map { $_ => $i->$_ }
4145 qw/copyfrom_path copyfrom_rev action/;
4146 $ret{$p} = \%s;
4148 \%ret;
4151 package Git::SVN::Log;
4152 use strict;
4153 use warnings;
4154 use POSIX qw/strftime/;
4155 use constant commit_log_separator => ('-' x 72) . "\n";
4156 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4157 %rusers $show_commit $incremental/;
4158 my $l_fmt;
4160 sub cmt_showable {
4161 my ($c) = @_;
4162 return 1 if defined $c->{r};
4164 # big commit message got truncated by the 16k pretty buffer in rev-list
4165 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4166 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4167 @{$c->{l}} = ();
4168 my @log = command(qw/cat-file commit/, $c->{c});
4170 # shift off the headers
4171 shift @log while ($log[0] ne '');
4172 shift @log;
4174 # TODO: make $c->{l} not have a trailing newline in the future
4175 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4177 (undef, $c->{r}, undef) = ::extract_metadata(
4178 (grep(/^git-svn-id: /, @log))[-1]);
4180 return defined $c->{r};
4183 sub log_use_color {
4184 return $color || Git->repository->get_colorbool('color.diff');
4187 sub git_svn_log_cmd {
4188 my ($r_min, $r_max, @args) = @_;
4189 my $head = 'HEAD';
4190 my (@files, @log_opts);
4191 foreach my $x (@args) {
4192 if ($x eq '--' || @files) {
4193 push @files, $x;
4194 } else {
4195 if (::verify_ref("$x^0")) {
4196 $head = $x;
4197 } else {
4198 push @log_opts, $x;
4203 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4204 $gs ||= Git::SVN->_new;
4205 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4206 $gs->refname);
4207 push @cmd, '-r' unless $non_recursive;
4208 push @cmd, qw/--raw --name-status/ if $verbose;
4209 push @cmd, '--color' if log_use_color();
4210 push @cmd, @log_opts;
4211 if (defined $r_max && $r_max == $r_min) {
4212 push @cmd, '--max-count=1';
4213 if (my $c = $gs->rev_map_get($r_max)) {
4214 push @cmd, $c;
4216 } elsif (defined $r_max) {
4217 if ($r_max < $r_min) {
4218 ($r_min, $r_max) = ($r_max, $r_min);
4220 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4221 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4222 # If there are no commits in the range, both $c_max and $c_min
4223 # will be undefined. If there is at least 1 commit in the
4224 # range, both will be defined.
4225 return () if !defined $c_min || !defined $c_max;
4226 if ($c_min eq $c_max) {
4227 push @cmd, '--max-count=1', $c_min;
4228 } else {
4229 push @cmd, '--boundary', "$c_min..$c_max";
4232 return (@cmd, @files);
4235 # adapted from pager.c
4236 sub config_pager {
4237 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4238 if (!defined $pager) {
4239 $pager = 'less';
4240 } elsif (length $pager == 0 || $pager eq 'cat') {
4241 $pager = undef;
4243 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4246 sub run_pager {
4247 return unless -t *STDOUT && defined $pager;
4248 pipe my $rfd, my $wfd or return;
4249 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4250 if (!$pid) {
4251 open STDOUT, '>&', $wfd or
4252 ::fatal "Can't redirect to stdout: $!";
4253 return;
4255 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4256 $ENV{LESS} ||= 'FRSX';
4257 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4260 sub format_svn_date {
4261 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4264 sub parse_git_date {
4265 my ($t, $tz) = @_;
4266 # Date::Parse isn't in the standard Perl distro :(
4267 if ($tz =~ s/^\+//) {
4268 $t += tz_to_s_offset($tz);
4269 } elsif ($tz =~ s/^\-//) {
4270 $t -= tz_to_s_offset($tz);
4272 return $t;
4275 sub set_local_timezone {
4276 if (defined $TZ) {
4277 $ENV{TZ} = $TZ;
4278 } else {
4279 delete $ENV{TZ};
4283 sub tz_to_s_offset {
4284 my ($tz) = @_;
4285 $tz =~ s/(\d\d)$//;
4286 return ($1 * 60) + ($tz * 3600);
4289 sub get_author_info {
4290 my ($dest, $author, $t, $tz) = @_;
4291 $author =~ s/(?:^\s*|\s*$)//g;
4292 $dest->{a_raw} = $author;
4293 my $au;
4294 if ($::_authors) {
4295 $au = $rusers{$author} || undef;
4297 if (!$au) {
4298 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4300 $dest->{t} = $t;
4301 $dest->{tz} = $tz;
4302 $dest->{a} = $au;
4303 $dest->{t_utc} = parse_git_date($t, $tz);
4306 sub process_commit {
4307 my ($c, $r_min, $r_max, $defer) = @_;
4308 if (defined $r_min && defined $r_max) {
4309 if ($r_min == $c->{r} && $r_min == $r_max) {
4310 show_commit($c);
4311 return 0;
4313 return 1 if $r_min == $r_max;
4314 if ($r_min < $r_max) {
4315 # we need to reverse the print order
4316 return 0 if (defined $limit && --$limit < 0);
4317 push @$defer, $c;
4318 return 1;
4320 if ($r_min != $r_max) {
4321 return 1 if ($r_min < $c->{r});
4322 return 1 if ($r_max > $c->{r});
4325 return 0 if (defined $limit && --$limit < 0);
4326 show_commit($c);
4327 return 1;
4330 sub show_commit {
4331 my $c = shift;
4332 if ($oneline) {
4333 my $x = "\n";
4334 if (my $l = $c->{l}) {
4335 while ($l->[0] =~ /^\s*$/) { shift @$l }
4336 $x = $l->[0];
4338 $l_fmt ||= 'A' . length($c->{r});
4339 print 'r',pack($l_fmt, $c->{r}),' | ';
4340 print "$c->{c} | " if $show_commit;
4341 print $x;
4342 } else {
4343 show_commit_normal($c);
4347 sub show_commit_changed_paths {
4348 my ($c) = @_;
4349 return unless $c->{changed};
4350 print "Changed paths:\n", @{$c->{changed}};
4353 sub show_commit_normal {
4354 my ($c) = @_;
4355 print commit_log_separator, "r$c->{r} | ";
4356 print "$c->{c} | " if $show_commit;
4357 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4358 my $nr_line = 0;
4360 if (my $l = $c->{l}) {
4361 while ($l->[$#$l] eq "\n" && $#$l > 0
4362 && $l->[($#$l - 1)] eq "\n") {
4363 pop @$l;
4365 $nr_line = scalar @$l;
4366 if (!$nr_line) {
4367 print "1 line\n\n\n";
4368 } else {
4369 if ($nr_line == 1) {
4370 $nr_line = '1 line';
4371 } else {
4372 $nr_line .= ' lines';
4374 print $nr_line, "\n";
4375 show_commit_changed_paths($c);
4376 print "\n";
4377 print $_ foreach @$l;
4379 } else {
4380 print "1 line\n";
4381 show_commit_changed_paths($c);
4382 print "\n";
4385 foreach my $x (qw/raw stat diff/) {
4386 if ($c->{$x}) {
4387 print "\n";
4388 print $_ foreach @{$c->{$x}}
4393 sub cmd_show_log {
4394 my (@args) = @_;
4395 my ($r_min, $r_max);
4396 my $r_last = -1; # prevent dupes
4397 set_local_timezone();
4398 if (defined $::_revision) {
4399 if ($::_revision =~ /^(\d+):(\d+)$/) {
4400 ($r_min, $r_max) = ($1, $2);
4401 } elsif ($::_revision =~ /^\d+$/) {
4402 $r_min = $r_max = $::_revision;
4403 } else {
4404 ::fatal "-r$::_revision is not supported, use ",
4405 "standard 'git log' arguments instead";
4409 config_pager();
4410 @args = git_svn_log_cmd($r_min, $r_max, @args);
4411 if (!@args) {
4412 print commit_log_separator unless $incremental || $oneline;
4413 return;
4415 my $log = command_output_pipe(@args);
4416 run_pager();
4417 my (@k, $c, $d, $stat);
4418 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4419 while (<$log>) {
4420 if (/^${esc_color}commit -?($::sha1_short)/o) {
4421 my $cmt = $1;
4422 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4423 $r_last = $c->{r};
4424 process_commit($c, $r_min, $r_max, \@k) or
4425 goto out;
4427 $d = undef;
4428 $c = { c => $cmt };
4429 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4430 get_author_info($c, $1, $2, $3);
4431 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4432 # ignore
4433 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4434 push @{$c->{raw}}, $_;
4435 } elsif (/^${esc_color}[ACRMDT]\t/) {
4436 # we could add $SVN->{svn_path} here, but that requires
4437 # remote access at the moment (repo_path_split)...
4438 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4439 push @{$c->{changed}}, $_;
4440 } elsif (/^${esc_color}diff /o) {
4441 $d = 1;
4442 push @{$c->{diff}}, $_;
4443 } elsif ($d) {
4444 push @{$c->{diff}}, $_;
4445 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4446 $esc_color*[\+\-]*$esc_color$/x) {
4447 $stat = 1;
4448 push @{$c->{stat}}, $_;
4449 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4450 push @{$c->{stat}}, $_;
4451 $stat = undef;
4452 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4453 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4454 } elsif (s/^${esc_color} //o) {
4455 push @{$c->{l}}, $_;
4458 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4459 $r_last = $c->{r};
4460 process_commit($c, $r_min, $r_max, \@k);
4462 if (@k) {
4463 ($r_min, $r_max) = ($r_max, $r_min);
4464 process_commit($_, $r_min, $r_max) foreach reverse @k;
4466 out:
4467 close $log;
4468 print commit_log_separator unless $incremental || $oneline;
4471 sub cmd_blame {
4472 my $path = pop;
4474 config_pager();
4475 run_pager();
4477 my ($fh, $ctx, $rev);
4479 if ($_git_format) {
4480 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4481 while (my $line = <$fh>) {
4482 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4483 # Uncommitted edits show up as a rev ID of
4484 # all zeros, which we can't look up with
4485 # cmt_metadata
4486 if ($1 !~ /^0+$/) {
4487 (undef, $rev, undef) =
4488 ::cmt_metadata($1);
4489 $rev = '0' if (!$rev);
4490 } else {
4491 $rev = '0';
4493 $rev = sprintf('%-10s', $rev);
4494 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4496 print $line;
4498 } else {
4499 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4500 '--', $path);
4501 my ($sha1);
4502 my %authors;
4503 while (my $line = <$fh>) {
4504 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4505 $sha1 = $1;
4506 (undef, $rev, undef) = ::cmt_metadata($1);
4507 $rev = '0' if (!$rev);
4509 elsif ($line =~ /^author (.*)/) {
4510 $authors{$rev} = $1;
4511 $authors{$rev} =~ s/\s/_/g;
4513 elsif ($line =~ /^\t(.*)$/) {
4514 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4518 command_close_pipe($fh, $ctx);
4521 package Git::SVN::Migration;
4522 # these version numbers do NOT correspond to actual version numbers
4523 # of git nor git-svn. They are just relative.
4525 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4527 # v1 layout: .git/$id/info/url, refs/remotes/$id
4529 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4531 # v3 layout: .git/svn/$id, refs/remotes/$id
4532 # - info/url may remain for backwards compatibility
4533 # - this is what we migrate up to this layout automatically,
4534 # - this will be used by git svn init on single branches
4535 # v3.1 layout (auto migrated):
4536 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4537 # for backwards compatibility
4539 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4540 # - this is only created for newly multi-init-ed
4541 # repositories. Similar in spirit to the
4542 # --use-separate-remotes option in git-clone (now default)
4543 # - we do not automatically migrate to this (following
4544 # the example set by core git)
4546 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4547 # - newer, more-efficient format that uses 24-bytes per record
4548 # with no filler space.
4549 # - use xxd -c24 < .rev_map.$UUID to view and debug
4550 # - This is a one-way migration, repositories updated to the
4551 # new format will not be able to use old git-svn without
4552 # rebuilding the .rev_db. Rebuilding the rev_db is not
4553 # possible if noMetadata or useSvmProps are set; but should
4554 # be no problem for users that use the (sensible) defaults.
4555 use strict;
4556 use warnings;
4557 use Carp qw/croak/;
4558 use File::Path qw/mkpath/;
4559 use File::Basename qw/dirname basename/;
4560 use vars qw/$_minimize/;
4562 sub migrate_from_v0 {
4563 my $git_dir = $ENV{GIT_DIR};
4564 return undef unless -d $git_dir;
4565 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4566 my $migrated = 0;
4567 while (<$fh>) {
4568 chomp;
4569 my ($id, $orig_ref) = ($_, $_);
4570 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4571 next unless -f "$git_dir/$id/info/url";
4572 my $new_ref = "refs/remotes/$id";
4573 if (::verify_ref("$new_ref^0")) {
4574 print STDERR "W: $orig_ref is probably an old ",
4575 "branch used by an ancient version of ",
4576 "git-svn.\n",
4577 "However, $new_ref also exists.\n",
4578 "We will not be able ",
4579 "to use this branch until this ",
4580 "ambiguity is resolved.\n";
4581 next;
4583 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4584 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4585 command_noisy('update-ref', $new_ref, $orig_ref);
4586 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4587 $migrated++;
4589 command_close_pipe($fh, $ctx);
4590 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4591 $migrated;
4594 sub migrate_from_v1 {
4595 my $git_dir = $ENV{GIT_DIR};
4596 my $migrated = 0;
4597 return $migrated unless -d $git_dir;
4598 my $svn_dir = "$git_dir/svn";
4600 # just in case somebody used 'svn' as their $id at some point...
4601 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4603 print STDERR "Migrating from a git-svn v1 layout...\n";
4604 mkpath([$svn_dir]);
4605 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4606 "$svn_dir\n\t(required for this version ",
4607 "($::VERSION) of git-svn) does not. exist\n";
4608 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4609 while (<$fh>) {
4610 my $x = $_;
4611 next unless $x =~ s#^refs/remotes/##;
4612 chomp $x;
4613 next unless -f "$git_dir/$x/info/url";
4614 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4615 next unless $u;
4616 my $dn = dirname("$git_dir/svn/$x");
4617 mkpath([$dn]) unless -d $dn;
4618 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4619 mkpath(["$git_dir/svn/svn"]);
4620 print STDERR " - $git_dir/$x/info => ",
4621 "$git_dir/svn/$x/info\n";
4622 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4623 croak "$!: $x";
4624 # don't worry too much about these, they probably
4625 # don't exist with repos this old (save for index,
4626 # and we can easily regenerate that)
4627 foreach my $f (qw/unhandled.log index .rev_db/) {
4628 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4630 } else {
4631 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4632 rename "$git_dir/$x", "$git_dir/svn/$x" or
4633 croak "$!: $x";
4635 $migrated++;
4637 command_close_pipe($fh, $ctx);
4638 print STDERR "Done migrating from a git-svn v1 layout\n";
4639 $migrated;
4642 sub read_old_urls {
4643 my ($l_map, $pfx, $path) = @_;
4644 my @dir;
4645 foreach (<$path/*>) {
4646 if (-r "$_/info/url") {
4647 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4648 my $ref_id = $pfx . basename $_;
4649 my $url = ::file_to_s("$_/info/url");
4650 $l_map->{$ref_id} = $url;
4651 } elsif (-d $_) {
4652 push @dir, $_;
4655 foreach (@dir) {
4656 my $x = $_;
4657 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4658 read_old_urls($l_map, $x, $_);
4662 sub migrate_from_v2 {
4663 my @cfg = command(qw/config -l/);
4664 return if grep /^svn-remote\..+\.url=/, @cfg;
4665 my %l_map;
4666 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4667 my $migrated = 0;
4669 foreach my $ref_id (sort keys %l_map) {
4670 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4671 if ($@) {
4672 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4674 $migrated++;
4676 $migrated;
4679 sub minimize_connections {
4680 my $r = Git::SVN::read_all_remotes();
4681 my $new_urls = {};
4682 my $root_repos = {};
4683 foreach my $repo_id (keys %$r) {
4684 my $url = $r->{$repo_id}->{url} or next;
4685 my $fetch = $r->{$repo_id}->{fetch} or next;
4686 my $ra = Git::SVN::Ra->new($url);
4688 # skip existing cases where we already connect to the root
4689 if (($ra->{url} eq $ra->{repos_root}) ||
4690 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4691 $repo_id)) {
4692 $root_repos->{$ra->{url}} = $repo_id;
4693 next;
4696 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4697 my $root_path = $ra->{url};
4698 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4699 foreach my $path (keys %$fetch) {
4700 my $ref_id = $fetch->{$path};
4701 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4703 # make sure we can read when connecting to
4704 # a higher level of a repository
4705 my ($last_rev, undef) = $gs->last_rev_commit;
4706 if (!defined $last_rev) {
4707 $last_rev = eval {
4708 $root_ra->get_latest_revnum;
4710 next if $@;
4712 my $new = $root_path;
4713 $new .= length $path ? "/$path" : '';
4714 eval {
4715 $root_ra->get_log([$new], $last_rev, $last_rev,
4716 0, 0, 1, sub { });
4718 next if $@;
4719 $new_urls->{$ra->{repos_root}}->{$new} =
4720 { ref_id => $ref_id,
4721 old_repo_id => $repo_id,
4722 old_path => $path };
4726 my @emptied;
4727 foreach my $url (keys %$new_urls) {
4728 # see if we can re-use an existing [svn-remote "repo_id"]
4729 # instead of creating a(n ugly) new section:
4730 my $repo_id = $root_repos->{$url} ||
4731 Git::SVN::sanitize_remote_name($url);
4733 my $fetch = $new_urls->{$url};
4734 foreach my $path (keys %$fetch) {
4735 my $x = $fetch->{$path};
4736 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4737 my $pfx = "svn-remote.$x->{old_repo_id}";
4739 my $old_fetch = quotemeta("$x->{old_path}:".
4740 "refs/remotes/$x->{ref_id}");
4741 command_noisy(qw/config --unset/,
4742 "$pfx.fetch", '^'. $old_fetch . '$');
4743 delete $r->{$x->{old_repo_id}}->
4744 {fetch}->{$x->{old_path}};
4745 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4746 command_noisy(qw/config --unset/,
4747 "$pfx.url");
4748 push @emptied, $x->{old_repo_id}
4752 if (@emptied) {
4753 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4754 "$ENV{GIT_DIR}/config";
4755 print STDERR <<EOF;
4756 The following [svn-remote] sections in your config file ($file) are empty
4757 and can be safely removed:
4759 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4763 sub migration_check {
4764 migrate_from_v0();
4765 migrate_from_v1();
4766 migrate_from_v2();
4767 minimize_connections() if $_minimize;
4770 package Git::IndexInfo;
4771 use strict;
4772 use warnings;
4773 use Git qw/command_input_pipe command_close_pipe/;
4775 sub new {
4776 my ($class) = @_;
4777 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4778 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4781 sub remove {
4782 my ($self, $path) = @_;
4783 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4784 return ++$self->{nr};
4786 undef;
4789 sub update {
4790 my ($self, $mode, $hash, $path) = @_;
4791 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4792 return ++$self->{nr};
4794 undef;
4797 sub DESTROY {
4798 my ($self) = @_;
4799 command_close_pipe($self->{gui}, $self->{ctx});
4802 package Git::SVN::GlobSpec;
4803 use strict;
4804 use warnings;
4806 sub new {
4807 my ($class, $glob) = @_;
4808 my $re = $glob;
4809 $re =~ s!/+$!!g; # no need for trailing slashes
4810 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4811 my ($left, $right) = ($1, $2);
4812 if ($nr > 1) {
4813 die "Only one '*' wildcard expansion ",
4814 "is supported (got $nr): '$glob'\n";
4815 } elsif ($nr == 0) {
4816 die "One '*' is needed for glob: '$glob'\n";
4818 $re = quotemeta($left) . $re . quotemeta($right);
4819 if (length $left && !($left =~ s!/+$!!g)) {
4820 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4822 if (length $right && !($right =~ s!^/+!!g)) {
4823 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4825 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4826 bless { left => $left, right => $right, left_regex => $left_re,
4827 regex => qr/$re/, glob => $glob }, $class;
4830 sub full_path {
4831 my ($self, $path) = @_;
4832 return (length $self->{left} ? "$self->{left}/" : '') .
4833 $path . (length $self->{right} ? "/$self->{right}" : '');
4836 __END__
4838 Data structures:
4841 $remotes = { # returned by read_all_remotes()
4842 'svn' => {
4843 # svn-remote.svn.url=https://svn.musicpd.org
4844 url => 'https://svn.musicpd.org',
4845 # svn-remote.svn.fetch=mpd/trunk:trunk
4846 fetch => {
4847 'mpd/trunk' => 'trunk',
4849 # svn-remote.svn.tags=mpd/tags/*:tags/*
4850 tags => {
4851 path => {
4852 left => 'mpd/tags',
4853 right => '',
4854 regex => qr!mpd/tags/([^/]+)$!,
4855 glob => 'tags/*',
4857 ref => {
4858 left => 'tags',
4859 right => '',
4860 regex => qr!tags/([^/]+)$!,
4861 glob => 'tags/*',
4867 $log_entry hashref as returned by libsvn_log_entry()
4869 log => 'whitespace-formatted log entry
4870 ', # trailing newline is preserved
4871 revision => '8', # integer
4872 date => '2004-02-24T17:01:44.108345Z', # commit date
4873 author => 'committer name'
4877 # this is generated by generate_diff();
4878 @mods = array of diff-index line hashes, each element represents one line
4879 of diff-index output
4881 diff-index line ($m hash)
4883 mode_a => first column of diff-index output, no leading ':',
4884 mode_b => second column of diff-index output,
4885 sha1_b => sha1sum of the final blob,
4886 chg => change type [MCRADT],
4887 file_a => original file name of a file (iff chg is 'C' or 'R')
4888 file_b => new/current file name of a file (any chg)
4892 # retval of read_url_paths{,_all}();
4893 $l_map = {
4894 # repository root url
4895 'https://svn.musicpd.org' => {
4896 # repository path # GIT_SVN_ID
4897 'mpd/trunk' => 'trunk',
4898 'mpd/tags/0.11.5' => 'tags/0.11.5',
4902 Notes:
4903 I don't trust the each() function on unless I created %hash myself
4904 because the internal iterator may not have started at base.