Add an optional <mode> argument to commit/status -u|--untracked-files option
[git/vmiklos.git] / git-svn.perl
blob47b0c37d17101e17e34fab8ed04c3409fe106e87
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
74 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
75 'authors-file|A=s' => \$_authors,
76 'repack:i' => \$Git::SVN::_repack,
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
81 'no-checkout' => \$_no_checkout,
82 'quiet|q' => \$_q,
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
85 'use-log-author' => \$Git::SVN::_use_log_author,
86 'add-author-from' => \$Git::SVN::_add_author_from,
87 %remote_opts );
89 my ($_trunk, $_tags, $_branches, $_stdlayout);
90 my %icv;
91 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
92 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
93 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
94 'stdlayout|s' => \$_stdlayout,
95 'minimize-url|m' => \$Git::SVN::_minimize_url,
96 'no-metadata' => sub { $icv{noMetadata} = 1 },
97 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
98 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
99 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
100 %remote_opts );
101 my %cmt_opts = ( 'edit|e' => \$_edit,
102 'rmdir' => \$SVN::Git::Editor::_rmdir,
103 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
104 'l=i' => \$SVN::Git::Editor::_rename_limit,
105 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
108 my %cmd = (
109 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
110 { 'revision|r=s' => \$_revision,
111 'fetch-all|all' => \$_fetch_all,
112 %fc_opts } ],
113 clone => [ \&cmd_clone, "Initialize and fetch revisions",
114 { 'revision|r=s' => \$_revision,
115 %fc_opts, %init_opts } ],
116 init => [ \&cmd_init, "Initialize a repo for tracking" .
117 " (requires URL argument)",
118 \%init_opts ],
119 'multi-init' => [ \&cmd_multi_init,
120 "Deprecated alias for ".
121 "'$0 init -T<trunk> -b<branches> -t<tags>'",
122 \%init_opts ],
123 dcommit => [ \&cmd_dcommit,
124 'Commit several diffs to merge with upstream',
125 { 'merge|m|M' => \$_merge,
126 'strategy|s=s' => \$_strategy,
127 'verbose|v' => \$_verbose,
128 'dry-run|n' => \$_dry_run,
129 'fetch-all|all' => \$_fetch_all,
130 'no-rebase' => \$_no_rebase,
131 %cmt_opts, %fc_opts } ],
132 'set-tree' => [ \&cmd_set_tree,
133 "Set an SVN repository to a git tree-ish",
134 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
135 'create-ignore' => [ \&cmd_create_ignore,
136 'Create a .gitignore per svn:ignore',
137 { 'revision|r=i' => \$_revision
138 } ],
139 'propget' => [ \&cmd_propget,
140 'Print the value of a property on a file or directory',
141 { 'revision|r=i' => \$_revision } ],
142 'proplist' => [ \&cmd_proplist,
143 'List all properties of a file or directory',
144 { 'revision|r=i' => \$_revision } ],
145 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
146 { 'revision|r=i' => \$_revision
147 } ],
148 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
149 { 'revision|r=i' => \$_revision
150 } ],
151 'multi-fetch' => [ \&cmd_multi_fetch,
152 "Deprecated alias for $0 fetch --all",
153 { 'revision|r=s' => \$_revision, %fc_opts } ],
154 'migrate' => [ sub { },
155 # no-op, we automatically run this anyways,
156 'Migrate configuration/metadata/layout from
157 previous versions of git-svn',
158 { 'minimize' => \$Git::SVN::Migration::_minimize,
159 %remote_opts } ],
160 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
161 { 'limit=i' => \$Git::SVN::Log::limit,
162 'revision|r=s' => \$_revision,
163 'verbose|v' => \$Git::SVN::Log::verbose,
164 'incremental' => \$Git::SVN::Log::incremental,
165 'oneline' => \$Git::SVN::Log::oneline,
166 'show-commit' => \$Git::SVN::Log::show_commit,
167 'non-recursive' => \$Git::SVN::Log::non_recursive,
168 'authors-file|A=s' => \$_authors,
169 'color' => \$Git::SVN::Log::color,
170 'pager=s' => \$Git::SVN::Log::pager
171 } ],
172 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
173 {} ],
174 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
175 { 'merge|m|M' => \$_merge,
176 'verbose|v' => \$_verbose,
177 'strategy|s=s' => \$_strategy,
178 'local|l' => \$_local,
179 'fetch-all|all' => \$_fetch_all,
180 'dry-run|n' => \$_dry_run,
181 %fc_opts } ],
182 'commit-diff' => [ \&cmd_commit_diff,
183 'Commit a diff between two trees',
184 { 'message|m=s' => \$_message,
185 'file|F=s' => \$_file,
186 'revision|r=s' => \$_revision,
187 %cmt_opts } ],
188 'info' => [ \&cmd_info,
189 "Show info about the latest SVN revision
190 on the current branch",
191 { 'url' => \$_url, } ],
192 'blame' => [ \&Git::SVN::Log::cmd_blame,
193 "Show what revision and author last modified each line of a file",
194 { 'git-format' => \$_git_format } ],
197 my $cmd;
198 for (my $i = 0; $i < @ARGV; $i++) {
199 if (defined $cmd{$ARGV[$i]}) {
200 $cmd = $ARGV[$i];
201 splice @ARGV, $i, 1;
202 last;
206 # make sure we're always running at the top-level working directory
207 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
208 unless (-d $ENV{GIT_DIR}) {
209 if ($git_dir_user_set) {
210 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
211 "but it is not a directory\n";
213 my $git_dir = delete $ENV{GIT_DIR};
214 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
215 unless (length $cdup) {
216 die "Already at toplevel, but $git_dir ",
217 "not found '$cdup'\n";
219 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
220 unless (-d $git_dir) {
221 die "$git_dir still not found after going to ",
222 "'$cdup'\n";
224 $ENV{GIT_DIR} = $git_dir;
226 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
229 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
231 read_repo_config(\%opts);
232 Getopt::Long::Configure('pass_through') if ($cmd && ($cmd eq 'log' || $cmd eq 'blame'));
233 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
234 'minimize-connections' => \$Git::SVN::Migration::_minimize,
235 'id|i=s' => \$Git::SVN::default_ref_id,
236 'svn-remote|remote|R=s' => sub {
237 $Git::SVN::no_reuse_existing = 1;
238 $Git::SVN::default_repo_id = $_[1] });
239 exit 1 if (!$rv && $cmd && $cmd ne 'log');
241 usage(0) if $_help;
242 version() if $_version;
243 usage(1) unless defined $cmd;
244 load_authors() if $_authors;
246 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
247 Git::SVN::Migration::migration_check();
249 Git::SVN::init_vars();
250 eval {
251 Git::SVN::verify_remotes_sanity();
252 $cmd{$cmd}->[0]->(@ARGV);
254 fatal $@ if $@;
255 post_fetch_checkout();
256 exit 0;
258 ####################### primary functions ######################
259 sub usage {
260 my $exit = shift || 0;
261 my $fd = $exit ? \*STDERR : \*STDOUT;
262 print $fd <<"";
263 git-svn - bidirectional operations between a single Subversion tree and git
264 Usage: $0 <command> [options] [arguments]\n
266 print $fd "Available commands:\n" unless $cmd;
268 foreach (sort keys %cmd) {
269 next if $cmd && $cmd ne $_;
270 next if /^multi-/; # don't show deprecated commands
271 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
272 foreach (sort keys %{$cmd{$_}->[2]}) {
273 # mixed-case options are for .git/config only
274 next if /[A-Z]/ && /^[a-z]+$/i;
275 # prints out arguments as they should be passed:
276 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
277 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
278 "--$_" : "-$_" }
279 split /\|/,$_)," $x\n";
282 print $fd <<"";
283 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
284 arbitrary identifier if you're tracking multiple SVN branches/repositories in
285 one git repository and want to keep them separate. See git-svn(1) for more
286 information.
288 exit $exit;
291 sub version {
292 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
293 exit 0;
296 sub do_git_init_db {
297 unless (-d $ENV{GIT_DIR}) {
298 my @init_db = ('init');
299 push @init_db, "--template=$_template" if defined $_template;
300 if (defined $_shared) {
301 if ($_shared =~ /[a-z]/) {
302 push @init_db, "--shared=$_shared";
303 } else {
304 push @init_db, "--shared";
307 command_noisy(@init_db);
308 $_repository = Git->repository(Repository => ".git");
310 my $set;
311 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
312 foreach my $i (keys %icv) {
313 die "'$set' and '$i' cannot both be set\n" if $set;
314 next unless defined $icv{$i};
315 command_noisy('config', "$pfx.$i", $icv{$i});
316 $set = $i;
320 sub init_subdir {
321 my $repo_path = shift or return;
322 mkpath([$repo_path]) unless -d $repo_path;
323 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
324 $ENV{GIT_DIR} = '.git';
325 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
328 sub cmd_clone {
329 my ($url, $path) = @_;
330 if (!defined $path &&
331 (defined $_trunk || defined $_branches || defined $_tags ||
332 defined $_stdlayout) &&
333 $url !~ m#^[a-z\+]+://#) {
334 $path = $url;
336 $path = basename($url) if !defined $path || !length $path;
337 cmd_init($url, $path);
338 Git::SVN::fetch_all($Git::SVN::default_repo_id);
341 sub cmd_init {
342 if (defined $_stdlayout) {
343 $_trunk = 'trunk' if (!defined $_trunk);
344 $_tags = 'tags' if (!defined $_tags);
345 $_branches = 'branches' if (!defined $_branches);
347 if (defined $_trunk || defined $_branches || defined $_tags) {
348 return cmd_multi_init(@_);
350 my $url = shift or die "SVN repository location required ",
351 "as a command-line argument\n";
352 init_subdir(@_);
353 do_git_init_db();
355 Git::SVN->init($url);
358 sub cmd_fetch {
359 if (grep /^\d+=./, @_) {
360 die "'<rev>=<commit>' fetch arguments are ",
361 "no longer supported.\n";
363 my ($remote) = @_;
364 if (@_ > 1) {
365 die "Usage: $0 fetch [--all] [svn-remote]\n";
367 $remote ||= $Git::SVN::default_repo_id;
368 if ($_fetch_all) {
369 cmd_multi_fetch();
370 } else {
371 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
375 sub cmd_set_tree {
376 my (@commits) = @_;
377 if ($_stdin || !@commits) {
378 print "Reading from stdin...\n";
379 @commits = ();
380 while (<STDIN>) {
381 if (/\b($sha1_short)\b/o) {
382 unshift @commits, $1;
386 my @revs;
387 foreach my $c (@commits) {
388 my @tmp = command('rev-parse',$c);
389 if (scalar @tmp == 1) {
390 push @revs, $tmp[0];
391 } elsif (scalar @tmp > 1) {
392 push @revs, reverse(command('rev-list',@tmp));
393 } else {
394 fatal "Failed to rev-parse $c";
397 my $gs = Git::SVN->new;
398 my ($r_last, $cmt_last) = $gs->last_rev_commit;
399 $gs->fetch;
400 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
401 fatal "There are new revisions that were fetched ",
402 "and need to be merged (or acknowledged) ",
403 "before committing.\nlast rev: $r_last\n",
404 " current: $gs->{last_rev}";
406 $gs->set_tree($_) foreach @revs;
407 print "Done committing ",scalar @revs," revisions to SVN\n";
408 unlink $gs->{index};
411 sub cmd_dcommit {
412 my $head = shift;
413 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
414 'Cannot dcommit with a dirty index. Commit your changes first, '
415 . "or stash them with `git stash'.\n";
416 $head ||= 'HEAD';
417 my @refs;
418 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
419 if ($url) {
420 print "Committing to $url ...\n";
422 unless ($gs) {
423 die "Unable to determine upstream SVN information from ",
424 "$head history.\nPerhaps the repository is empty.";
426 my $last_rev;
427 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
428 if ($_no_rebase && scalar(@$linear_refs) > 1) {
429 warn "Attempting to commit more than one change while ",
430 "--no-rebase is enabled.\n",
431 "If these changes depend on each other, re-running ",
432 "without --no-rebase may be required."
434 while (1) {
435 my $d = shift @$linear_refs or last;
436 unless (defined $last_rev) {
437 (undef, $last_rev, undef) = cmt_metadata("$d~1");
438 unless (defined $last_rev) {
439 fatal "Unable to extract revision information ",
440 "from commit $d~1";
443 if ($_dry_run) {
444 print "diff-tree $d~1 $d\n";
445 } else {
446 my $cmt_rev;
447 my %ed_opts = ( r => $last_rev,
448 log => get_commit_entry($d)->{log},
449 ra => Git::SVN::Ra->new($gs->full_url),
450 config => SVN::Core::config_get_config(
451 $Git::SVN::Ra::config_dir
453 tree_a => "$d~1",
454 tree_b => $d,
455 editor_cb => sub {
456 print "Committed r$_[0]\n";
457 $cmt_rev = $_[0];
459 svn_path => '');
460 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
461 print "No changes\n$d~1 == $d\n";
462 } elsif ($parents->{$d} && @{$parents->{$d}}) {
463 $gs->{inject_parents_dcommit}->{$cmt_rev} =
464 $parents->{$d};
466 $_fetch_all ? $gs->fetch_all : $gs->fetch;
467 $last_rev = $cmt_rev;
468 next if $_no_rebase;
470 # we always want to rebase against the current HEAD,
471 # not any head that was passed to us
472 my @diff = command('diff-tree', $d,
473 $gs->refname, '--');
474 my @finish;
475 if (@diff) {
476 @finish = rebase_cmd();
477 print STDERR "W: $d and ", $gs->refname,
478 " differ, using @finish:\n",
479 join("\n", @diff), "\n";
480 } else {
481 print "No changes between current HEAD and ",
482 $gs->refname,
483 "\nResetting to the latest ",
484 $gs->refname, "\n";
485 @finish = qw/reset --mixed/;
487 command_noisy(@finish, $gs->refname);
488 if (@diff) {
489 @refs = ();
490 my ($url_, $rev_, $uuid_, $gs_) =
491 working_head_info($head, \@refs);
492 my ($linear_refs_, $parents_) =
493 linearize_history($gs_, \@refs);
494 if (scalar(@$linear_refs) !=
495 scalar(@$linear_refs_)) {
496 fatal "# of revisions changed ",
497 "\nbefore:\n",
498 join("\n", @$linear_refs),
499 "\n\nafter:\n",
500 join("\n", @$linear_refs_), "\n",
501 'If you are attempting to commit ',
502 "merges, try running:\n\t",
503 'git rebase --interactive',
504 '--preserve-merges ',
505 $gs->refname,
506 "\nBefore dcommitting";
508 if ($url_ ne $url) {
509 fatal "URL mismatch after rebase: ",
510 "$url_ != $url";
512 if ($uuid_ ne $uuid) {
513 fatal "uuid mismatch after rebase: ",
514 "$uuid_ != $uuid";
516 # remap parents
517 my (%p, @l, $i);
518 for ($i = 0; $i < scalar @$linear_refs; $i++) {
519 my $new = $linear_refs_->[$i] or next;
520 $p{$new} =
521 $parents->{$linear_refs->[$i]};
522 push @l, $new;
524 $parents = \%p;
525 $linear_refs = \@l;
529 unlink $gs->{index};
532 sub cmd_find_rev {
533 my $revision_or_hash = shift or die "SVN or git revision required ",
534 "as a command-line argument\n";
535 my $result;
536 if ($revision_or_hash =~ /^r\d+$/) {
537 my $head = shift;
538 $head ||= 'HEAD';
539 my @refs;
540 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
541 unless ($gs) {
542 die "Unable to determine upstream SVN information from ",
543 "$head history\n";
545 my $desired_revision = substr($revision_or_hash, 1);
546 $result = $gs->rev_map_get($desired_revision);
547 } else {
548 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
549 $result = $rev;
551 print "$result\n" if $result;
554 sub cmd_rebase {
555 command_noisy(qw/update-index --refresh/);
556 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
557 unless ($gs) {
558 die "Unable to determine upstream SVN information from ",
559 "working tree history\n";
561 if ($_dry_run) {
562 print "Remote Branch: " . $gs->refname . "\n";
563 print "SVN URL: " . $url . "\n";
564 return;
566 if (command(qw/diff-index HEAD --/)) {
567 print STDERR "Cannot rebase with uncommited changes:\n";
568 command_noisy('status');
569 exit 1;
571 unless ($_local) {
572 # rebase will checkout for us, so no need to do it explicitly
573 $_no_checkout = 'true';
574 $_fetch_all ? $gs->fetch_all : $gs->fetch;
576 command_noisy(rebase_cmd(), $gs->refname);
579 sub cmd_show_ignore {
580 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
581 $gs ||= Git::SVN->new;
582 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
583 $gs->prop_walk($gs->{path}, $r, sub {
584 my ($gs, $path, $props) = @_;
585 print STDOUT "\n# $path\n";
586 my $s = $props->{'svn:ignore'} or return;
587 $s =~ s/[\r\n]+/\n/g;
588 chomp $s;
589 $s =~ s#^#$path#gm;
590 print STDOUT "$s\n";
594 sub cmd_show_externals {
595 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
596 $gs ||= Git::SVN->new;
597 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
598 $gs->prop_walk($gs->{path}, $r, sub {
599 my ($gs, $path, $props) = @_;
600 print STDOUT "\n# $path\n";
601 my $s = $props->{'svn:externals'} or return;
602 $s =~ s/[\r\n]+/\n/g;
603 chomp $s;
604 $s =~ s#^#$path#gm;
605 print STDOUT "$s\n";
609 sub cmd_create_ignore {
610 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
611 $gs ||= Git::SVN->new;
612 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
613 $gs->prop_walk($gs->{path}, $r, sub {
614 my ($gs, $path, $props) = @_;
615 # $path is of the form /path/to/dir/
616 my $ignore = '.' . $path . '.gitignore';
617 my $s = $props->{'svn:ignore'} or return;
618 open(GITIGNORE, '>', $ignore)
619 or fatal("Failed to open `$ignore' for writing: $!");
620 $s =~ s/[\r\n]+/\n/g;
621 chomp $s;
622 # Prefix all patterns so that the ignore doesn't apply
623 # to sub-directories.
624 $s =~ s#^#/#gm;
625 print GITIGNORE "$s\n";
626 close(GITIGNORE)
627 or fatal("Failed to close `$ignore': $!");
628 command_noisy('add', '-f', $ignore);
632 sub canonicalize_path {
633 my ($path) = @_;
634 my $dot_slash_added = 0;
635 if (substr($path, 0, 1) ne "/") {
636 $path = "./" . $path;
637 $dot_slash_added = 1;
639 # File::Spec->canonpath doesn't collapse x/../y into y (for a
640 # good reason), so let's do this manually.
641 $path =~ s#/+#/#g;
642 $path =~ s#/\.(?:/|$)#/#g;
643 $path =~ s#/[^/]+/\.\.##g;
644 $path =~ s#/$##g;
645 $path =~ s#^\./## if $dot_slash_added;
646 return $path;
649 # get_svnprops(PATH)
650 # ------------------
651 # Helper for cmd_propget and cmd_proplist below.
652 sub get_svnprops {
653 my $path = shift;
654 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
655 $gs ||= Git::SVN->new;
657 # prefix THE PATH by the sub-directory from which the user
658 # invoked us.
659 $path = $cmd_dir_prefix . $path;
660 fatal("No such file or directory: $path") unless -e $path;
661 my $is_dir = -d $path ? 1 : 0;
662 $path = $gs->{path} . '/' . $path;
664 # canonicalize the path (otherwise libsvn will abort or fail to
665 # find the file)
666 $path = canonicalize_path($path);
668 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
669 my $props;
670 if ($is_dir) {
671 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
673 else {
674 (undef, $props) = $gs->ra->get_file($path, $r, undef);
676 return $props;
679 # cmd_propget (PROP, PATH)
680 # ------------------------
681 # Print the SVN property PROP for PATH.
682 sub cmd_propget {
683 my ($prop, $path) = @_;
684 $path = '.' if not defined $path;
685 usage(1) if not defined $prop;
686 my $props = get_svnprops($path);
687 if (not defined $props->{$prop}) {
688 fatal("`$path' does not have a `$prop' SVN property.");
690 print $props->{$prop} . "\n";
693 # cmd_proplist (PATH)
694 # -------------------
695 # Print the list of SVN properties for PATH.
696 sub cmd_proplist {
697 my $path = shift;
698 $path = '.' if not defined $path;
699 my $props = get_svnprops($path);
700 print "Properties on '$path':\n";
701 foreach (sort keys %{$props}) {
702 print " $_\n";
706 sub cmd_multi_init {
707 my $url = shift;
708 unless (defined $_trunk || defined $_branches || defined $_tags) {
709 usage(1);
712 # there are currently some bugs that prevent multi-init/multi-fetch
713 # setups from working well without this.
714 $Git::SVN::_minimize_url = 1;
716 $_prefix = '' unless defined $_prefix;
717 if (defined $url) {
718 $url =~ s#/+$##;
719 init_subdir(@_);
721 do_git_init_db();
722 if (defined $_trunk) {
723 my $trunk_ref = $_prefix . 'trunk';
724 # try both old-style and new-style lookups:
725 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
726 unless ($gs_trunk) {
727 my ($trunk_url, $trunk_path) =
728 complete_svn_url($url, $_trunk);
729 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
730 undef, $trunk_ref);
733 return unless defined $_branches || defined $_tags;
734 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
735 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
736 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
739 sub cmd_multi_fetch {
740 my $remotes = Git::SVN::read_all_remotes();
741 foreach my $repo_id (sort keys %$remotes) {
742 if ($remotes->{$repo_id}->{url}) {
743 Git::SVN::fetch_all($repo_id, $remotes);
748 # this command is special because it requires no metadata
749 sub cmd_commit_diff {
750 my ($ta, $tb, $url) = @_;
751 my $usage = "Usage: $0 commit-diff -r<revision> ".
752 "<tree-ish> <tree-ish> [<URL>]";
753 fatal($usage) if (!defined $ta || !defined $tb);
754 my $svn_path = '';
755 if (!defined $url) {
756 my $gs = eval { Git::SVN->new };
757 if (!$gs) {
758 fatal("Needed URL or usable git-svn --id in ",
759 "the command-line\n", $usage);
761 $url = $gs->{url};
762 $svn_path = $gs->{path};
764 unless (defined $_revision) {
765 fatal("-r|--revision is a required argument\n", $usage);
767 if (defined $_message && defined $_file) {
768 fatal("Both --message/-m and --file/-F specified ",
769 "for the commit message.\n",
770 "I have no idea what you mean");
772 if (defined $_file) {
773 $_message = file_to_s($_file);
774 } else {
775 $_message ||= get_commit_entry($tb)->{log};
777 my $ra ||= Git::SVN::Ra->new($url);
778 my $r = $_revision;
779 if ($r eq 'HEAD') {
780 $r = $ra->get_latest_revnum;
781 } elsif ($r !~ /^\d+$/) {
782 die "revision argument: $r not understood by git-svn\n";
784 my %ed_opts = ( r => $r,
785 log => $_message,
786 ra => $ra,
787 tree_a => $ta,
788 tree_b => $tb,
789 editor_cb => sub { print "Committed r$_[0]\n" },
790 svn_path => $svn_path );
791 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
792 print "No changes\n$ta == $tb\n";
796 sub cmd_info {
797 my $path = canonicalize_path(shift or ".");
798 unless (scalar(@_) == 0) {
799 die "Too many arguments specified\n";
802 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
804 if (!$file_type && !$diff_status) {
805 print STDERR "$path: (Not a versioned resource)\n\n";
806 return;
809 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
810 unless ($gs) {
811 die "Unable to determine upstream SVN information from ",
812 "working tree history\n";
814 my $full_url = $url . ($path eq "." ? "" : "/$path");
816 if ($_url) {
817 print $full_url, "\n";
818 return;
821 my $result = "Path: $path\n";
822 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
823 $result .= "URL: " . $full_url . "\n";
825 eval {
826 my $repos_root = $gs->repos_root;
827 Git::SVN::remove_username($repos_root);
828 $result .= "Repository Root: $repos_root\n";
830 if ($@) {
831 $result .= "Repository Root: (offline)\n";
833 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
834 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
836 $result .= "Node Kind: " .
837 ($file_type eq "dir" ? "directory" : "file") . "\n";
839 my $schedule = $diff_status eq "A"
840 ? "add"
841 : ($diff_status eq "D" ? "delete" : "normal");
842 $result .= "Schedule: $schedule\n";
844 if ($diff_status eq "A") {
845 print $result, "\n";
846 return;
849 my ($lc_author, $lc_rev, $lc_date_utc);
850 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
851 my $log = command_output_pipe(@args);
852 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
853 while (<$log>) {
854 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
855 $lc_author = $1;
856 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
857 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
858 (undef, $lc_rev, undef) = ::extract_metadata($1);
861 close $log;
863 Git::SVN::Log::set_local_timezone();
865 $result .= "Last Changed Author: $lc_author\n";
866 $result .= "Last Changed Rev: $lc_rev\n";
867 $result .= "Last Changed Date: " .
868 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
870 if ($file_type ne "dir") {
871 my $text_last_updated_date =
872 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
873 $result .=
874 "Text Last Updated: " .
875 Git::SVN::Log::format_svn_date($text_last_updated_date) .
876 "\n";
877 my $checksum;
878 if ($diff_status eq "D") {
879 my ($fh, $ctx) =
880 command_output_pipe(qw(cat-file blob), "HEAD:$path");
881 if ($file_type eq "link") {
882 my $file_name = <$fh>;
883 $checksum = md5sum("link $file_name");
884 } else {
885 $checksum = md5sum($fh);
887 command_close_pipe($fh, $ctx);
888 } elsif ($file_type eq "link") {
889 my $file_name =
890 command(qw(cat-file blob), "HEAD:$path");
891 $checksum =
892 md5sum("link " . $file_name);
893 } else {
894 open FILE, "<", $path or die $!;
895 $checksum = md5sum(\*FILE);
896 close FILE or die $!;
898 $result .= "Checksum: " . $checksum . "\n";
901 print $result, "\n";
904 ########################### utility functions #########################
906 sub rebase_cmd {
907 my @cmd = qw/rebase/;
908 push @cmd, '-v' if $_verbose;
909 push @cmd, qw/--merge/ if $_merge;
910 push @cmd, "--strategy=$_strategy" if $_strategy;
911 @cmd;
914 sub post_fetch_checkout {
915 return if $_no_checkout;
916 my $gs = $Git::SVN::_head or return;
917 return if verify_ref('refs/heads/master^0');
919 my $valid_head = verify_ref('HEAD^0');
920 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
921 return if ($valid_head || !verify_ref('HEAD^0'));
923 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
924 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
925 return if -f $index;
927 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
928 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
929 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
930 print STDERR "Checked out HEAD:\n ",
931 $gs->full_url, " r", $gs->last_rev, "\n";
934 sub complete_svn_url {
935 my ($url, $path) = @_;
936 $path =~ s#/+$##;
937 if ($path !~ m#^[a-z\+]+://#) {
938 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
939 fatal("E: '$path' is not a complete URL ",
940 "and a separate URL is not specified");
942 return ($url, $path);
944 return ($path, '');
947 sub complete_url_ls_init {
948 my ($ra, $repo_path, $switch, $pfx) = @_;
949 unless ($repo_path) {
950 print STDERR "W: $switch not specified\n";
951 return;
953 $repo_path =~ s#/+$##;
954 if ($repo_path =~ m#^[a-z\+]+://#) {
955 $ra = Git::SVN::Ra->new($repo_path);
956 $repo_path = '';
957 } else {
958 $repo_path =~ s#^/+##;
959 unless ($ra) {
960 fatal("E: '$repo_path' is not a complete URL ",
961 "and a separate URL is not specified");
964 my $url = $ra->{url};
965 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
966 my $k = "svn-remote.$gs->{repo_id}.url";
967 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
968 if ($orig_url && ($orig_url ne $gs->{url})) {
969 die "$k already set: $orig_url\n",
970 "wanted to set to: $gs->{url}\n";
972 command_oneline('config', $k, $gs->{url}) unless $orig_url;
973 my $remote_path = "$ra->{svn_path}/$repo_path";
974 $remote_path =~ s#/+#/#g;
975 $remote_path =~ s#^/##g;
976 $remote_path .= "/*" if $remote_path !~ /\*/;
977 my ($n) = ($switch =~ /^--(\w+)/);
978 if (length $pfx && $pfx !~ m#/$#) {
979 die "--prefix='$pfx' must have a trailing slash '/'\n";
981 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
982 "$remote_path:refs/remotes/$pfx*");
985 sub verify_ref {
986 my ($ref) = @_;
987 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
988 { STDERR => 0 }); };
991 sub get_tree_from_treeish {
992 my ($treeish) = @_;
993 # $treeish can be a symbolic ref, too:
994 my $type = command_oneline(qw/cat-file -t/, $treeish);
995 my $expected;
996 while ($type eq 'tag') {
997 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
999 if ($type eq 'commit') {
1000 $expected = (grep /^tree /, command(qw/cat-file commit/,
1001 $treeish))[0];
1002 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1003 die "Unable to get tree from $treeish\n" unless $expected;
1004 } elsif ($type eq 'tree') {
1005 $expected = $treeish;
1006 } else {
1007 die "$treeish is a $type, expected tree, tag or commit\n";
1009 return $expected;
1012 sub get_commit_entry {
1013 my ($treeish) = shift;
1014 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1015 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1016 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1017 open my $log_fh, '>', $commit_editmsg or croak $!;
1019 my $type = command_oneline(qw/cat-file -t/, $treeish);
1020 if ($type eq 'commit' || $type eq 'tag') {
1021 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1022 $type, $treeish);
1023 my $in_msg = 0;
1024 my $author;
1025 my $saw_from = 0;
1026 while (<$msg_fh>) {
1027 if (!$in_msg) {
1028 $in_msg = 1 if (/^\s*$/);
1029 $author = $1 if (/^author (.*>)/);
1030 } elsif (/^git-svn-id: /) {
1031 # skip this for now, we regenerate the
1032 # correct one on re-fetch anyways
1033 # TODO: set *:merge properties or like...
1034 } else {
1035 if (/^From:/ || /^Signed-off-by:/) {
1036 $saw_from = 1;
1038 print $log_fh $_ or croak $!;
1041 if ($Git::SVN::_add_author_from && defined($author)
1042 && !$saw_from) {
1043 print $log_fh "\nFrom: $author\n"
1044 or croak $!;
1046 command_close_pipe($msg_fh, $ctx);
1048 close $log_fh or croak $!;
1050 if ($_edit || ($type eq 'tree')) {
1051 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1052 # TODO: strip out spaces, comments, like git-commit.sh
1053 system($editor, $commit_editmsg);
1055 rename $commit_editmsg, $commit_msg or croak $!;
1056 open $log_fh, '<', $commit_msg or croak $!;
1057 { local $/; chomp($log_entry{log} = <$log_fh>); }
1058 close $log_fh or croak $!;
1059 unlink $commit_msg;
1060 \%log_entry;
1063 sub s_to_file {
1064 my ($str, $file, $mode) = @_;
1065 open my $fd,'>',$file or croak $!;
1066 print $fd $str,"\n" or croak $!;
1067 close $fd or croak $!;
1068 chmod ($mode &~ umask, $file) if (defined $mode);
1071 sub file_to_s {
1072 my $file = shift;
1073 open my $fd,'<',$file or croak "$!: file: $file\n";
1074 local $/;
1075 my $ret = <$fd>;
1076 close $fd or croak $!;
1077 $ret =~ s/\s*$//s;
1078 return $ret;
1081 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1082 sub load_authors {
1083 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1084 my $log = $cmd eq 'log';
1085 while (<$authors>) {
1086 chomp;
1087 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1088 my ($user, $name, $email) = ($1, $2, $3);
1089 if ($log) {
1090 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1091 } else {
1092 $users{$user} = [$name, $email];
1095 close $authors or croak $!;
1098 # convert GetOpt::Long specs for use by git-config
1099 sub read_repo_config {
1100 return unless -d $ENV{GIT_DIR};
1101 my $opts = shift;
1102 my @config_only;
1103 foreach my $o (keys %$opts) {
1104 # if we have mixedCase and a long option-only, then
1105 # it's a config-only variable that we don't need for
1106 # the command-line.
1107 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1108 my $v = $opts->{$o};
1109 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1110 $key =~ s/-//g;
1111 my $arg = 'git-config';
1112 $arg .= ' --int' if ($o =~ /[:=]i$/);
1113 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1114 if (ref $v eq 'ARRAY') {
1115 chomp(my @tmp = `$arg --get-all svn.$key`);
1116 @$v = @tmp if @tmp;
1117 } else {
1118 chomp(my $tmp = `$arg --get svn.$key`);
1119 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1120 $$v = $tmp;
1124 delete @$opts{@config_only} if @config_only;
1127 sub extract_metadata {
1128 my $id = shift or return (undef, undef, undef);
1129 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1130 \s([a-f\d\-]+)$/x);
1131 if (!defined $rev || !$uuid || !$url) {
1132 # some of the original repositories I made had
1133 # identifiers like this:
1134 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1136 return ($url, $rev, $uuid);
1139 sub cmt_metadata {
1140 return extract_metadata((grep(/^git-svn-id: /,
1141 command(qw/cat-file commit/, shift)))[-1]);
1144 sub working_head_info {
1145 my ($head, $refs) = @_;
1146 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1147 my ($fh, $ctx) = command_output_pipe(@args, $head);
1148 my $hash;
1149 my %max;
1150 while (<$fh>) {
1151 if ( m{^commit ($::sha1)$} ) {
1152 unshift @$refs, $hash if $hash and $refs;
1153 $hash = $1;
1154 next;
1156 next unless s{^\s*(git-svn-id:)}{$1};
1157 my ($url, $rev, $uuid) = extract_metadata($_);
1158 if (defined $url && defined $rev) {
1159 next if $max{$url} and $max{$url} < $rev;
1160 if (my $gs = Git::SVN->find_by_url($url)) {
1161 my $c = $gs->rev_map_get($rev);
1162 if ($c && $c eq $hash) {
1163 close $fh; # break the pipe
1164 return ($url, $rev, $uuid, $gs);
1165 } else {
1166 $max{$url} ||= $gs->rev_map_max;
1171 command_close_pipe($fh, $ctx);
1172 (undef, undef, undef, undef);
1175 sub read_commit_parents {
1176 my ($parents, $c) = @_;
1177 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1178 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1179 @{$parents->{$c}} = split(/ /, $p);
1182 sub linearize_history {
1183 my ($gs, $refs) = @_;
1184 my %parents;
1185 foreach my $c (@$refs) {
1186 read_commit_parents(\%parents, $c);
1189 my @linear_refs;
1190 my %skip = ();
1191 my $last_svn_commit = $gs->last_commit;
1192 foreach my $c (reverse @$refs) {
1193 next if $c eq $last_svn_commit;
1194 last if $skip{$c};
1196 unshift @linear_refs, $c;
1197 $skip{$c} = 1;
1199 # we only want the first parent to diff against for linear
1200 # history, we save the rest to inject when we finalize the
1201 # svn commit
1202 my $fp_a = verify_ref("$c~1");
1203 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1204 if (!$fp_a || !$fp_b) {
1205 die "Commit $c\n",
1206 "has no parent commit, and therefore ",
1207 "nothing to diff against.\n",
1208 "You should be working from a repository ",
1209 "originally created by git-svn\n";
1211 if ($fp_a ne $fp_b) {
1212 die "$c~1 = $fp_a, however parsing commit $c ",
1213 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1216 foreach my $p (@{$parents{$c}}) {
1217 $skip{$p} = 1;
1220 (\@linear_refs, \%parents);
1223 sub find_file_type_and_diff_status {
1224 my ($path) = @_;
1225 return ('dir', '') if $path eq '.';
1227 my $diff_output =
1228 command_oneline(qw(diff --cached --name-status --), $path) || "";
1229 my $diff_status = (split(' ', $diff_output))[0] || "";
1231 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1233 return (undef, undef) if !$diff_status && !$ls_tree;
1235 if ($diff_status eq "A") {
1236 return ("link", $diff_status) if -l $path;
1237 return ("dir", $diff_status) if -d $path;
1238 return ("file", $diff_status);
1241 my $mode = (split(' ', $ls_tree))[0] || "";
1243 return ("link", $diff_status) if $mode eq "120000";
1244 return ("dir", $diff_status) if $mode eq "040000";
1245 return ("file", $diff_status);
1248 sub md5sum {
1249 my $arg = shift;
1250 my $ref = ref $arg;
1251 my $md5 = Digest::MD5->new();
1252 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1253 $md5->addfile($arg) or croak $!;
1254 } elsif ($ref eq 'SCALAR') {
1255 $md5->add($$arg) or croak $!;
1256 } elsif (!$ref) {
1257 $md5->add($arg) or croak $!;
1258 } else {
1259 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1261 return $md5->hexdigest();
1264 package Git::SVN;
1265 use strict;
1266 use warnings;
1267 use Fcntl qw/:DEFAULT :seek/;
1268 use constant rev_map_fmt => 'NH40';
1269 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1270 $_repack $_repack_flags $_use_svm_props $_head
1271 $_use_svnsync_props $no_reuse_existing $_minimize_url
1272 $_use_log_author $_add_author_from/;
1273 use Carp qw/croak/;
1274 use File::Path qw/mkpath/;
1275 use File::Copy qw/copy/;
1276 use IPC::Open3;
1278 my ($_gc_nr, $_gc_period);
1280 # properties that we do not log:
1281 my %SKIP_PROP;
1282 BEGIN {
1283 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1284 svn:special svn:executable
1285 svn:entry:committed-rev
1286 svn:entry:last-author
1287 svn:entry:uuid
1288 svn:entry:committed-date/;
1290 # some options are read globally, but can be overridden locally
1291 # per [svn-remote "..."] section. Command-line options will *NOT*
1292 # override options set in an [svn-remote "..."] section
1293 no strict 'refs';
1294 for my $option (qw/follow_parent no_metadata use_svm_props
1295 use_svnsync_props/) {
1296 my $key = $option;
1297 $key =~ tr/_//d;
1298 my $prop = "-$option";
1299 *$option = sub {
1300 my ($self) = @_;
1301 return $self->{$prop} if exists $self->{$prop};
1302 my $k = "svn-remote.$self->{repo_id}.$key";
1303 eval { command_oneline(qw/config --get/, $k) };
1304 if ($@) {
1305 $self->{$prop} = ${"Git::SVN::_$option"};
1306 } else {
1307 my $v = command_oneline(qw/config --bool/,$k);
1308 $self->{$prop} = $v eq 'false' ? 0 : 1;
1310 return $self->{$prop};
1315 my (%LOCKFILES, %INDEX_FILES);
1316 END {
1317 unlink keys %LOCKFILES if %LOCKFILES;
1318 unlink keys %INDEX_FILES if %INDEX_FILES;
1321 sub resolve_local_globs {
1322 my ($url, $fetch, $glob_spec) = @_;
1323 return unless defined $glob_spec;
1324 my $ref = $glob_spec->{ref};
1325 my $path = $glob_spec->{path};
1326 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1327 next unless m#^refs/remotes/$ref->{regex}$#;
1328 my $p = $1;
1329 my $pathname = desanitize_refname($path->full_path($p));
1330 my $refname = desanitize_refname($ref->full_path($p));
1331 if (my $existing = $fetch->{$pathname}) {
1332 if ($existing ne $refname) {
1333 die "Refspec conflict:\n",
1334 "existing: refs/remotes/$existing\n",
1335 " globbed: refs/remotes/$refname\n";
1337 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1338 $u =~ s!^\Q$url\E(/|$)!! or die
1339 "refs/remotes/$refname: '$url' not found in '$u'\n";
1340 if ($pathname ne $u) {
1341 warn "W: Refspec glob conflict ",
1342 "(ref: refs/remotes/$refname):\n",
1343 "expected path: $pathname\n",
1344 " real path: $u\n",
1345 "Continuing ahead with $u\n";
1346 next;
1348 } else {
1349 $fetch->{$pathname} = $refname;
1354 sub parse_revision_argument {
1355 my ($base, $head) = @_;
1356 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1357 return ($base, $head);
1359 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1360 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1361 return ($head, $head) if ($::_revision eq 'HEAD');
1362 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1363 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1364 die "revision argument: $::_revision not understood by git-svn\n";
1367 sub fetch_all {
1368 my ($repo_id, $remotes) = @_;
1369 if (ref $repo_id) {
1370 my $gs = $repo_id;
1371 $repo_id = undef;
1372 $repo_id = $gs->{repo_id};
1374 $remotes ||= read_all_remotes();
1375 my $remote = $remotes->{$repo_id} or
1376 die "[svn-remote \"$repo_id\"] unknown\n";
1377 my $fetch = $remote->{fetch};
1378 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1379 my (@gs, @globs);
1380 my $ra = Git::SVN::Ra->new($url);
1381 my $uuid = $ra->get_uuid;
1382 my $head = $ra->get_latest_revnum;
1383 my $base = defined $fetch ? $head : 0;
1385 # read the max revs for wildcard expansion (branches/*, tags/*)
1386 foreach my $t (qw/branches tags/) {
1387 defined $remote->{$t} or next;
1388 push @globs, $remote->{$t};
1389 my $max_rev = eval { tmp_config(qw/--int --get/,
1390 "svn-remote.$repo_id.${t}-maxRev") };
1391 if (defined $max_rev && ($max_rev < $base)) {
1392 $base = $max_rev;
1393 } elsif (!defined $max_rev) {
1394 $base = 0;
1398 if ($fetch) {
1399 foreach my $p (sort keys %$fetch) {
1400 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1401 my $lr = $gs->rev_map_max;
1402 if (defined $lr) {
1403 $base = $lr if ($lr < $base);
1405 push @gs, $gs;
1409 ($base, $head) = parse_revision_argument($base, $head);
1410 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1413 sub read_all_remotes {
1414 my $r = {};
1415 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1416 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1417 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1418 $local_ref =~ s{^/}{};
1419 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1420 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1421 $r->{$1}->{url} = $2;
1422 } elsif (m!^(.+)\.(branches|tags)=
1423 (.*):refs/remotes/(.+)\s*$/!x) {
1424 my ($p, $g) = ($3, $4);
1425 my $rs = $r->{$1}->{$2} = {
1426 t => $2,
1427 remote => $1,
1428 path => Git::SVN::GlobSpec->new($p),
1429 ref => Git::SVN::GlobSpec->new($g) };
1430 if (length($rs->{ref}->{right}) != 0) {
1431 die "The '*' glob character must be the last ",
1432 "character of '$g'\n";
1439 sub init_vars {
1440 $_gc_nr = $_gc_period = 1000;
1441 if (defined $_repack || defined $_repack_flags) {
1442 warn "Repack options are obsolete; they have no effect.\n";
1446 sub verify_remotes_sanity {
1447 return unless -d $ENV{GIT_DIR};
1448 my %seen;
1449 foreach (command(qw/config -l/)) {
1450 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1451 if ($seen{$1}) {
1452 die "Remote ref refs/remote/$1 is tracked by",
1453 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1454 "Please resolve this ambiguity in ",
1455 "your git configuration file before ",
1456 "continuing\n";
1458 $seen{$1} = $_;
1463 # we allow more chars than remotes2config.sh...
1464 sub sanitize_remote_name {
1465 my ($name) = @_;
1466 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1467 $name;
1470 sub find_existing_remote {
1471 my ($url, $remotes) = @_;
1472 return undef if $no_reuse_existing;
1473 my $existing;
1474 foreach my $repo_id (keys %$remotes) {
1475 my $u = $remotes->{$repo_id}->{url} or next;
1476 next if $u ne $url;
1477 $existing = $repo_id;
1478 last;
1480 $existing;
1483 sub init_remote_config {
1484 my ($self, $url, $no_write) = @_;
1485 $url =~ s!/+$!!; # strip trailing slash
1486 my $r = read_all_remotes();
1487 my $existing = find_existing_remote($url, $r);
1488 if ($existing) {
1489 unless ($no_write) {
1490 print STDERR "Using existing ",
1491 "[svn-remote \"$existing\"]\n";
1493 $self->{repo_id} = $existing;
1494 } elsif ($_minimize_url) {
1495 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1496 $existing = find_existing_remote($min_url, $r);
1497 if ($existing) {
1498 unless ($no_write) {
1499 print STDERR "Using existing ",
1500 "[svn-remote \"$existing\"]\n";
1502 $self->{repo_id} = $existing;
1504 if ($min_url ne $url) {
1505 unless ($no_write) {
1506 print STDERR "Using higher level of URL: ",
1507 "$url => $min_url\n";
1509 my $old_path = $self->{path};
1510 $self->{path} = $url;
1511 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1512 if (length $old_path) {
1513 $self->{path} .= "/$old_path";
1515 $url = $min_url;
1518 my $orig_url;
1519 if (!$existing) {
1520 # verify that we aren't overwriting anything:
1521 $orig_url = eval {
1522 command_oneline('config', '--get',
1523 "svn-remote.$self->{repo_id}.url")
1525 if ($orig_url && ($orig_url ne $url)) {
1526 die "svn-remote.$self->{repo_id}.url already set: ",
1527 "$orig_url\nwanted to set to: $url\n";
1530 my ($xrepo_id, $xpath) = find_ref($self->refname);
1531 if (defined $xpath) {
1532 die "svn-remote.$xrepo_id.fetch already set to track ",
1533 "$xpath:refs/remotes/", $self->refname, "\n";
1535 unless ($no_write) {
1536 command_noisy('config',
1537 "svn-remote.$self->{repo_id}.url", $url);
1538 $self->{path} =~ s{^/}{};
1539 command_noisy('config', '--add',
1540 "svn-remote.$self->{repo_id}.fetch",
1541 "$self->{path}:".$self->refname);
1543 $self->{url} = $url;
1546 sub find_by_url { # repos_root and, path are optional
1547 my ($class, $full_url, $repos_root, $path) = @_;
1549 return undef unless defined $full_url;
1550 remove_username($full_url);
1551 remove_username($repos_root) if defined $repos_root;
1552 my $remotes = read_all_remotes();
1553 if (defined $full_url && defined $repos_root && !defined $path) {
1554 $path = $full_url;
1555 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1557 foreach my $repo_id (keys %$remotes) {
1558 my $u = $remotes->{$repo_id}->{url} or next;
1559 remove_username($u);
1560 next if defined $repos_root && $repos_root ne $u;
1562 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1563 foreach (qw/branches tags/) {
1564 resolve_local_globs($u, $fetch,
1565 $remotes->{$repo_id}->{$_});
1567 my $p = $path;
1568 my $rwr = rewrite_root({repo_id => $repo_id});
1569 unless (defined $p) {
1570 $p = $full_url;
1571 my $z = $u;
1572 if ($rwr) {
1573 $z = $rwr;
1575 $p =~ s#^\Q$z\E(?:/|$)## or next;
1577 foreach my $f (keys %$fetch) {
1578 next if $f ne $p;
1579 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1582 undef;
1585 sub init {
1586 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1587 my $self = _new($class, $repo_id, $ref_id, $path);
1588 if (defined $url) {
1589 $self->init_remote_config($url, $no_write);
1591 $self;
1594 sub find_ref {
1595 my ($ref_id) = @_;
1596 foreach (command(qw/config -l/)) {
1597 next unless m!^svn-remote\.(.+)\.fetch=
1598 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1599 my ($repo_id, $path, $ref) = ($1, $2, $3);
1600 if ($ref eq $ref_id) {
1601 $path = '' if ($path =~ m#^\./?#);
1602 return ($repo_id, $path);
1605 (undef, undef, undef);
1608 sub new {
1609 my ($class, $ref_id, $repo_id, $path) = @_;
1610 if (defined $ref_id && !defined $repo_id && !defined $path) {
1611 ($repo_id, $path) = find_ref($ref_id);
1612 if (!defined $repo_id) {
1613 die "Could not find a \"svn-remote.*.fetch\" key ",
1614 "in the repository configuration matching: ",
1615 "refs/remotes/$ref_id\n";
1618 my $self = _new($class, $repo_id, $ref_id, $path);
1619 if (!defined $self->{path} || !length $self->{path}) {
1620 my $fetch = command_oneline('config', '--get',
1621 "svn-remote.$repo_id.fetch",
1622 ":refs/remotes/$ref_id\$") or
1623 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1624 "\":refs/remotes/$ref_id\$\" in config\n";
1625 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1627 $self->{url} = command_oneline('config', '--get',
1628 "svn-remote.$repo_id.url") or
1629 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1630 $self->rebuild;
1631 $self;
1634 sub refname {
1635 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1637 # It cannot end with a slash /, we'll throw up on this because
1638 # SVN can't have directories with a slash in their name, either:
1639 if ($refname =~ m{/$}) {
1640 die "ref: '$refname' ends with a trailing slash, this is ",
1641 "not permitted by git nor Subversion\n";
1644 # It cannot have ASCII control character space, tilde ~, caret ^,
1645 # colon :, question-mark ?, asterisk *, space, or open bracket [
1646 # anywhere.
1648 # Additionally, % must be escaped because it is used for escaping
1649 # and we want our escaped refname to be reversible
1650 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1652 # no slash-separated component can begin with a dot .
1653 # /.* becomes /%2E*
1654 $refname =~ s{/\.}{/%2E}g;
1656 # It cannot have two consecutive dots .. anywhere
1657 # .. becomes %2E%2E
1658 $refname =~ s{\.\.}{%2E%2E}g;
1660 return $refname;
1663 sub desanitize_refname {
1664 my ($refname) = @_;
1665 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1666 return $refname;
1669 sub svm_uuid {
1670 my ($self) = @_;
1671 return $self->{svm}->{uuid} if $self->svm;
1672 $self->ra;
1673 unless ($self->{svm}) {
1674 die "SVM UUID not cached, and reading remotely failed\n";
1676 $self->{svm}->{uuid};
1679 sub svm {
1680 my ($self) = @_;
1681 return $self->{svm} if $self->{svm};
1682 my $svm;
1683 # see if we have it in our config, first:
1684 eval {
1685 my $section = "svn-remote.$self->{repo_id}";
1686 $svm = {
1687 source => tmp_config('--get', "$section.svm-source"),
1688 uuid => tmp_config('--get', "$section.svm-uuid"),
1689 replace => tmp_config('--get', "$section.svm-replace"),
1692 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1693 $self->{svm} = $svm;
1695 $self->{svm};
1698 sub _set_svm_vars {
1699 my ($self, $ra) = @_;
1700 return $ra if $self->svm;
1702 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1703 "(svm:source, svm:uuid) ",
1704 "from the following URLs:\n" );
1705 sub read_svm_props {
1706 my ($self, $ra, $path, $r) = @_;
1707 my $props = ($ra->get_dir($path, $r))[2];
1708 my $src = $props->{'svm:source'};
1709 my $uuid = $props->{'svm:uuid'};
1710 return undef if (!$src || !$uuid);
1712 chomp($src, $uuid);
1714 $uuid =~ m{^[0-9a-f\-]{30,}$}
1715 or die "doesn't look right - svm:uuid is '$uuid'\n";
1717 # the '!' is used to mark the repos_root!/relative/path
1718 $src =~ s{/?!/?}{/};
1719 $src =~ s{/+$}{}; # no trailing slashes please
1720 # username is of no interest
1721 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1723 my $replace = $ra->{url};
1724 $replace .= "/$path" if length $path;
1726 my $section = "svn-remote.$self->{repo_id}";
1727 tmp_config("$section.svm-source", $src);
1728 tmp_config("$section.svm-replace", $replace);
1729 tmp_config("$section.svm-uuid", $uuid);
1730 $self->{svm} = {
1731 source => $src,
1732 uuid => $uuid,
1733 replace => $replace
1737 my $r = $ra->get_latest_revnum;
1738 my $path = $self->{path};
1739 my %tried;
1740 while (length $path) {
1741 unless ($tried{"$self->{url}/$path"}) {
1742 return $ra if $self->read_svm_props($ra, $path, $r);
1743 $tried{"$self->{url}/$path"} = 1;
1745 $path =~ s#/?[^/]+$##;
1747 die "Path: '$path' should be ''\n" if $path ne '';
1748 return $ra if $self->read_svm_props($ra, $path, $r);
1749 $tried{"$self->{url}/$path"} = 1;
1751 if ($ra->{repos_root} eq $self->{url}) {
1752 die @err, (map { " $_\n" } keys %tried), "\n";
1755 # nope, make sure we're connected to the repository root:
1756 my $ok;
1757 my @tried_b;
1758 $path = $ra->{svn_path};
1759 $ra = Git::SVN::Ra->new($ra->{repos_root});
1760 while (length $path) {
1761 unless ($tried{"$ra->{url}/$path"}) {
1762 $ok = $self->read_svm_props($ra, $path, $r);
1763 last if $ok;
1764 $tried{"$ra->{url}/$path"} = 1;
1766 $path =~ s#/?[^/]+$##;
1768 die "Path: '$path' should be ''\n" if $path ne '';
1769 $ok ||= $self->read_svm_props($ra, $path, $r);
1770 $tried{"$ra->{url}/$path"} = 1;
1771 if (!$ok) {
1772 die @err, (map { " $_\n" } keys %tried), "\n";
1774 Git::SVN::Ra->new($self->{url});
1777 sub svnsync {
1778 my ($self) = @_;
1779 return $self->{svnsync} if $self->{svnsync};
1781 if ($self->no_metadata) {
1782 die "Can't have both 'noMetadata' and ",
1783 "'useSvnsyncProps' options set!\n";
1785 if ($self->rewrite_root) {
1786 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1787 "options set!\n";
1790 my $svnsync;
1791 # see if we have it in our config, first:
1792 eval {
1793 my $section = "svn-remote.$self->{repo_id}";
1795 my $url = tmp_config('--get', "$section.svnsync-url");
1796 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1797 die "doesn't look right - svn:sync-from-url is '$url'\n";
1799 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1800 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1801 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1803 $svnsync = { url => $url, uuid => $uuid }
1805 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1806 return $self->{svnsync} = $svnsync;
1809 my $err = "useSvnsyncProps set, but failed to read " .
1810 "svnsync property: svn:sync-from-";
1811 my $rp = $self->ra->rev_proplist(0);
1813 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1814 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1815 die "doesn't look right - svn:sync-from-url is '$url'\n";
1817 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1818 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1819 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1821 my $section = "svn-remote.$self->{repo_id}";
1822 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1823 tmp_config('--add', "$section.svnsync-url", $url);
1824 return $self->{svnsync} = { url => $url, uuid => $uuid };
1827 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1828 # remote lookup (useful for 'git svn log').
1829 sub ra_uuid {
1830 my ($self) = @_;
1831 unless ($self->{ra_uuid}) {
1832 my $key = "svn-remote.$self->{repo_id}.uuid";
1833 my $uuid = eval { tmp_config('--get', $key) };
1834 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1835 $self->{ra_uuid} = $uuid;
1836 } else {
1837 die "ra_uuid called without URL\n" unless $self->{url};
1838 $self->{ra_uuid} = $self->ra->get_uuid;
1839 tmp_config('--add', $key, $self->{ra_uuid});
1842 $self->{ra_uuid};
1845 sub _set_repos_root {
1846 my ($self, $repos_root) = @_;
1847 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1848 $repos_root ||= $self->ra->{repos_root};
1849 tmp_config($k, $repos_root);
1850 $repos_root;
1853 sub repos_root {
1854 my ($self) = @_;
1855 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1856 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1859 sub ra {
1860 my ($self) = shift;
1861 my $ra = Git::SVN::Ra->new($self->{url});
1862 $self->_set_repos_root($ra->{repos_root});
1863 if ($self->use_svm_props && !$self->{svm}) {
1864 if ($self->no_metadata) {
1865 die "Can't have both 'noMetadata' and ",
1866 "'useSvmProps' options set!\n";
1867 } elsif ($self->use_svnsync_props) {
1868 die "Can't have both 'useSvnsyncProps' and ",
1869 "'useSvmProps' options set!\n";
1871 $ra = $self->_set_svm_vars($ra);
1872 $self->{-want_revprops} = 1;
1874 $ra;
1877 sub rel_path {
1878 my ($self) = @_;
1879 my $repos_root = $self->ra->{repos_root};
1880 return $self->{path} if ($self->{url} eq $repos_root);
1881 my $url = $self->{url} .
1882 (length $self->{path} ? "/$self->{path}" : $self->{path});
1883 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1884 $url;
1887 # prop_walk(PATH, REV, SUB)
1888 # -------------------------
1889 # Recursively traverse PATH at revision REV and invoke SUB for each
1890 # directory that contains a SVN property. SUB will be invoked as
1891 # follows: &SUB(gs, path, props); where `gs' is this instance of
1892 # Git::SVN, `path' the path to the directory where the properties
1893 # `props' were found. The `path' will be relative to point of checkout,
1894 # that is, if url://repo/trunk is the current Git branch, and that
1895 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1896 # as `path' (note the trailing `/').
1897 sub prop_walk {
1898 my ($self, $path, $rev, $sub) = @_;
1900 $path =~ s#^/##;
1901 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1902 $path =~ s#^/*#/#g;
1903 my $p = $path;
1904 # Strip the irrelevant part of the path.
1905 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1906 # Ensure the path is terminated by a `/'.
1907 $p =~ s#/*$#/#;
1909 # The properties contain all the internal SVN stuff nobody
1910 # (usually) cares about.
1911 my $interesting_props = 0;
1912 foreach (keys %{$props}) {
1913 # If it doesn't start with `svn:', it must be a
1914 # user-defined property.
1915 ++$interesting_props and next if $_ !~ /^svn:/;
1916 # FIXME: Fragile, if SVN adds new public properties,
1917 # this needs to be updated.
1918 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1919 |eol-style|mime-type
1920 |externals|needs-lock)$/x;
1922 &$sub($self, $p, $props) if $interesting_props;
1924 foreach (sort keys %$dirent) {
1925 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1926 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1930 sub last_rev { ($_[0]->last_rev_commit)[0] }
1931 sub last_commit { ($_[0]->last_rev_commit)[1] }
1933 # returns the newest SVN revision number and newest commit SHA1
1934 sub last_rev_commit {
1935 my ($self) = @_;
1936 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1937 return ($self->{last_rev}, $self->{last_commit});
1939 my $c = ::verify_ref($self->refname.'^0');
1940 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1941 my $rev = (::cmt_metadata($c))[1];
1942 if (defined $rev) {
1943 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1944 return ($rev, $c);
1947 my $map_path = $self->map_path;
1948 unless (-e $map_path) {
1949 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1950 return (undef, undef);
1952 my ($rev, $commit) = $self->rev_map_max(1);
1953 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1954 return ($rev, $commit);
1957 sub get_fetch_range {
1958 my ($self, $min, $max) = @_;
1959 $max ||= $self->ra->get_latest_revnum;
1960 $min ||= $self->rev_map_max;
1961 (++$min, $max);
1964 sub tmp_config {
1965 my (@args) = @_;
1966 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1967 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1968 if (! -f $config && -f $old_def_config) {
1969 rename $old_def_config, $config or
1970 die "Failed rename $old_def_config => $config: $!\n";
1972 my $old_config = $ENV{GIT_CONFIG};
1973 $ENV{GIT_CONFIG} = $config;
1974 $@ = undef;
1975 my @ret = eval {
1976 unless (-f $config) {
1977 mkfile($config);
1978 open my $fh, '>', $config or
1979 die "Can't open $config: $!\n";
1980 print $fh "; This file is used internally by ",
1981 "git-svn\n" or die
1982 "Couldn't write to $config: $!\n";
1983 print $fh "; You should not have to edit it\n" or
1984 die "Couldn't write to $config: $!\n";
1985 close $fh or die "Couldn't close $config: $!\n";
1987 command('config', @args);
1989 my $err = $@;
1990 if (defined $old_config) {
1991 $ENV{GIT_CONFIG} = $old_config;
1992 } else {
1993 delete $ENV{GIT_CONFIG};
1995 die $err if $err;
1996 wantarray ? @ret : $ret[0];
1999 sub tmp_index_do {
2000 my ($self, $sub) = @_;
2001 my $old_index = $ENV{GIT_INDEX_FILE};
2002 $ENV{GIT_INDEX_FILE} = $self->{index};
2003 $@ = undef;
2004 my @ret = eval {
2005 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2006 mkpath([$dir]) unless -d $dir;
2007 &$sub;
2009 my $err = $@;
2010 if (defined $old_index) {
2011 $ENV{GIT_INDEX_FILE} = $old_index;
2012 } else {
2013 delete $ENV{GIT_INDEX_FILE};
2015 die $err if $err;
2016 wantarray ? @ret : $ret[0];
2019 sub assert_index_clean {
2020 my ($self, $treeish) = @_;
2022 $self->tmp_index_do(sub {
2023 command_noisy('read-tree', $treeish) unless -e $self->{index};
2024 my $x = command_oneline('write-tree');
2025 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2026 /^tree ($::sha1)/mo);
2027 return if $y eq $x;
2029 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2030 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2031 command_noisy('read-tree', $treeish);
2032 $x = command_oneline('write-tree');
2033 if ($y ne $x) {
2034 ::fatal "trees ($treeish) $y != $x\n",
2035 "Something is seriously wrong...";
2040 sub get_commit_parents {
2041 my ($self, $log_entry) = @_;
2042 my (%seen, @ret, @tmp);
2043 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2044 if (my $ip = $self->{inject_parents}) {
2045 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2046 push @tmp, $commit;
2049 if (my $cur = ::verify_ref($self->refname.'^0')) {
2050 push @tmp, $cur;
2052 if (my $ipd = $self->{inject_parents_dcommit}) {
2053 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2054 push @tmp, @$commit;
2057 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2058 while (my $p = shift @tmp) {
2059 next if $seen{$p};
2060 $seen{$p} = 1;
2061 push @ret, $p;
2062 # MAXPARENT is defined to 16 in commit-tree.c:
2063 last if @ret >= 16;
2065 if (@tmp) {
2066 die "r$log_entry->{revision}: No room for parents:\n\t",
2067 join("\n\t", @tmp), "\n";
2069 @ret;
2072 sub rewrite_root {
2073 my ($self) = @_;
2074 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2075 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2076 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2077 if ($rwr) {
2078 $rwr =~ s#/+$##;
2079 if ($rwr !~ m#^[a-z\+]+://#) {
2080 die "$rwr is not a valid URL (key: $k)\n";
2083 $self->{-rewrite_root} = $rwr;
2086 sub metadata_url {
2087 my ($self) = @_;
2088 ($self->rewrite_root || $self->{url}) .
2089 (length $self->{path} ? '/' . $self->{path} : '');
2092 sub full_url {
2093 my ($self) = @_;
2094 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2098 sub set_commit_header_env {
2099 my ($log_entry) = @_;
2100 my %env;
2101 foreach my $ned (qw/NAME EMAIL DATE/) {
2102 foreach my $ac (qw/AUTHOR COMMITTER/) {
2103 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2107 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2108 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2109 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2111 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2112 ? $log_entry->{commit_name}
2113 : $log_entry->{name};
2114 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2115 ? $log_entry->{commit_email}
2116 : $log_entry->{email};
2117 \%env;
2120 sub restore_commit_header_env {
2121 my ($env) = @_;
2122 foreach my $ned (qw/NAME EMAIL DATE/) {
2123 foreach my $ac (qw/AUTHOR COMMITTER/) {
2124 my $k = "GIT_${ac}_${ned}";
2125 if (defined $env->{$k}) {
2126 $ENV{$k} = $env->{$k};
2127 } else {
2128 delete $ENV{$k};
2134 sub gc {
2135 command_noisy('gc', '--auto');
2138 sub do_git_commit {
2139 my ($self, $log_entry) = @_;
2140 my $lr = $self->last_rev;
2141 if (defined $lr && $lr >= $log_entry->{revision}) {
2142 die "Last fetched revision of ", $self->refname,
2143 " was r$lr, but we are about to fetch: ",
2144 "r$log_entry->{revision}!\n";
2146 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2147 croak "$log_entry->{revision} = $c already exists! ",
2148 "Why are we refetching it?\n";
2150 my $old_env = set_commit_header_env($log_entry);
2151 my $tree = $log_entry->{tree};
2152 if (!defined $tree) {
2153 $tree = $self->tmp_index_do(sub {
2154 command_oneline('write-tree') });
2156 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2158 my @exec = ('git-commit-tree', $tree);
2159 foreach ($self->get_commit_parents($log_entry)) {
2160 push @exec, '-p', $_;
2162 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2163 or croak $!;
2164 print $msg_fh $log_entry->{log} or croak $!;
2165 restore_commit_header_env($old_env);
2166 unless ($self->no_metadata) {
2167 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2168 or croak $!;
2170 $msg_fh->flush == 0 or croak $!;
2171 close $msg_fh or croak $!;
2172 chomp(my $commit = do { local $/; <$out_fh> });
2173 close $out_fh or croak $!;
2174 waitpid $pid, 0;
2175 croak $? if $?;
2176 if ($commit !~ /^$::sha1$/o) {
2177 die "Failed to commit, invalid sha1: $commit\n";
2180 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2182 $self->{last_rev} = $log_entry->{revision};
2183 $self->{last_commit} = $commit;
2184 print "r$log_entry->{revision}";
2185 if (defined $log_entry->{svm_revision}) {
2186 print " (\@$log_entry->{svm_revision})";
2187 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2188 0, $self->svm_uuid);
2190 print " = $commit ($self->{ref_id})\n";
2191 if (--$_gc_nr == 0) {
2192 $_gc_nr = $_gc_period;
2193 gc();
2195 return $commit;
2198 sub match_paths {
2199 my ($self, $paths, $r) = @_;
2200 return 1 if $self->{path} eq '';
2201 if (my $path = $paths->{"/$self->{path}"}) {
2202 return ($path->{action} eq 'D') ? 0 : 1;
2204 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2205 if (grep /$self->{path_regex}/, keys %$paths) {
2206 return 1;
2208 my $c = '';
2209 foreach (split m#/#, $self->{path}) {
2210 $c .= "/$_";
2211 next unless ($paths->{$c} &&
2212 ($paths->{$c}->{action} =~ /^[AR]$/));
2213 if ($self->ra->check_path($self->{path}, $r) ==
2214 $SVN::Node::dir) {
2215 return 1;
2218 return 0;
2221 sub find_parent_branch {
2222 my ($self, $paths, $rev) = @_;
2223 return undef unless $self->follow_parent;
2224 unless (defined $paths) {
2225 my $err_handler = $SVN::Error::handler;
2226 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2227 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2228 $paths =
2229 Git::SVN::Ra::dup_changed_paths($_[0]) });
2230 $SVN::Error::handler = $err_handler;
2232 return undef unless defined $paths;
2234 # look for a parent from another branch:
2235 my @b_path_components = split m#/#, $self->rel_path;
2236 my @a_path_components;
2237 my $i;
2238 while (@b_path_components) {
2239 $i = $paths->{'/'.join('/', @b_path_components)};
2240 last if $i && defined $i->{copyfrom_path};
2241 unshift(@a_path_components, pop(@b_path_components));
2243 return undef unless defined $i && defined $i->{copyfrom_path};
2244 my $branch_from = $i->{copyfrom_path};
2245 if (@a_path_components) {
2246 print STDERR "branch_from: $branch_from => ";
2247 $branch_from .= '/'.join('/', @a_path_components);
2248 print STDERR $branch_from, "\n";
2250 my $r = $i->{copyfrom_rev};
2251 my $repos_root = $self->ra->{repos_root};
2252 my $url = $self->ra->{url};
2253 my $new_url = $repos_root . $branch_from;
2254 print STDERR "Found possible branch point: ",
2255 "$new_url => ", $self->full_url, ", $r\n";
2256 $branch_from =~ s#^/##;
2257 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2258 unless ($gs) {
2259 my $ref_id = $self->{ref_id};
2260 $ref_id =~ s/\@\d+$//;
2261 $ref_id .= "\@$r";
2262 # just grow a tail if we're not unique enough :x
2263 $ref_id .= '-' while find_ref($ref_id);
2264 print STDERR "Initializing parent: $ref_id\n";
2265 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2266 if ($u =~ s#^\Q$url\E(/|$)##) {
2267 $p = $u;
2268 $u = $url;
2269 $repo_id = $self->{repo_id};
2271 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2273 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2274 if (!defined $r0 || !defined $parent) {
2275 my ($base, $head) = parse_revision_argument(0, $r);
2276 if ($base <= $r) {
2277 $gs->fetch($base, $r);
2279 ($r0, $parent) = $gs->last_rev_commit;
2281 if (defined $r0 && defined $parent) {
2282 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2283 my $ed;
2284 if ($self->ra->can_do_switch) {
2285 $self->assert_index_clean($parent);
2286 print STDERR "Following parent with do_switch\n";
2287 # do_switch works with svn/trunk >= r22312, but that
2288 # is not included with SVN 1.4.3 (the latest version
2289 # at the moment), so we can't rely on it
2290 $self->{last_commit} = $parent;
2291 $ed = SVN::Git::Fetcher->new($self);
2292 $gs->ra->gs_do_switch($r0, $rev, $gs,
2293 $self->full_url, $ed)
2294 or die "SVN connection failed somewhere...\n";
2295 } elsif ($self->ra->trees_match($new_url, $r0,
2296 $self->full_url, $rev)) {
2297 print STDERR "Trees match:\n",
2298 " $new_url\@$r0\n",
2299 " ${\$self->full_url}\@$rev\n",
2300 "Following parent with no changes\n";
2301 $self->tmp_index_do(sub {
2302 command_noisy('read-tree', $parent);
2304 $self->{last_commit} = $parent;
2305 } else {
2306 print STDERR "Following parent with do_update\n";
2307 $ed = SVN::Git::Fetcher->new($self);
2308 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2309 or die "SVN connection failed somewhere...\n";
2311 print STDERR "Successfully followed parent\n";
2312 return $self->make_log_entry($rev, [$parent], $ed);
2314 return undef;
2317 sub do_fetch {
2318 my ($self, $paths, $rev) = @_;
2319 my $ed;
2320 my ($last_rev, @parents);
2321 if (my $lc = $self->last_commit) {
2322 # we can have a branch that was deleted, then re-added
2323 # under the same name but copied from another path, in
2324 # which case we'll have multiple parents (we don't
2325 # want to break the original ref, nor lose copypath info):
2326 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2327 push @{$log_entry->{parents}}, $lc;
2328 return $log_entry;
2330 $ed = SVN::Git::Fetcher->new($self);
2331 $last_rev = $self->{last_rev};
2332 $ed->{c} = $lc;
2333 @parents = ($lc);
2334 } else {
2335 $last_rev = $rev;
2336 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2337 return $log_entry;
2339 $ed = SVN::Git::Fetcher->new($self);
2341 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2342 die "SVN connection failed somewhere...\n";
2344 $self->make_log_entry($rev, \@parents, $ed);
2347 sub get_untracked {
2348 my ($self, $ed) = @_;
2349 my @out;
2350 my $h = $ed->{empty};
2351 foreach (sort keys %$h) {
2352 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2353 push @out, " $act: " . uri_encode($_);
2354 warn "W: $act: $_\n";
2356 foreach my $t (qw/dir_prop file_prop/) {
2357 $h = $ed->{$t} or next;
2358 foreach my $path (sort keys %$h) {
2359 my $ppath = $path eq '' ? '.' : $path;
2360 foreach my $prop (sort keys %{$h->{$path}}) {
2361 next if $SKIP_PROP{$prop};
2362 my $v = $h->{$path}->{$prop};
2363 my $t_ppath_prop = "$t: " .
2364 uri_encode($ppath) . ' ' .
2365 uri_encode($prop);
2366 if (defined $v) {
2367 push @out, " +$t_ppath_prop " .
2368 uri_encode($v);
2369 } else {
2370 push @out, " -$t_ppath_prop";
2375 foreach my $t (qw/absent_file absent_directory/) {
2376 $h = $ed->{$t} or next;
2377 foreach my $parent (sort keys %$h) {
2378 foreach my $path (sort @{$h->{$parent}}) {
2379 push @out, " $t: " .
2380 uri_encode("$parent/$path");
2381 warn "W: $t: $parent/$path ",
2382 "Insufficient permissions?\n";
2386 \@out;
2389 sub parse_svn_date {
2390 my $date = shift || return '+0000 1970-01-01 00:00:00';
2391 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2392 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2393 croak "Unable to parse date: $date\n";
2394 "+0000 $Y-$m-$d $H:$M:$S";
2397 sub check_author {
2398 my ($author) = @_;
2399 if (!defined $author || length $author == 0) {
2400 $author = '(no author)';
2401 } elsif (defined $::_authors && ! defined $::users{$author}) {
2402 die "Author: $author not defined in $::_authors file\n";
2404 $author;
2407 sub make_log_entry {
2408 my ($self, $rev, $parents, $ed) = @_;
2409 my $untracked = $self->get_untracked($ed);
2411 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2412 print $un "r$rev\n" or croak $!;
2413 print $un $_, "\n" foreach @$untracked;
2414 my %log_entry = ( parents => $parents || [], revision => $rev,
2415 log => '');
2417 my $headrev;
2418 my $logged = delete $self->{logged_rev_props};
2419 if (!$logged || $self->{-want_revprops}) {
2420 my $rp = $self->ra->rev_proplist($rev);
2421 foreach (sort keys %$rp) {
2422 my $v = $rp->{$_};
2423 if (/^svn:(author|date|log)$/) {
2424 $log_entry{$1} = $v;
2425 } elsif ($_ eq 'svm:headrev') {
2426 $headrev = $v;
2427 } else {
2428 print $un " rev_prop: ", uri_encode($_), ' ',
2429 uri_encode($v), "\n";
2432 } else {
2433 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2435 close $un or croak $!;
2437 $log_entry{date} = parse_svn_date($log_entry{date});
2438 $log_entry{log} .= "\n";
2439 my $author = $log_entry{author} = check_author($log_entry{author});
2440 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2441 : ($author, undef);
2443 my ($commit_name, $commit_email) = ($name, $email);
2444 if ($_use_log_author) {
2445 my $name_field;
2446 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2447 $name_field = $1;
2448 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2449 $name_field = $1;
2451 if (!defined $name_field) {
2452 if (!defined $email) {
2453 $email = $name;
2455 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2456 ($name, $email) = ($1, $2);
2457 } elsif ($name_field =~ /(.*)@/) {
2458 ($name, $email) = ($1, $name_field);
2459 } else {
2460 ($name, $email) = ($name_field, $name_field);
2463 if (defined $headrev && $self->use_svm_props) {
2464 if ($self->rewrite_root) {
2465 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2466 "options set!\n";
2468 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2469 # we don't want "SVM: initializing mirror for junk" ...
2470 return undef if $r == 0;
2471 my $svm = $self->svm;
2472 if ($uuid ne $svm->{uuid}) {
2473 die "UUID mismatch on SVM path:\n",
2474 "expected: $svm->{uuid}\n",
2475 " got: $uuid\n";
2477 my $full_url = $self->full_url;
2478 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2479 die "Failed to replace '$svm->{replace}' with ",
2480 "'$svm->{source}' in $full_url\n";
2481 # throw away username for storing in records
2482 remove_username($full_url);
2483 $log_entry{metadata} = "$full_url\@$r $uuid";
2484 $log_entry{svm_revision} = $r;
2485 $email ||= "$author\@$uuid";
2486 $commit_email ||= "$author\@$uuid";
2487 } elsif ($self->use_svnsync_props) {
2488 my $full_url = $self->svnsync->{url};
2489 $full_url .= "/$self->{path}" if length $self->{path};
2490 remove_username($full_url);
2491 my $uuid = $self->svnsync->{uuid};
2492 $log_entry{metadata} = "$full_url\@$rev $uuid";
2493 $email ||= "$author\@$uuid";
2494 $commit_email ||= "$author\@$uuid";
2495 } else {
2496 my $url = $self->metadata_url;
2497 remove_username($url);
2498 $log_entry{metadata} = "$url\@$rev " .
2499 $self->ra->get_uuid;
2500 $email ||= "$author\@" . $self->ra->get_uuid;
2501 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2503 $log_entry{name} = $name;
2504 $log_entry{email} = $email;
2505 $log_entry{commit_name} = $commit_name;
2506 $log_entry{commit_email} = $commit_email;
2507 \%log_entry;
2510 sub fetch {
2511 my ($self, $min_rev, $max_rev, @parents) = @_;
2512 my ($last_rev, $last_commit) = $self->last_rev_commit;
2513 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2514 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2517 sub set_tree_cb {
2518 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2519 $self->{inject_parents} = { $rev => $tree };
2520 $self->fetch(undef, undef);
2523 sub set_tree {
2524 my ($self, $tree) = (shift, shift);
2525 my $log_entry = ::get_commit_entry($tree);
2526 unless ($self->{last_rev}) {
2527 fatal("Must have an existing revision to commit");
2529 my %ed_opts = ( r => $self->{last_rev},
2530 log => $log_entry->{log},
2531 ra => $self->ra,
2532 tree_a => $self->{last_commit},
2533 tree_b => $tree,
2534 editor_cb => sub {
2535 $self->set_tree_cb($log_entry, $tree, @_) },
2536 svn_path => $self->{path} );
2537 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2538 print "No changes\nr$self->{last_rev} = $tree\n";
2542 sub rebuild_from_rev_db {
2543 my ($self, $path) = @_;
2544 my $r = -1;
2545 open my $fh, '<', $path or croak "open: $!";
2546 binmode $fh or croak "binmode: $!";
2547 while (<$fh>) {
2548 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2549 chomp($_);
2550 ++$r;
2551 next if $_ eq ('0' x 40);
2552 $self->rev_map_set($r, $_);
2553 print "r$r = $_\n";
2555 close $fh or croak "close: $!";
2556 unlink $path or croak "unlink: $!";
2559 sub rebuild {
2560 my ($self) = @_;
2561 my $map_path = $self->map_path;
2562 return if (-e $map_path && ! -z $map_path);
2563 return unless ::verify_ref($self->refname.'^0');
2564 if ($self->use_svm_props || $self->no_metadata) {
2565 my $rev_db = $self->rev_db_path;
2566 $self->rebuild_from_rev_db($rev_db);
2567 if ($self->use_svm_props) {
2568 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2569 $self->rebuild_from_rev_db($svm_rev_db);
2571 $self->unlink_rev_db_symlink;
2572 return;
2574 print "Rebuilding $map_path ...\n";
2575 my ($log, $ctx) =
2576 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2577 $self->refname, '--');
2578 my $full_url = $self->full_url;
2579 remove_username($full_url);
2580 my $svn_uuid = $self->ra_uuid;
2581 my $c;
2582 while (<$log>) {
2583 if ( m{^commit ($::sha1)$} ) {
2584 $c = $1;
2585 next;
2587 next unless s{^\s*(git-svn-id:)}{$1};
2588 my ($url, $rev, $uuid) = ::extract_metadata($_);
2589 remove_username($url);
2591 # ignore merges (from set-tree)
2592 next if (!defined $rev || !$uuid);
2594 # if we merged or otherwise started elsewhere, this is
2595 # how we break out of it
2596 if (($uuid ne $svn_uuid) ||
2597 ($full_url && $url && ($url ne $full_url))) {
2598 next;
2601 $self->rev_map_set($rev, $c);
2602 print "r$rev = $c\n";
2604 command_close_pipe($log, $ctx);
2605 print "Done rebuilding $map_path\n";
2606 my $rev_db_path = $self->rev_db_path;
2607 if (-f $self->rev_db_path) {
2608 unlink $self->rev_db_path or croak "unlink: $!";
2610 $self->unlink_rev_db_symlink;
2613 # rev_map:
2614 # Tie::File seems to be prone to offset errors if revisions get sparse,
2615 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2616 # one of my favorite modules is out :< Next up would be one of the DBM
2617 # modules, but I'm not sure which is most portable...
2619 # This is the replacement for the rev_db format, which was too big
2620 # and inefficient for large repositories with a lot of sparse history
2621 # (mainly tags)
2623 # The format is this:
2624 # - 24 bytes for every record,
2625 # * 4 bytes for the integer representing an SVN revision number
2626 # * 20 bytes representing the sha1 of a git commit
2627 # - No empty padding records like the old format
2628 # (except the last record, which can be overwritten)
2629 # - new records are written append-only since SVN revision numbers
2630 # increase monotonically
2631 # - lookups on SVN revision number are done via a binary search
2632 # - Piping the file to xxd -c24 is a good way of dumping it for
2633 # viewing or editing (piped back through xxd -r), should the need
2634 # ever arise.
2635 # - The last record can be padding revision with an all-zero sha1
2636 # This is used to optimize fetch performance when using multiple
2637 # "fetch" directives in .git/config
2639 # These files are disposable unless noMetadata or useSvmProps is set
2641 sub _rev_map_set {
2642 my ($fh, $rev, $commit) = @_;
2644 binmode $fh or croak "binmode: $!";
2645 my $size = (stat($fh))[7];
2646 ($size % 24) == 0 or croak "inconsistent size: $size";
2648 my $wr_offset = 0;
2649 if ($size > 0) {
2650 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2651 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2652 $read == 24 or croak "read only $read bytes (!= 24)";
2653 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2654 if ($last_commit eq ('0' x40)) {
2655 if ($size >= 48) {
2656 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2657 $read = sysread($fh, $buf, 24) or
2658 croak "read: $!";
2659 $read == 24 or
2660 croak "read only $read bytes (!= 24)";
2661 ($last_rev, $last_commit) =
2662 unpack(rev_map_fmt, $buf);
2663 if ($last_commit eq ('0' x40)) {
2664 croak "inconsistent .rev_map\n";
2667 if ($last_rev >= $rev) {
2668 croak "last_rev is higher!: $last_rev >= $rev";
2670 $wr_offset = -24;
2673 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2674 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2675 croak "write: $!";
2678 sub mkfile {
2679 my ($path) = @_;
2680 unless (-e $path) {
2681 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2682 mkpath([$dir]) unless -d $dir;
2683 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2684 close $fh or die "Couldn't close (create) $path: $!\n";
2688 sub rev_map_set {
2689 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2690 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2691 my $db = $self->map_path($uuid);
2692 my $db_lock = "$db.lock";
2693 my $sig;
2694 if ($update_ref) {
2695 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2696 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2698 mkfile($db);
2700 $LOCKFILES{$db_lock} = 1;
2701 my $sync;
2702 # both of these options make our .rev_db file very, very important
2703 # and we can't afford to lose it because rebuild() won't work
2704 if ($self->use_svm_props || $self->no_metadata) {
2705 $sync = 1;
2706 copy($db, $db_lock) or die "rev_map_set(@_): ",
2707 "Failed to copy: ",
2708 "$db => $db_lock ($!)\n";
2709 } else {
2710 rename $db, $db_lock or die "rev_map_set(@_): ",
2711 "Failed to rename: ",
2712 "$db => $db_lock ($!)\n";
2715 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2716 or croak "Couldn't open $db_lock: $!\n";
2717 _rev_map_set($fh, $rev, $commit);
2718 if ($sync) {
2719 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2720 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2722 close $fh or croak $!;
2723 if ($update_ref) {
2724 $_head = $self;
2725 command_noisy('update-ref', '-m', "r$rev",
2726 $self->refname, $commit);
2728 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2729 "$db_lock => $db ($!)\n";
2730 delete $LOCKFILES{$db_lock};
2731 if ($update_ref) {
2732 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2733 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2734 kill $sig, $$ if defined $sig;
2738 # If want_commit, this will return an array of (rev, commit) where
2739 # commit _must_ be a valid commit in the archive.
2740 # Otherwise, it'll return the max revision (whether or not the
2741 # commit is valid or just a 0x40 placeholder).
2742 sub rev_map_max {
2743 my ($self, $want_commit) = @_;
2744 $self->rebuild;
2745 my $map_path = $self->map_path;
2746 stat $map_path or return $want_commit ? (0, undef) : 0;
2747 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2748 binmode $fh or croak "binmode: $!";
2749 my $size = (stat($fh))[7];
2750 ($size % 24) == 0 or croak "inconsistent size: $size";
2752 if ($size == 0) {
2753 close $fh or croak "close: $!";
2754 return $want_commit ? (0, undef) : 0;
2757 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2758 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2759 my ($r, $c) = unpack(rev_map_fmt, $buf);
2760 if ($want_commit && $c eq ('0' x40)) {
2761 if ($size < 48) {
2762 return $want_commit ? (0, undef) : 0;
2764 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2765 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2766 ($r, $c) = unpack(rev_map_fmt, $buf);
2767 if ($c eq ('0'x40)) {
2768 croak "Penultimate record is all-zeroes in $map_path";
2771 close $fh or croak "close: $!";
2772 $want_commit ? ($r, $c) : $r;
2775 sub rev_map_get {
2776 my ($self, $rev, $uuid) = @_;
2777 my $map_path = $self->map_path($uuid);
2778 return undef unless -e $map_path;
2780 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2781 binmode $fh or croak "binmode: $!";
2782 my $size = (stat($fh))[7];
2783 ($size % 24) == 0 or croak "inconsistent size: $size";
2785 if ($size == 0) {
2786 close $fh or croak "close: $fh";
2787 return undef;
2790 my ($l, $u) = (0, $size - 24);
2791 my ($r, $c, $buf);
2793 while ($l <= $u) {
2794 my $i = int(($l/24 + $u/24) / 2) * 24;
2795 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2796 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2797 my ($r, $c) = unpack('NH40', $buf);
2799 if ($r < $rev) {
2800 $l = $i + 24;
2801 } elsif ($r > $rev) {
2802 $u = $i - 24;
2803 } else { # $r == $rev
2804 close($fh) or croak "close: $!";
2805 return $c eq ('0' x 40) ? undef : $c;
2808 close($fh) or croak "close: $!";
2809 undef;
2812 # Finds the first svn revision that exists on (if $eq_ok is true) or
2813 # before $rev for the current branch. It will not search any lower
2814 # than $min_rev. Returns the git commit hash and svn revision number
2815 # if found, else (undef, undef).
2816 sub find_rev_before {
2817 my ($self, $rev, $eq_ok, $min_rev) = @_;
2818 --$rev unless $eq_ok;
2819 $min_rev ||= 1;
2820 while ($rev >= $min_rev) {
2821 if (my $c = $self->rev_map_get($rev)) {
2822 return ($rev, $c);
2824 --$rev;
2826 return (undef, undef);
2829 # Finds the first svn revision that exists on (if $eq_ok is true) or
2830 # after $rev for the current branch. It will not search any higher
2831 # than $max_rev. Returns the git commit hash and svn revision number
2832 # if found, else (undef, undef).
2833 sub find_rev_after {
2834 my ($self, $rev, $eq_ok, $max_rev) = @_;
2835 ++$rev unless $eq_ok;
2836 $max_rev ||= $self->rev_map_max;
2837 while ($rev <= $max_rev) {
2838 if (my $c = $self->rev_map_get($rev)) {
2839 return ($rev, $c);
2841 ++$rev;
2843 return (undef, undef);
2846 sub _new {
2847 my ($class, $repo_id, $ref_id, $path) = @_;
2848 unless (defined $repo_id && length $repo_id) {
2849 $repo_id = $Git::SVN::default_repo_id;
2851 unless (defined $ref_id && length $ref_id) {
2852 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2854 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2855 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2856 $_[3] = $path = '' unless (defined $path);
2857 mkpath(["$ENV{GIT_DIR}/svn"]);
2858 bless {
2859 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2860 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2861 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2864 # for read-only access of old .rev_db formats
2865 sub unlink_rev_db_symlink {
2866 my ($self) = @_;
2867 my $link = $self->rev_db_path;
2868 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2869 if (-l $link) {
2870 unlink $link or croak "unlink: $link failed!";
2874 sub rev_db_path {
2875 my ($self, $uuid) = @_;
2876 my $db_path = $self->map_path($uuid);
2877 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2878 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2879 $db_path;
2882 # the new replacement for .rev_db
2883 sub map_path {
2884 my ($self, $uuid) = @_;
2885 $uuid ||= $self->ra_uuid;
2886 "$self->{map_root}.$uuid";
2889 sub uri_encode {
2890 my ($f) = @_;
2891 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2895 sub remove_username {
2896 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2899 package Git::SVN::Prompt;
2900 use strict;
2901 use warnings;
2902 require SVN::Core;
2903 use vars qw/$_no_auth_cache $_username/;
2905 sub simple {
2906 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2907 $may_save = undef if $_no_auth_cache;
2908 $default_username = $_username if defined $_username;
2909 if (defined $default_username && length $default_username) {
2910 if (defined $realm && length $realm) {
2911 print STDERR "Authentication realm: $realm\n";
2912 STDERR->flush;
2914 $cred->username($default_username);
2915 } else {
2916 username($cred, $realm, $may_save, $pool);
2918 $cred->password(_read_password("Password for '" .
2919 $cred->username . "': ", $realm));
2920 $cred->may_save($may_save);
2921 $SVN::_Core::SVN_NO_ERROR;
2924 sub ssl_server_trust {
2925 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2926 $may_save = undef if $_no_auth_cache;
2927 print STDERR "Error validating server certificate for '$realm':\n";
2929 no warnings 'once';
2930 # All variables SVN::Auth::SSL::* are used only once,
2931 # so we're shutting up Perl warnings about this.
2932 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2933 print STDERR " - The certificate is not issued ",
2934 "by a trusted authority. Use the\n",
2935 " fingerprint to validate ",
2936 "the certificate manually!\n";
2938 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2939 print STDERR " - The certificate hostname ",
2940 "does not match.\n";
2942 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2943 print STDERR " - The certificate is not yet valid.\n";
2945 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2946 print STDERR " - The certificate has expired.\n";
2948 if ($failures & $SVN::Auth::SSL::OTHER) {
2949 print STDERR " - The certificate has ",
2950 "an unknown error.\n";
2952 } # no warnings 'once'
2953 printf STDERR
2954 "Certificate information:\n".
2955 " - Hostname: %s\n".
2956 " - Valid: from %s until %s\n".
2957 " - Issuer: %s\n".
2958 " - Fingerprint: %s\n",
2959 map $cert_info->$_, qw(hostname valid_from valid_until
2960 issuer_dname fingerprint);
2961 my $choice;
2962 prompt:
2963 print STDERR $may_save ?
2964 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2965 "(R)eject or accept (t)emporarily? ";
2966 STDERR->flush;
2967 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2968 if ($choice =~ /^t$/i) {
2969 $cred->may_save(undef);
2970 } elsif ($choice =~ /^r$/i) {
2971 return -1;
2972 } elsif ($may_save && $choice =~ /^p$/i) {
2973 $cred->may_save($may_save);
2974 } else {
2975 goto prompt;
2977 $cred->accepted_failures($failures);
2978 $SVN::_Core::SVN_NO_ERROR;
2981 sub ssl_client_cert {
2982 my ($cred, $realm, $may_save, $pool) = @_;
2983 $may_save = undef if $_no_auth_cache;
2984 print STDERR "Client certificate filename: ";
2985 STDERR->flush;
2986 chomp(my $filename = <STDIN>);
2987 $cred->cert_file($filename);
2988 $cred->may_save($may_save);
2989 $SVN::_Core::SVN_NO_ERROR;
2992 sub ssl_client_cert_pw {
2993 my ($cred, $realm, $may_save, $pool) = @_;
2994 $may_save = undef if $_no_auth_cache;
2995 $cred->password(_read_password("Password: ", $realm));
2996 $cred->may_save($may_save);
2997 $SVN::_Core::SVN_NO_ERROR;
3000 sub username {
3001 my ($cred, $realm, $may_save, $pool) = @_;
3002 $may_save = undef if $_no_auth_cache;
3003 if (defined $realm && length $realm) {
3004 print STDERR "Authentication realm: $realm\n";
3006 my $username;
3007 if (defined $_username) {
3008 $username = $_username;
3009 } else {
3010 print STDERR "Username: ";
3011 STDERR->flush;
3012 chomp($username = <STDIN>);
3014 $cred->username($username);
3015 $cred->may_save($may_save);
3016 $SVN::_Core::SVN_NO_ERROR;
3019 sub _read_password {
3020 my ($prompt, $realm) = @_;
3021 print STDERR $prompt;
3022 STDERR->flush;
3023 require Term::ReadKey;
3024 Term::ReadKey::ReadMode('noecho');
3025 my $password = '';
3026 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3027 last if $key =~ /[\012\015]/; # \n\r
3028 $password .= $key;
3030 Term::ReadKey::ReadMode('restore');
3031 print STDERR "\n";
3032 STDERR->flush;
3033 $password;
3036 package SVN::Git::Fetcher;
3037 use vars qw/@ISA/;
3038 use strict;
3039 use warnings;
3040 use Carp qw/croak/;
3041 use File::Temp qw/tempfile/;
3042 use IO::File qw//;
3044 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3045 sub new {
3046 my ($class, $git_svn) = @_;
3047 my $self = SVN::Delta::Editor->new;
3048 bless $self, $class;
3049 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3050 $self->{empty} = {};
3051 $self->{dir_prop} = {};
3052 $self->{file_prop} = {};
3053 $self->{absent_dir} = {};
3054 $self->{absent_file} = {};
3055 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3056 $self;
3059 sub set_path_strip {
3060 my ($self, $path) = @_;
3061 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3064 sub open_root {
3065 { path => '' };
3068 sub open_directory {
3069 my ($self, $path, $pb, $rev) = @_;
3070 { path => $path };
3073 sub git_path {
3074 my ($self, $path) = @_;
3075 if ($self->{path_strip}) {
3076 $path =~ s!$self->{path_strip}!! or
3077 die "Failed to strip path '$path' ($self->{path_strip})\n";
3079 $path;
3082 sub delete_entry {
3083 my ($self, $path, $rev, $pb) = @_;
3085 my $gpath = $self->git_path($path);
3086 return undef if ($gpath eq '');
3088 # remove entire directories.
3089 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3090 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3091 -r --name-only -z/,
3092 $self->{c}, '--', $gpath);
3093 local $/ = "\0";
3094 while (<$ls>) {
3095 chomp;
3096 $self->{gii}->remove($_);
3097 print "\tD\t$_\n" unless $::_q;
3099 print "\tD\t$gpath/\n" unless $::_q;
3100 command_close_pipe($ls, $ctx);
3101 $self->{empty}->{$path} = 0
3102 } else {
3103 $self->{gii}->remove($gpath);
3104 print "\tD\t$gpath\n" unless $::_q;
3106 undef;
3109 sub open_file {
3110 my ($self, $path, $pb, $rev) = @_;
3111 my $gpath = $self->git_path($path);
3112 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3113 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3114 unless (defined $mode && defined $blob) {
3115 die "$path was not found in commit $self->{c} (r$rev)\n";
3117 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3118 pool => SVN::Pool->new, action => 'M' };
3121 sub add_file {
3122 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3123 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3124 delete $self->{empty}->{$dir};
3125 { path => $path, mode_a => 100644, mode_b => 100644,
3126 pool => SVN::Pool->new, action => 'A' };
3129 sub add_directory {
3130 my ($self, $path, $cp_path, $cp_rev) = @_;
3131 my $gpath = $self->git_path($path);
3132 if ($gpath eq '') {
3133 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3134 -r --name-only -z/,
3135 $self->{c});
3136 local $/ = "\0";
3137 while (<$ls>) {
3138 chomp;
3139 $self->{gii}->remove($_);
3140 print "\tD\t$_\n" unless $::_q;
3142 command_close_pipe($ls, $ctx);
3143 $self->{empty}->{$path} = 0;
3145 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3146 delete $self->{empty}->{$dir};
3147 $self->{empty}->{$path} = 1;
3148 { path => $path };
3151 sub change_dir_prop {
3152 my ($self, $db, $prop, $value) = @_;
3153 $self->{dir_prop}->{$db->{path}} ||= {};
3154 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3155 undef;
3158 sub absent_directory {
3159 my ($self, $path, $pb) = @_;
3160 $self->{absent_dir}->{$pb->{path}} ||= [];
3161 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3162 undef;
3165 sub absent_file {
3166 my ($self, $path, $pb) = @_;
3167 $self->{absent_file}->{$pb->{path}} ||= [];
3168 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3169 undef;
3172 sub change_file_prop {
3173 my ($self, $fb, $prop, $value) = @_;
3174 if ($prop eq 'svn:executable') {
3175 if ($fb->{mode_b} != 120000) {
3176 $fb->{mode_b} = defined $value ? 100755 : 100644;
3178 } elsif ($prop eq 'svn:special') {
3179 $fb->{mode_b} = defined $value ? 120000 : 100644;
3180 } else {
3181 $self->{file_prop}->{$fb->{path}} ||= {};
3182 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3184 undef;
3187 sub apply_textdelta {
3188 my ($self, $fb, $exp) = @_;
3189 my $fh = IO::File->new_tmpfile;
3190 $fh->autoflush(1);
3191 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3192 # (but $base does not,) so dup() it for reading in close_file
3193 open my $dup, '<&', $fh or croak $!;
3194 my $base = IO::File->new_tmpfile;
3195 $base->autoflush(1);
3196 if ($fb->{blob}) {
3197 print $base 'link ' if ($fb->{mode_a} == 120000);
3198 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3199 die "Failed to read object $fb->{blob}" if ($size < 0);
3201 if (defined $exp) {
3202 seek $base, 0, 0 or croak $!;
3203 my $got = ::md5sum($base);
3204 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3205 "expected: $exp\n",
3206 " got: $got\n" if ($got ne $exp);
3209 seek $base, 0, 0 or croak $!;
3210 $fb->{fh} = $dup;
3211 $fb->{base} = $base;
3212 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3215 sub close_file {
3216 my ($self, $fb, $exp) = @_;
3217 my $hash;
3218 my $path = $self->git_path($fb->{path});
3219 if (my $fh = $fb->{fh}) {
3220 if (defined $exp) {
3221 seek($fh, 0, 0) or croak $!;
3222 my $got = ::md5sum($fh);
3223 if ($got ne $exp) {
3224 die "Checksum mismatch: $path\n",
3225 "expected: $exp\n got: $got\n";
3228 sysseek($fh, 0, 0) or croak $!;
3229 if ($fb->{mode_b} == 120000) {
3230 eval {
3231 sysread($fh, my $buf, 5) == 5 or croak $!;
3232 $buf eq 'link ' or die "$path has mode 120000",
3233 " but is not a link";
3235 if ($@) {
3236 warn "$@\n";
3237 sysseek($fh, 0, 0) or croak $!;
3241 my ($tmp_fh, $tmp_filename) = File::Temp::tempfile(UNLINK => 1);
3242 my $result;
3243 while ($result = sysread($fh, my $string, 1024)) {
3244 syswrite($tmp_fh, $string, $result);
3246 defined $result or croak $!;
3247 close $tmp_fh or croak $!;
3249 close $fh or croak $!;
3251 $hash = $::_repository->hash_and_insert_object($tmp_filename);
3252 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3253 close $fb->{base} or croak $!;
3254 } else {
3255 $hash = $fb->{blob} or die "no blob information\n";
3257 $fb->{pool}->clear;
3258 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3259 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3260 undef;
3263 sub abort_edit {
3264 my $self = shift;
3265 $self->{nr} = $self->{gii}->{nr};
3266 delete $self->{gii};
3267 $self->SUPER::abort_edit(@_);
3270 sub close_edit {
3271 my $self = shift;
3272 $self->{git_commit_ok} = 1;
3273 $self->{nr} = $self->{gii}->{nr};
3274 delete $self->{gii};
3275 $self->SUPER::close_edit(@_);
3278 package SVN::Git::Editor;
3279 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3280 use strict;
3281 use warnings;
3282 use Carp qw/croak/;
3283 use IO::File;
3285 sub new {
3286 my ($class, $opts) = @_;
3287 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3288 die "$_ required!\n" unless (defined $opts->{$_});
3291 my $pool = SVN::Pool->new;
3292 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3293 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3294 $opts->{r}, $mods);
3296 # $opts->{ra} functions should not be used after this:
3297 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3298 $opts->{editor_cb}, $pool);
3299 my $self = SVN::Delta::Editor->new(@ce, $pool);
3300 bless $self, $class;
3301 foreach (qw/svn_path r tree_a tree_b/) {
3302 $self->{$_} = $opts->{$_};
3304 $self->{url} = $opts->{ra}->{url};
3305 $self->{mods} = $mods;
3306 $self->{types} = $types;
3307 $self->{pool} = $pool;
3308 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3309 $self->{rm} = { };
3310 $self->{path_prefix} = length $self->{svn_path} ?
3311 "$self->{svn_path}/" : '';
3312 return $self;
3315 sub generate_diff {
3316 my ($tree_a, $tree_b) = @_;
3317 my @diff_tree = qw(diff-tree -z -r);
3318 if ($_cp_similarity) {
3319 push @diff_tree, "-C$_cp_similarity";
3320 } else {
3321 push @diff_tree, '-C';
3323 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3324 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3325 push @diff_tree, $tree_a, $tree_b;
3326 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3327 local $/ = "\0";
3328 my $state = 'meta';
3329 my @mods;
3330 while (<$diff_fh>) {
3331 chomp $_; # this gets rid of the trailing "\0"
3332 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3333 $::sha1\s($::sha1)\s
3334 ([MTCRAD])\d*$/xo) {
3335 push @mods, { mode_a => $1, mode_b => $2,
3336 sha1_b => $3, chg => $4 };
3337 if ($4 =~ /^(?:C|R)$/) {
3338 $state = 'file_a';
3339 } else {
3340 $state = 'file_b';
3342 } elsif ($state eq 'file_a') {
3343 my $x = $mods[$#mods] or croak "Empty array\n";
3344 if ($x->{chg} !~ /^(?:C|R)$/) {
3345 croak "Error parsing $_, $x->{chg}\n";
3347 $x->{file_a} = $_;
3348 $state = 'file_b';
3349 } elsif ($state eq 'file_b') {
3350 my $x = $mods[$#mods] or croak "Empty array\n";
3351 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3352 croak "Error parsing $_, $x->{chg}\n";
3354 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3355 croak "Error parsing $_, $x->{chg}\n";
3357 $x->{file_b} = $_;
3358 $state = 'meta';
3359 } else {
3360 croak "Error parsing $_\n";
3363 command_close_pipe($diff_fh, $ctx);
3364 \@mods;
3367 sub check_diff_paths {
3368 my ($ra, $pfx, $rev, $mods) = @_;
3369 my %types;
3370 $pfx .= '/' if length $pfx;
3372 sub type_diff_paths {
3373 my ($ra, $types, $path, $rev) = @_;
3374 my @p = split m#/+#, $path;
3375 my $c = shift @p;
3376 unless (defined $types->{$c}) {
3377 $types->{$c} = $ra->check_path($c, $rev);
3379 while (@p) {
3380 $c .= '/' . shift @p;
3381 next if defined $types->{$c};
3382 $types->{$c} = $ra->check_path($c, $rev);
3386 foreach my $m (@$mods) {
3387 foreach my $f (qw/file_a file_b/) {
3388 next unless defined $m->{$f};
3389 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3390 if (length $pfx.$dir && ! defined $types{$dir}) {
3391 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3395 \%types;
3398 sub split_path {
3399 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3402 sub repo_path {
3403 my ($self, $path) = @_;
3404 $self->{path_prefix}.(defined $path ? $path : '');
3407 sub url_path {
3408 my ($self, $path) = @_;
3409 if ($self->{url} =~ m#^https?://#) {
3410 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3412 $self->{url} . '/' . $self->repo_path($path);
3415 sub rmdirs {
3416 my ($self) = @_;
3417 my $rm = $self->{rm};
3418 delete $rm->{''}; # we never delete the url we're tracking
3419 return unless %$rm;
3421 foreach (keys %$rm) {
3422 my @d = split m#/#, $_;
3423 my $c = shift @d;
3424 $rm->{$c} = 1;
3425 while (@d) {
3426 $c .= '/' . shift @d;
3427 $rm->{$c} = 1;
3430 delete $rm->{$self->{svn_path}};
3431 delete $rm->{''}; # we never delete the url we're tracking
3432 return unless %$rm;
3434 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3435 $self->{tree_b});
3436 local $/ = "\0";
3437 while (<$fh>) {
3438 chomp;
3439 my @dn = split m#/#, $_;
3440 while (pop @dn) {
3441 delete $rm->{join '/', @dn};
3443 unless (%$rm) {
3444 close $fh;
3445 return;
3448 command_close_pipe($fh, $ctx);
3450 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3451 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3452 $self->close_directory($bat->{$d}, $p);
3453 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3454 print "\tD+\t$d/\n" unless $::_q;
3455 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3456 delete $bat->{$d};
3460 sub open_or_add_dir {
3461 my ($self, $full_path, $baton) = @_;
3462 my $t = $self->{types}->{$full_path};
3463 if (!defined $t) {
3464 die "$full_path not known in r$self->{r} or we have a bug!\n";
3467 no warnings 'once';
3468 # SVN::Node::none and SVN::Node::file are used only once,
3469 # so we're shutting up Perl's warnings about them.
3470 if ($t == $SVN::Node::none) {
3471 return $self->add_directory($full_path, $baton,
3472 undef, -1, $self->{pool});
3473 } elsif ($t == $SVN::Node::dir) {
3474 return $self->open_directory($full_path, $baton,
3475 $self->{r}, $self->{pool});
3476 } # no warnings 'once'
3477 print STDERR "$full_path already exists in repository at ",
3478 "r$self->{r} and it is not a directory (",
3479 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3480 } # no warnings 'once'
3481 exit 1;
3484 sub ensure_path {
3485 my ($self, $path) = @_;
3486 my $bat = $self->{bat};
3487 my $repo_path = $self->repo_path($path);
3488 return $bat->{''} unless (length $repo_path);
3489 my @p = split m#/+#, $repo_path;
3490 my $c = shift @p;
3491 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3492 while (@p) {
3493 my $c0 = $c;
3494 $c .= '/' . shift @p;
3495 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3497 return $bat->{$c};
3500 sub A {
3501 my ($self, $m) = @_;
3502 my ($dir, $file) = split_path($m->{file_b});
3503 my $pbat = $self->ensure_path($dir);
3504 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3505 undef, -1);
3506 print "\tA\t$m->{file_b}\n" unless $::_q;
3507 $self->chg_file($fbat, $m);
3508 $self->close_file($fbat,undef,$self->{pool});
3511 sub C {
3512 my ($self, $m) = @_;
3513 my ($dir, $file) = split_path($m->{file_b});
3514 my $pbat = $self->ensure_path($dir);
3515 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3516 $self->url_path($m->{file_a}), $self->{r});
3517 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3518 $self->chg_file($fbat, $m);
3519 $self->close_file($fbat,undef,$self->{pool});
3522 sub delete_entry {
3523 my ($self, $path, $pbat) = @_;
3524 my $rpath = $self->repo_path($path);
3525 my ($dir, $file) = split_path($rpath);
3526 $self->{rm}->{$dir} = 1;
3527 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3530 sub R {
3531 my ($self, $m) = @_;
3532 my ($dir, $file) = split_path($m->{file_b});
3533 my $pbat = $self->ensure_path($dir);
3534 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3535 $self->url_path($m->{file_a}), $self->{r});
3536 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3537 $self->chg_file($fbat, $m);
3538 $self->close_file($fbat,undef,$self->{pool});
3540 ($dir, $file) = split_path($m->{file_a});
3541 $pbat = $self->ensure_path($dir);
3542 $self->delete_entry($m->{file_a}, $pbat);
3545 sub M {
3546 my ($self, $m) = @_;
3547 my ($dir, $file) = split_path($m->{file_b});
3548 my $pbat = $self->ensure_path($dir);
3549 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3550 $pbat,$self->{r},$self->{pool});
3551 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3552 $self->chg_file($fbat, $m);
3553 $self->close_file($fbat,undef,$self->{pool});
3556 sub T { shift->M(@_) }
3558 sub change_file_prop {
3559 my ($self, $fbat, $pname, $pval) = @_;
3560 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3563 sub chg_file {
3564 my ($self, $fbat, $m) = @_;
3565 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3566 $self->change_file_prop($fbat,'svn:executable','*');
3567 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3568 $self->change_file_prop($fbat,'svn:executable',undef);
3570 my $fh = IO::File->new_tmpfile or croak $!;
3571 if ($m->{mode_b} =~ /^120/) {
3572 print $fh 'link ' or croak $!;
3573 $self->change_file_prop($fbat,'svn:special','*');
3574 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3575 $self->change_file_prop($fbat,'svn:special',undef);
3577 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
3578 croak "Failed to read object $m->{sha1_b}" if ($size < 0);
3579 $fh->flush == 0 or croak $!;
3580 seek $fh, 0, 0 or croak $!;
3582 my $exp = ::md5sum($fh);
3583 seek $fh, 0, 0 or croak $!;
3585 my $pool = SVN::Pool->new;
3586 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3587 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3588 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3589 $pool->clear;
3591 close $fh or croak $!;
3594 sub D {
3595 my ($self, $m) = @_;
3596 my ($dir, $file) = split_path($m->{file_b});
3597 my $pbat = $self->ensure_path($dir);
3598 print "\tD\t$m->{file_b}\n" unless $::_q;
3599 $self->delete_entry($m->{file_b}, $pbat);
3602 sub close_edit {
3603 my ($self) = @_;
3604 my ($p,$bat) = ($self->{pool}, $self->{bat});
3605 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3606 next if $_ eq '';
3607 $self->close_directory($bat->{$_}, $p);
3609 $self->close_directory($bat->{''}, $p);
3610 $self->SUPER::close_edit($p);
3611 $p->clear;
3614 sub abort_edit {
3615 my ($self) = @_;
3616 $self->SUPER::abort_edit($self->{pool});
3619 sub DESTROY {
3620 my $self = shift;
3621 $self->SUPER::DESTROY(@_);
3622 $self->{pool}->clear;
3625 # this drives the editor
3626 sub apply_diff {
3627 my ($self) = @_;
3628 my $mods = $self->{mods};
3629 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3630 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3631 my $f = $m->{chg};
3632 if (defined $o{$f}) {
3633 $self->$f($m);
3634 } else {
3635 fatal("Invalid change type: $f");
3638 $self->rmdirs if $_rmdir;
3639 if (@$mods == 0) {
3640 $self->abort_edit;
3641 } else {
3642 $self->close_edit;
3644 return scalar @$mods;
3647 package Git::SVN::Ra;
3648 use vars qw/@ISA $config_dir $_log_window_size/;
3649 use strict;
3650 use warnings;
3651 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3653 BEGIN {
3654 # enforce temporary pool usage for some simple functions
3655 no strict 'refs';
3656 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3657 my $SUPER = "SUPER::$f";
3658 *$f = sub {
3659 my $self = shift;
3660 my $pool = SVN::Pool->new;
3661 my @ret = $self->$SUPER(@_,$pool);
3662 $pool->clear;
3663 wantarray ? @ret : $ret[0];
3668 sub _auth_providers () {
3670 SVN::Client::get_simple_provider(),
3671 SVN::Client::get_ssl_server_trust_file_provider(),
3672 SVN::Client::get_simple_prompt_provider(
3673 \&Git::SVN::Prompt::simple, 2),
3674 SVN::Client::get_ssl_client_cert_file_provider(),
3675 SVN::Client::get_ssl_client_cert_prompt_provider(
3676 \&Git::SVN::Prompt::ssl_client_cert, 2),
3677 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3678 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3679 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3680 SVN::Client::get_username_provider(),
3681 SVN::Client::get_ssl_server_trust_prompt_provider(
3682 \&Git::SVN::Prompt::ssl_server_trust),
3683 SVN::Client::get_username_prompt_provider(
3684 \&Git::SVN::Prompt::username, 2)
3688 sub escape_uri_only {
3689 my ($uri) = @_;
3690 my @tmp;
3691 foreach (split m{/}, $uri) {
3692 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3693 push @tmp, $_;
3695 join('/', @tmp);
3698 sub escape_url {
3699 my ($url) = @_;
3700 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3701 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3702 $url = "$scheme://$domain$uri";
3704 $url;
3707 sub new {
3708 my ($class, $url) = @_;
3709 $url =~ s!/+$!!;
3710 return $RA if ($RA && $RA->{url} eq $url);
3712 SVN::_Core::svn_config_ensure($config_dir, undef);
3713 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3714 my $config = SVN::Core::config_get_config($config_dir);
3715 $RA = undef;
3716 my $dont_store_passwords = 1;
3717 my $conf_t = ${$config}{'config'};
3719 no warnings 'once';
3720 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3721 # produces warnings that variables are used only once.
3722 # I had not found the better way to shut them up, so
3723 # the warnings of type 'once' are disabled in this block.
3724 if (SVN::_Core::svn_config_get_bool($conf_t,
3725 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3726 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3727 1) == 0) {
3728 SVN::_Core::svn_auth_set_parameter($baton,
3729 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3730 bless (\$dont_store_passwords, "_p_void"));
3732 if (SVN::_Core::svn_config_get_bool($conf_t,
3733 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3734 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3735 1) == 0) {
3736 $Git::SVN::Prompt::_no_auth_cache = 1;
3738 } # no warnings 'once'
3739 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3740 config => $config,
3741 pool => SVN::Pool->new,
3742 auth_provider_callbacks => $callbacks);
3743 $self->{url} = $url;
3744 $self->{svn_path} = $url;
3745 $self->{repos_root} = $self->get_repos_root;
3746 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3747 $self->{cache} = { check_path => { r => 0, data => {} },
3748 get_dir => { r => 0, data => {} } };
3749 $RA = bless $self, $class;
3752 sub check_path {
3753 my ($self, $path, $r) = @_;
3754 my $cache = $self->{cache}->{check_path};
3755 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3756 return $cache->{data}->{$path};
3758 my $pool = SVN::Pool->new;
3759 my $t = $self->SUPER::check_path($path, $r, $pool);
3760 $pool->clear;
3761 if ($r != $cache->{r}) {
3762 %{$cache->{data}} = ();
3763 $cache->{r} = $r;
3765 $cache->{data}->{$path} = $t;
3768 sub get_dir {
3769 my ($self, $dir, $r) = @_;
3770 my $cache = $self->{cache}->{get_dir};
3771 if ($r == $cache->{r}) {
3772 if (my $x = $cache->{data}->{$dir}) {
3773 return wantarray ? @$x : $x->[0];
3776 my $pool = SVN::Pool->new;
3777 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3778 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3779 $pool->clear;
3780 if ($r != $cache->{r}) {
3781 %{$cache->{data}} = ();
3782 $cache->{r} = $r;
3784 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3785 wantarray ? (\%dirents, $r, $props) : \%dirents;
3788 sub DESTROY {
3789 # do not call the real DESTROY since we store ourselves in $RA
3792 sub get_log {
3793 my ($self, @args) = @_;
3794 my $pool = SVN::Pool->new;
3795 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3796 my $ret = $self->SUPER::get_log(@args, $pool);
3797 $pool->clear;
3798 $ret;
3801 sub trees_match {
3802 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3803 my $ctx = SVN::Client->new(auth => _auth_providers);
3804 my $out = IO::File->new_tmpfile;
3806 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3807 # $ctx->diff(), so we'll create a default one
3808 my $pool = SVN::Pool->new_default_sub;
3810 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3811 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3812 $out->flush;
3813 my $ret = (($out->stat)[7] == 0);
3814 close $out or croak $!;
3816 $ret;
3819 sub get_commit_editor {
3820 my ($self, $log, $cb, $pool) = @_;
3821 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3822 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3825 sub gs_do_update {
3826 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3827 my $new = ($rev_a == $rev_b);
3828 my $path = $gs->{path};
3830 if ($new && -e $gs->{index}) {
3831 unlink $gs->{index} or die
3832 "Couldn't unlink index: $gs->{index}: $!\n";
3834 my $pool = SVN::Pool->new;
3835 $editor->set_path_strip($path);
3836 my (@pc) = split m#/#, $path;
3837 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3838 1, $editor, $pool);
3839 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3841 # Since we can't rely on svn_ra_reparent being available, we'll
3842 # just have to do some magic with set_path to make it so
3843 # we only want a partial path.
3844 my $sp = '';
3845 my $final = join('/', @pc);
3846 while (@pc) {
3847 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3848 $sp .= '/' if length $sp;
3849 $sp .= shift @pc;
3851 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3853 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3855 $reporter->finish_report($pool);
3856 $pool->clear;
3857 $editor->{git_commit_ok};
3860 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3861 # svn_ra_reparent didn't work before 1.4)
3862 sub gs_do_switch {
3863 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3864 my $path = $gs->{path};
3865 my $pool = SVN::Pool->new;
3867 my $full_url = $self->{url};
3868 my $old_url = $full_url;
3869 $full_url .= '/' . escape_uri_only($path) if length $path;
3870 my ($ra, $reparented);
3871 if ($old_url ne $full_url) {
3872 if ($old_url !~ m#^svn(\+ssh)?://#) {
3873 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3874 $pool);
3875 $self->{url} = $full_url;
3876 $reparented = 1;
3877 } else {
3878 $_[0] = undef;
3879 $self = undef;
3880 $RA = undef;
3881 $ra = Git::SVN::Ra->new($full_url);
3882 $ra_invalid = 1;
3885 $ra ||= $self;
3886 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3887 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3888 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3889 $reporter->finish_report($pool);
3891 if ($reparented) {
3892 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3893 $self->{url} = $old_url;
3896 $pool->clear;
3897 $editor->{git_commit_ok};
3900 sub longest_common_path {
3901 my ($gsv, $globs) = @_;
3902 my %common;
3903 my $common_max = scalar @$gsv;
3905 foreach my $gs (@$gsv) {
3906 my @tmp = split m#/#, $gs->{path};
3907 my $p = '';
3908 foreach (@tmp) {
3909 $p .= length($p) ? "/$_" : $_;
3910 $common{$p} ||= 0;
3911 $common{$p}++;
3914 $globs ||= [];
3915 $common_max += scalar @$globs;
3916 foreach my $glob (@$globs) {
3917 my @tmp = split m#/#, $glob->{path}->{left};
3918 my $p = '';
3919 foreach (@tmp) {
3920 $p .= length($p) ? "/$_" : $_;
3921 $common{$p} ||= 0;
3922 $common{$p}++;
3926 my $longest_path = '';
3927 foreach (sort {length $b <=> length $a} keys %common) {
3928 if ($common{$_} == $common_max) {
3929 $longest_path = $_;
3930 last;
3933 $longest_path;
3936 sub gs_fetch_loop_common {
3937 my ($self, $base, $head, $gsv, $globs) = @_;
3938 return if ($base > $head);
3939 my $inc = $_log_window_size;
3940 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3941 my $longest_path = longest_common_path($gsv, $globs);
3942 my $ra_url = $self->{url};
3943 while (1) {
3944 my %revs;
3945 my $err;
3946 my $err_handler = $SVN::Error::handler;
3947 $SVN::Error::handler = sub {
3948 ($err) = @_;
3949 skip_unknown_revs($err);
3951 sub _cb {
3952 my ($paths, $r, $author, $date, $log) = @_;
3953 [ dup_changed_paths($paths),
3954 { author => $author, date => $date, log => $log } ];
3956 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3957 sub { $revs{$_[1]} = _cb(@_) });
3958 if ($err && $max >= $head) {
3959 print STDERR "Path '$longest_path' ",
3960 "was probably deleted:\n",
3961 $err->expanded_message,
3962 "\nWill attempt to follow ",
3963 "revisions r$min .. r$max ",
3964 "committed before the deletion\n";
3965 my $hi = $max;
3966 while (--$hi >= $min) {
3967 my $ok;
3968 $self->get_log([$longest_path], $min, $hi,
3969 0, 1, 1, sub {
3970 $ok ||= $_[1];
3971 $revs{$_[1]} = _cb(@_) });
3972 if ($ok) {
3973 print STDERR "r$min .. r$ok OK\n";
3974 last;
3978 $SVN::Error::handler = $err_handler;
3980 my %exists = map { $_->{path} => $_ } @$gsv;
3981 foreach my $r (sort {$a <=> $b} keys %revs) {
3982 my ($paths, $logged) = @{$revs{$r}};
3984 foreach my $gs ($self->match_globs(\%exists, $paths,
3985 $globs, $r)) {
3986 if ($gs->rev_map_max >= $r) {
3987 next;
3989 next unless $gs->match_paths($paths, $r);
3990 $gs->{logged_rev_props} = $logged;
3991 if (my $last_commit = $gs->last_commit) {
3992 $gs->assert_index_clean($last_commit);
3994 my $log_entry = $gs->do_fetch($paths, $r);
3995 if ($log_entry) {
3996 $gs->do_git_commit($log_entry);
3998 $INDEX_FILES{$gs->{index}} = 1;
4000 foreach my $g (@$globs) {
4001 my $k = "svn-remote.$g->{remote}." .
4002 "$g->{t}-maxRev";
4003 Git::SVN::tmp_config($k, $r);
4005 if ($ra_invalid) {
4006 $_[0] = undef;
4007 $self = undef;
4008 $RA = undef;
4009 $self = Git::SVN::Ra->new($ra_url);
4010 $ra_invalid = undef;
4013 # pre-fill the .rev_db since it'll eventually get filled in
4014 # with '0' x40 if something new gets committed
4015 foreach my $gs (@$gsv) {
4016 next if $gs->rev_map_max >= $max;
4017 next if defined $gs->rev_map_get($max);
4018 $gs->rev_map_set($max, 0 x40);
4020 foreach my $g (@$globs) {
4021 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4022 Git::SVN::tmp_config($k, $max);
4024 last if $max >= $head;
4025 $min = $max + 1;
4026 $max += $inc;
4027 $max = $head if ($max > $head);
4029 Git::SVN::gc();
4032 sub match_globs {
4033 my ($self, $exists, $paths, $globs, $r) = @_;
4035 sub get_dir_check {
4036 my ($self, $exists, $g, $r) = @_;
4037 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
4038 return unless scalar @x == 3;
4039 my $dirents = $x[0];
4040 foreach my $de (keys %$dirents) {
4041 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4042 my $p = $g->{path}->full_path($de);
4043 next if $exists->{$p};
4044 next if (length $g->{path}->{right} &&
4045 ($self->check_path($p, $r) !=
4046 $SVN::Node::dir));
4047 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4048 $g->{ref}->full_path($de), 1);
4051 foreach my $g (@$globs) {
4052 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4053 if ($path->{action} =~ /^[AR]$/) {
4054 get_dir_check($self, $exists, $g, $r);
4057 foreach (keys %$paths) {
4058 if (/$g->{path}->{left_regex}/ &&
4059 !/$g->{path}->{regex}/) {
4060 next if $paths->{$_}->{action} !~ /^[AR]$/;
4061 get_dir_check($self, $exists, $g, $r);
4063 next unless /$g->{path}->{regex}/;
4064 my $p = $1;
4065 my $pathname = $g->{path}->full_path($p);
4066 next if $exists->{$pathname};
4067 next if ($self->check_path($pathname, $r) !=
4068 $SVN::Node::dir);
4069 $exists->{$pathname} = Git::SVN->init(
4070 $self->{url}, $pathname, undef,
4071 $g->{ref}->full_path($p), 1);
4073 my $c = '';
4074 foreach (split m#/#, $g->{path}->{left}) {
4075 $c .= "/$_";
4076 next unless ($paths->{$c} &&
4077 ($paths->{$c}->{action} =~ /^[AR]$/));
4078 get_dir_check($self, $exists, $g, $r);
4081 values %$exists;
4084 sub minimize_url {
4085 my ($self) = @_;
4086 return $self->{url} if ($self->{url} eq $self->{repos_root});
4087 my $url = $self->{repos_root};
4088 my @components = split(m!/!, $self->{svn_path});
4089 my $c = '';
4090 do {
4091 $url .= "/$c" if length $c;
4092 eval { (ref $self)->new($url)->get_latest_revnum };
4093 } while ($@ && ($c = shift @components));
4094 $url;
4097 sub can_do_switch {
4098 my $self = shift;
4099 unless (defined $can_do_switch) {
4100 my $pool = SVN::Pool->new;
4101 my $rep = eval {
4102 $self->do_switch(1, '', 0, $self->{url},
4103 SVN::Delta::Editor->new, $pool);
4105 if ($@) {
4106 $can_do_switch = 0;
4107 } else {
4108 $rep->abort_report($pool);
4109 $can_do_switch = 1;
4111 $pool->clear;
4113 $can_do_switch;
4116 sub skip_unknown_revs {
4117 my ($err) = @_;
4118 my $errno = $err->apr_err();
4119 # Maybe the branch we're tracking didn't
4120 # exist when the repo started, so it's
4121 # not an error if it doesn't, just continue
4123 # Wonderfully consistent library, eh?
4124 # 160013 - svn:// and file://
4125 # 175002 - http(s)://
4126 # 175007 - http(s):// (this repo required authorization, too...)
4127 # More codes may be discovered later...
4128 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4129 my $err_key = $err->expanded_message;
4130 # revision numbers change every time, filter them out
4131 $err_key =~ s/\d+/\0/g;
4132 $err_key = "$errno\0$err_key";
4133 unless ($ignored_err{$err_key}) {
4134 warn "W: Ignoring error from SVN, path probably ",
4135 "does not exist: ($errno): ",
4136 $err->expanded_message,"\n";
4137 warn "W: Do not be alarmed at the above message ",
4138 "git-svn is just searching aggressively for ",
4139 "old history.\n",
4140 "This may take a while on large repositories\n";
4141 $ignored_err{$err_key} = 1;
4143 return;
4145 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4148 # svn_log_changed_path_t objects passed to get_log are likely to be
4149 # overwritten even if only the refs are copied to an external variable,
4150 # so we should dup the structures in their entirety. Using an externally
4151 # passed pool (instead of our temporary and quickly cleared pool in
4152 # Git::SVN::Ra) does not help matters at all...
4153 sub dup_changed_paths {
4154 my ($paths) = @_;
4155 return undef unless $paths;
4156 my %ret;
4157 foreach my $p (keys %$paths) {
4158 my $i = $paths->{$p};
4159 my %s = map { $_ => $i->$_ }
4160 qw/copyfrom_path copyfrom_rev action/;
4161 $ret{$p} = \%s;
4163 \%ret;
4166 package Git::SVN::Log;
4167 use strict;
4168 use warnings;
4169 use POSIX qw/strftime/;
4170 use constant commit_log_separator => ('-' x 72) . "\n";
4171 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4172 %rusers $show_commit $incremental/;
4173 my $l_fmt;
4175 sub cmt_showable {
4176 my ($c) = @_;
4177 return 1 if defined $c->{r};
4179 # big commit message got truncated by the 16k pretty buffer in rev-list
4180 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4181 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4182 @{$c->{l}} = ();
4183 my @log = command(qw/cat-file commit/, $c->{c});
4185 # shift off the headers
4186 shift @log while ($log[0] ne '');
4187 shift @log;
4189 # TODO: make $c->{l} not have a trailing newline in the future
4190 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4192 (undef, $c->{r}, undef) = ::extract_metadata(
4193 (grep(/^git-svn-id: /, @log))[-1]);
4195 return defined $c->{r};
4198 sub log_use_color {
4199 return $color || Git->repository->get_colorbool('color.diff');
4202 sub git_svn_log_cmd {
4203 my ($r_min, $r_max, @args) = @_;
4204 my $head = 'HEAD';
4205 my (@files, @log_opts);
4206 foreach my $x (@args) {
4207 if ($x eq '--' || @files) {
4208 push @files, $x;
4209 } else {
4210 if (::verify_ref("$x^0")) {
4211 $head = $x;
4212 } else {
4213 push @log_opts, $x;
4218 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4219 $gs ||= Git::SVN->_new;
4220 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4221 $gs->refname);
4222 push @cmd, '-r' unless $non_recursive;
4223 push @cmd, qw/--raw --name-status/ if $verbose;
4224 push @cmd, '--color' if log_use_color();
4225 push @cmd, @log_opts;
4226 if (defined $r_max && $r_max == $r_min) {
4227 push @cmd, '--max-count=1';
4228 if (my $c = $gs->rev_map_get($r_max)) {
4229 push @cmd, $c;
4231 } elsif (defined $r_max) {
4232 if ($r_max < $r_min) {
4233 ($r_min, $r_max) = ($r_max, $r_min);
4235 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4236 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4237 # If there are no commits in the range, both $c_max and $c_min
4238 # will be undefined. If there is at least 1 commit in the
4239 # range, both will be defined.
4240 return () if !defined $c_min || !defined $c_max;
4241 if ($c_min eq $c_max) {
4242 push @cmd, '--max-count=1', $c_min;
4243 } else {
4244 push @cmd, '--boundary', "$c_min..$c_max";
4247 return (@cmd, @files);
4250 # adapted from pager.c
4251 sub config_pager {
4252 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4253 if (!defined $pager) {
4254 $pager = 'less';
4255 } elsif (length $pager == 0 || $pager eq 'cat') {
4256 $pager = undef;
4258 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4261 sub run_pager {
4262 return unless -t *STDOUT && defined $pager;
4263 pipe my $rfd, my $wfd or return;
4264 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4265 if (!$pid) {
4266 open STDOUT, '>&', $wfd or
4267 ::fatal "Can't redirect to stdout: $!";
4268 return;
4270 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4271 $ENV{LESS} ||= 'FRSX';
4272 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4275 sub format_svn_date {
4276 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4279 sub parse_git_date {
4280 my ($t, $tz) = @_;
4281 # Date::Parse isn't in the standard Perl distro :(
4282 if ($tz =~ s/^\+//) {
4283 $t += tz_to_s_offset($tz);
4284 } elsif ($tz =~ s/^\-//) {
4285 $t -= tz_to_s_offset($tz);
4287 return $t;
4290 sub set_local_timezone {
4291 if (defined $TZ) {
4292 $ENV{TZ} = $TZ;
4293 } else {
4294 delete $ENV{TZ};
4298 sub tz_to_s_offset {
4299 my ($tz) = @_;
4300 $tz =~ s/(\d\d)$//;
4301 return ($1 * 60) + ($tz * 3600);
4304 sub get_author_info {
4305 my ($dest, $author, $t, $tz) = @_;
4306 $author =~ s/(?:^\s*|\s*$)//g;
4307 $dest->{a_raw} = $author;
4308 my $au;
4309 if ($::_authors) {
4310 $au = $rusers{$author} || undef;
4312 if (!$au) {
4313 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4315 $dest->{t} = $t;
4316 $dest->{tz} = $tz;
4317 $dest->{a} = $au;
4318 $dest->{t_utc} = parse_git_date($t, $tz);
4321 sub process_commit {
4322 my ($c, $r_min, $r_max, $defer) = @_;
4323 if (defined $r_min && defined $r_max) {
4324 if ($r_min == $c->{r} && $r_min == $r_max) {
4325 show_commit($c);
4326 return 0;
4328 return 1 if $r_min == $r_max;
4329 if ($r_min < $r_max) {
4330 # we need to reverse the print order
4331 return 0 if (defined $limit && --$limit < 0);
4332 push @$defer, $c;
4333 return 1;
4335 if ($r_min != $r_max) {
4336 return 1 if ($r_min < $c->{r});
4337 return 1 if ($r_max > $c->{r});
4340 return 0 if (defined $limit && --$limit < 0);
4341 show_commit($c);
4342 return 1;
4345 sub show_commit {
4346 my $c = shift;
4347 if ($oneline) {
4348 my $x = "\n";
4349 if (my $l = $c->{l}) {
4350 while ($l->[0] =~ /^\s*$/) { shift @$l }
4351 $x = $l->[0];
4353 $l_fmt ||= 'A' . length($c->{r});
4354 print 'r',pack($l_fmt, $c->{r}),' | ';
4355 print "$c->{c} | " if $show_commit;
4356 print $x;
4357 } else {
4358 show_commit_normal($c);
4362 sub show_commit_changed_paths {
4363 my ($c) = @_;
4364 return unless $c->{changed};
4365 print "Changed paths:\n", @{$c->{changed}};
4368 sub show_commit_normal {
4369 my ($c) = @_;
4370 print commit_log_separator, "r$c->{r} | ";
4371 print "$c->{c} | " if $show_commit;
4372 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4373 my $nr_line = 0;
4375 if (my $l = $c->{l}) {
4376 while ($l->[$#$l] eq "\n" && $#$l > 0
4377 && $l->[($#$l - 1)] eq "\n") {
4378 pop @$l;
4380 $nr_line = scalar @$l;
4381 if (!$nr_line) {
4382 print "1 line\n\n\n";
4383 } else {
4384 if ($nr_line == 1) {
4385 $nr_line = '1 line';
4386 } else {
4387 $nr_line .= ' lines';
4389 print $nr_line, "\n";
4390 show_commit_changed_paths($c);
4391 print "\n";
4392 print $_ foreach @$l;
4394 } else {
4395 print "1 line\n";
4396 show_commit_changed_paths($c);
4397 print "\n";
4400 foreach my $x (qw/raw stat diff/) {
4401 if ($c->{$x}) {
4402 print "\n";
4403 print $_ foreach @{$c->{$x}}
4408 sub cmd_show_log {
4409 my (@args) = @_;
4410 my ($r_min, $r_max);
4411 my $r_last = -1; # prevent dupes
4412 set_local_timezone();
4413 if (defined $::_revision) {
4414 if ($::_revision =~ /^(\d+):(\d+)$/) {
4415 ($r_min, $r_max) = ($1, $2);
4416 } elsif ($::_revision =~ /^\d+$/) {
4417 $r_min = $r_max = $::_revision;
4418 } else {
4419 ::fatal "-r$::_revision is not supported, use ",
4420 "standard 'git log' arguments instead";
4424 config_pager();
4425 @args = git_svn_log_cmd($r_min, $r_max, @args);
4426 if (!@args) {
4427 print commit_log_separator unless $incremental || $oneline;
4428 return;
4430 my $log = command_output_pipe(@args);
4431 run_pager();
4432 my (@k, $c, $d, $stat);
4433 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4434 while (<$log>) {
4435 if (/^${esc_color}commit -?($::sha1_short)/o) {
4436 my $cmt = $1;
4437 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4438 $r_last = $c->{r};
4439 process_commit($c, $r_min, $r_max, \@k) or
4440 goto out;
4442 $d = undef;
4443 $c = { c => $cmt };
4444 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4445 get_author_info($c, $1, $2, $3);
4446 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4447 # ignore
4448 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4449 push @{$c->{raw}}, $_;
4450 } elsif (/^${esc_color}[ACRMDT]\t/) {
4451 # we could add $SVN->{svn_path} here, but that requires
4452 # remote access at the moment (repo_path_split)...
4453 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4454 push @{$c->{changed}}, $_;
4455 } elsif (/^${esc_color}diff /o) {
4456 $d = 1;
4457 push @{$c->{diff}}, $_;
4458 } elsif ($d) {
4459 push @{$c->{diff}}, $_;
4460 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4461 $esc_color*[\+\-]*$esc_color$/x) {
4462 $stat = 1;
4463 push @{$c->{stat}}, $_;
4464 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4465 push @{$c->{stat}}, $_;
4466 $stat = undef;
4467 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4468 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4469 } elsif (s/^${esc_color} //o) {
4470 push @{$c->{l}}, $_;
4473 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4474 $r_last = $c->{r};
4475 process_commit($c, $r_min, $r_max, \@k);
4477 if (@k) {
4478 ($r_min, $r_max) = ($r_max, $r_min);
4479 process_commit($_, $r_min, $r_max) foreach reverse @k;
4481 out:
4482 close $log;
4483 print commit_log_separator unless $incremental || $oneline;
4486 sub cmd_blame {
4487 my $path = pop;
4489 config_pager();
4490 run_pager();
4492 my ($fh, $ctx, $rev);
4494 if ($_git_format) {
4495 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4496 while (my $line = <$fh>) {
4497 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4498 # Uncommitted edits show up as a rev ID of
4499 # all zeros, which we can't look up with
4500 # cmt_metadata
4501 if ($1 !~ /^0+$/) {
4502 (undef, $rev, undef) =
4503 ::cmt_metadata($1);
4504 $rev = '0' if (!$rev);
4505 } else {
4506 $rev = '0';
4508 $rev = sprintf('%-10s', $rev);
4509 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4511 print $line;
4513 } else {
4514 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4515 '--', $path);
4516 my ($sha1);
4517 my %authors;
4518 while (my $line = <$fh>) {
4519 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4520 $sha1 = $1;
4521 (undef, $rev, undef) = ::cmt_metadata($1);
4522 $rev = '0' if (!$rev);
4524 elsif ($line =~ /^author (.*)/) {
4525 $authors{$rev} = $1;
4526 $authors{$rev} =~ s/\s/_/g;
4528 elsif ($line =~ /^\t(.*)$/) {
4529 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4533 command_close_pipe($fh, $ctx);
4536 package Git::SVN::Migration;
4537 # these version numbers do NOT correspond to actual version numbers
4538 # of git nor git-svn. They are just relative.
4540 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4542 # v1 layout: .git/$id/info/url, refs/remotes/$id
4544 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4546 # v3 layout: .git/svn/$id, refs/remotes/$id
4547 # - info/url may remain for backwards compatibility
4548 # - this is what we migrate up to this layout automatically,
4549 # - this will be used by git svn init on single branches
4550 # v3.1 layout (auto migrated):
4551 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4552 # for backwards compatibility
4554 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4555 # - this is only created for newly multi-init-ed
4556 # repositories. Similar in spirit to the
4557 # --use-separate-remotes option in git-clone (now default)
4558 # - we do not automatically migrate to this (following
4559 # the example set by core git)
4561 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4562 # - newer, more-efficient format that uses 24-bytes per record
4563 # with no filler space.
4564 # - use xxd -c24 < .rev_map.$UUID to view and debug
4565 # - This is a one-way migration, repositories updated to the
4566 # new format will not be able to use old git-svn without
4567 # rebuilding the .rev_db. Rebuilding the rev_db is not
4568 # possible if noMetadata or useSvmProps are set; but should
4569 # be no problem for users that use the (sensible) defaults.
4570 use strict;
4571 use warnings;
4572 use Carp qw/croak/;
4573 use File::Path qw/mkpath/;
4574 use File::Basename qw/dirname basename/;
4575 use vars qw/$_minimize/;
4577 sub migrate_from_v0 {
4578 my $git_dir = $ENV{GIT_DIR};
4579 return undef unless -d $git_dir;
4580 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4581 my $migrated = 0;
4582 while (<$fh>) {
4583 chomp;
4584 my ($id, $orig_ref) = ($_, $_);
4585 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4586 next unless -f "$git_dir/$id/info/url";
4587 my $new_ref = "refs/remotes/$id";
4588 if (::verify_ref("$new_ref^0")) {
4589 print STDERR "W: $orig_ref is probably an old ",
4590 "branch used by an ancient version of ",
4591 "git-svn.\n",
4592 "However, $new_ref also exists.\n",
4593 "We will not be able ",
4594 "to use this branch until this ",
4595 "ambiguity is resolved.\n";
4596 next;
4598 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4599 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4600 command_noisy('update-ref', $new_ref, $orig_ref);
4601 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4602 $migrated++;
4604 command_close_pipe($fh, $ctx);
4605 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4606 $migrated;
4609 sub migrate_from_v1 {
4610 my $git_dir = $ENV{GIT_DIR};
4611 my $migrated = 0;
4612 return $migrated unless -d $git_dir;
4613 my $svn_dir = "$git_dir/svn";
4615 # just in case somebody used 'svn' as their $id at some point...
4616 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4618 print STDERR "Migrating from a git-svn v1 layout...\n";
4619 mkpath([$svn_dir]);
4620 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4621 "$svn_dir\n\t(required for this version ",
4622 "($::VERSION) of git-svn) does not. exist\n";
4623 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4624 while (<$fh>) {
4625 my $x = $_;
4626 next unless $x =~ s#^refs/remotes/##;
4627 chomp $x;
4628 next unless -f "$git_dir/$x/info/url";
4629 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4630 next unless $u;
4631 my $dn = dirname("$git_dir/svn/$x");
4632 mkpath([$dn]) unless -d $dn;
4633 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4634 mkpath(["$git_dir/svn/svn"]);
4635 print STDERR " - $git_dir/$x/info => ",
4636 "$git_dir/svn/$x/info\n";
4637 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4638 croak "$!: $x";
4639 # don't worry too much about these, they probably
4640 # don't exist with repos this old (save for index,
4641 # and we can easily regenerate that)
4642 foreach my $f (qw/unhandled.log index .rev_db/) {
4643 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4645 } else {
4646 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4647 rename "$git_dir/$x", "$git_dir/svn/$x" or
4648 croak "$!: $x";
4650 $migrated++;
4652 command_close_pipe($fh, $ctx);
4653 print STDERR "Done migrating from a git-svn v1 layout\n";
4654 $migrated;
4657 sub read_old_urls {
4658 my ($l_map, $pfx, $path) = @_;
4659 my @dir;
4660 foreach (<$path/*>) {
4661 if (-r "$_/info/url") {
4662 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4663 my $ref_id = $pfx . basename $_;
4664 my $url = ::file_to_s("$_/info/url");
4665 $l_map->{$ref_id} = $url;
4666 } elsif (-d $_) {
4667 push @dir, $_;
4670 foreach (@dir) {
4671 my $x = $_;
4672 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4673 read_old_urls($l_map, $x, $_);
4677 sub migrate_from_v2 {
4678 my @cfg = command(qw/config -l/);
4679 return if grep /^svn-remote\..+\.url=/, @cfg;
4680 my %l_map;
4681 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4682 my $migrated = 0;
4684 foreach my $ref_id (sort keys %l_map) {
4685 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4686 if ($@) {
4687 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4689 $migrated++;
4691 $migrated;
4694 sub minimize_connections {
4695 my $r = Git::SVN::read_all_remotes();
4696 my $new_urls = {};
4697 my $root_repos = {};
4698 foreach my $repo_id (keys %$r) {
4699 my $url = $r->{$repo_id}->{url} or next;
4700 my $fetch = $r->{$repo_id}->{fetch} or next;
4701 my $ra = Git::SVN::Ra->new($url);
4703 # skip existing cases where we already connect to the root
4704 if (($ra->{url} eq $ra->{repos_root}) ||
4705 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4706 $repo_id)) {
4707 $root_repos->{$ra->{url}} = $repo_id;
4708 next;
4711 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4712 my $root_path = $ra->{url};
4713 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4714 foreach my $path (keys %$fetch) {
4715 my $ref_id = $fetch->{$path};
4716 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4718 # make sure we can read when connecting to
4719 # a higher level of a repository
4720 my ($last_rev, undef) = $gs->last_rev_commit;
4721 if (!defined $last_rev) {
4722 $last_rev = eval {
4723 $root_ra->get_latest_revnum;
4725 next if $@;
4727 my $new = $root_path;
4728 $new .= length $path ? "/$path" : '';
4729 eval {
4730 $root_ra->get_log([$new], $last_rev, $last_rev,
4731 0, 0, 1, sub { });
4733 next if $@;
4734 $new_urls->{$ra->{repos_root}}->{$new} =
4735 { ref_id => $ref_id,
4736 old_repo_id => $repo_id,
4737 old_path => $path };
4741 my @emptied;
4742 foreach my $url (keys %$new_urls) {
4743 # see if we can re-use an existing [svn-remote "repo_id"]
4744 # instead of creating a(n ugly) new section:
4745 my $repo_id = $root_repos->{$url} ||
4746 Git::SVN::sanitize_remote_name($url);
4748 my $fetch = $new_urls->{$url};
4749 foreach my $path (keys %$fetch) {
4750 my $x = $fetch->{$path};
4751 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4752 my $pfx = "svn-remote.$x->{old_repo_id}";
4754 my $old_fetch = quotemeta("$x->{old_path}:".
4755 "refs/remotes/$x->{ref_id}");
4756 command_noisy(qw/config --unset/,
4757 "$pfx.fetch", '^'. $old_fetch . '$');
4758 delete $r->{$x->{old_repo_id}}->
4759 {fetch}->{$x->{old_path}};
4760 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4761 command_noisy(qw/config --unset/,
4762 "$pfx.url");
4763 push @emptied, $x->{old_repo_id}
4767 if (@emptied) {
4768 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4769 "$ENV{GIT_DIR}/config";
4770 print STDERR <<EOF;
4771 The following [svn-remote] sections in your config file ($file) are empty
4772 and can be safely removed:
4774 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4778 sub migration_check {
4779 migrate_from_v0();
4780 migrate_from_v1();
4781 migrate_from_v2();
4782 minimize_connections() if $_minimize;
4785 package Git::IndexInfo;
4786 use strict;
4787 use warnings;
4788 use Git qw/command_input_pipe command_close_pipe/;
4790 sub new {
4791 my ($class) = @_;
4792 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4793 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4796 sub remove {
4797 my ($self, $path) = @_;
4798 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4799 return ++$self->{nr};
4801 undef;
4804 sub update {
4805 my ($self, $mode, $hash, $path) = @_;
4806 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4807 return ++$self->{nr};
4809 undef;
4812 sub DESTROY {
4813 my ($self) = @_;
4814 command_close_pipe($self->{gui}, $self->{ctx});
4817 package Git::SVN::GlobSpec;
4818 use strict;
4819 use warnings;
4821 sub new {
4822 my ($class, $glob) = @_;
4823 my $re = $glob;
4824 $re =~ s!/+$!!g; # no need for trailing slashes
4825 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4826 my ($left, $right) = ($1, $2);
4827 if ($nr > 1) {
4828 die "Only one '*' wildcard expansion ",
4829 "is supported (got $nr): '$glob'\n";
4830 } elsif ($nr == 0) {
4831 die "One '*' is needed for glob: '$glob'\n";
4833 $re = quotemeta($left) . $re . quotemeta($right);
4834 if (length $left && !($left =~ s!/+$!!g)) {
4835 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4837 if (length $right && !($right =~ s!^/+!!g)) {
4838 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4840 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4841 bless { left => $left, right => $right, left_regex => $left_re,
4842 regex => qr/$re/, glob => $glob }, $class;
4845 sub full_path {
4846 my ($self, $path) = @_;
4847 return (length $self->{left} ? "$self->{left}/" : '') .
4848 $path . (length $self->{right} ? "/$self->{right}" : '');
4851 __END__
4853 Data structures:
4856 $remotes = { # returned by read_all_remotes()
4857 'svn' => {
4858 # svn-remote.svn.url=https://svn.musicpd.org
4859 url => 'https://svn.musicpd.org',
4860 # svn-remote.svn.fetch=mpd/trunk:trunk
4861 fetch => {
4862 'mpd/trunk' => 'trunk',
4864 # svn-remote.svn.tags=mpd/tags/*:tags/*
4865 tags => {
4866 path => {
4867 left => 'mpd/tags',
4868 right => '',
4869 regex => qr!mpd/tags/([^/]+)$!,
4870 glob => 'tags/*',
4872 ref => {
4873 left => 'tags',
4874 right => '',
4875 regex => qr!tags/([^/]+)$!,
4876 glob => 'tags/*',
4882 $log_entry hashref as returned by libsvn_log_entry()
4884 log => 'whitespace-formatted log entry
4885 ', # trailing newline is preserved
4886 revision => '8', # integer
4887 date => '2004-02-24T17:01:44.108345Z', # commit date
4888 author => 'committer name'
4892 # this is generated by generate_diff();
4893 @mods = array of diff-index line hashes, each element represents one line
4894 of diff-index output
4896 diff-index line ($m hash)
4898 mode_a => first column of diff-index output, no leading ':',
4899 mode_b => second column of diff-index output,
4900 sha1_b => sha1sum of the final blob,
4901 chg => change type [MCRADT],
4902 file_a => original file name of a file (iff chg is 'C' or 'R')
4903 file_b => new/current file name of a file (any chg)
4907 # retval of read_url_paths{,_all}();
4908 $l_map = {
4909 # repository root url
4910 'https://svn.musicpd.org' => {
4911 # repository path # GIT_SVN_ID
4912 'mpd/trunk' => 'trunk',
4913 'mpd/tags/0.11.5' => 'tags/0.11.5',
4917 Notes:
4918 I don't trust the each() function on unless I created %hash myself
4919 because the internal iterator may not have started at base.