Teach fsck and prune that tmp_obj_ file names may not be 14 bytes long
[git/git-p4.git] / git-svn.perl
blobdf0ed9027df2c3b8b8f9d7f4f4046f3a0b1ae7f1
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: git svn <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, $uuid, $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, $uuid);
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 $path =~ s#^/##;
647 $path =~ s#^\.$##;
648 return $path;
651 # get_svnprops(PATH)
652 # ------------------
653 # Helper for cmd_propget and cmd_proplist below.
654 sub get_svnprops {
655 my $path = shift;
656 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
657 $gs ||= Git::SVN->new;
659 # prefix THE PATH by the sub-directory from which the user
660 # invoked us.
661 $path = $cmd_dir_prefix . $path;
662 fatal("No such file or directory: $path") unless -e $path;
663 my $is_dir = -d $path ? 1 : 0;
664 $path = $gs->{path} . '/' . $path;
666 # canonicalize the path (otherwise libsvn will abort or fail to
667 # find the file)
668 $path = canonicalize_path($path);
670 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
671 my $props;
672 if ($is_dir) {
673 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
675 else {
676 (undef, $props) = $gs->ra->get_file($path, $r, undef);
678 return $props;
681 # cmd_propget (PROP, PATH)
682 # ------------------------
683 # Print the SVN property PROP for PATH.
684 sub cmd_propget {
685 my ($prop, $path) = @_;
686 $path = '.' if not defined $path;
687 usage(1) if not defined $prop;
688 my $props = get_svnprops($path);
689 if (not defined $props->{$prop}) {
690 fatal("`$path' does not have a `$prop' SVN property.");
692 print $props->{$prop} . "\n";
695 # cmd_proplist (PATH)
696 # -------------------
697 # Print the list of SVN properties for PATH.
698 sub cmd_proplist {
699 my $path = shift;
700 $path = '.' if not defined $path;
701 my $props = get_svnprops($path);
702 print "Properties on '$path':\n";
703 foreach (sort keys %{$props}) {
704 print " $_\n";
708 sub cmd_multi_init {
709 my $url = shift;
710 unless (defined $_trunk || defined $_branches || defined $_tags) {
711 usage(1);
714 # there are currently some bugs that prevent multi-init/multi-fetch
715 # setups from working well without this.
716 $Git::SVN::_minimize_url = 1;
718 $_prefix = '' unless defined $_prefix;
719 if (defined $url) {
720 $url =~ s#/+$##;
721 init_subdir(@_);
723 do_git_init_db();
724 if (defined $_trunk) {
725 my $trunk_ref = $_prefix . 'trunk';
726 # try both old-style and new-style lookups:
727 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
728 unless ($gs_trunk) {
729 my ($trunk_url, $trunk_path) =
730 complete_svn_url($url, $_trunk);
731 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
732 undef, $trunk_ref);
735 return unless defined $_branches || defined $_tags;
736 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
737 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
738 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
741 sub cmd_multi_fetch {
742 my $remotes = Git::SVN::read_all_remotes();
743 foreach my $repo_id (sort keys %$remotes) {
744 if ($remotes->{$repo_id}->{url}) {
745 Git::SVN::fetch_all($repo_id, $remotes);
750 # this command is special because it requires no metadata
751 sub cmd_commit_diff {
752 my ($ta, $tb, $url) = @_;
753 my $usage = "Usage: $0 commit-diff -r<revision> ".
754 "<tree-ish> <tree-ish> [<URL>]";
755 fatal($usage) if (!defined $ta || !defined $tb);
756 my $svn_path = '';
757 if (!defined $url) {
758 my $gs = eval { Git::SVN->new };
759 if (!$gs) {
760 fatal("Needed URL or usable git-svn --id in ",
761 "the command-line\n", $usage);
763 $url = $gs->{url};
764 $svn_path = $gs->{path};
766 unless (defined $_revision) {
767 fatal("-r|--revision is a required argument\n", $usage);
769 if (defined $_message && defined $_file) {
770 fatal("Both --message/-m and --file/-F specified ",
771 "for the commit message.\n",
772 "I have no idea what you mean");
774 if (defined $_file) {
775 $_message = file_to_s($_file);
776 } else {
777 $_message ||= get_commit_entry($tb)->{log};
779 my $ra ||= Git::SVN::Ra->new($url);
780 my $r = $_revision;
781 if ($r eq 'HEAD') {
782 $r = $ra->get_latest_revnum;
783 } elsif ($r !~ /^\d+$/) {
784 die "revision argument: $r not understood by git-svn\n";
786 my %ed_opts = ( r => $r,
787 log => $_message,
788 ra => $ra,
789 tree_a => $ta,
790 tree_b => $tb,
791 editor_cb => sub { print "Committed r$_[0]\n" },
792 svn_path => $svn_path );
793 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
794 print "No changes\n$ta == $tb\n";
798 sub cmd_info {
799 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
800 if (exists $_[1]) {
801 die "Too many arguments specified\n";
804 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
806 if (!$file_type && !$diff_status) {
807 print STDERR "$path: (Not a versioned resource)\n\n";
808 return;
811 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
812 unless ($gs) {
813 die "Unable to determine upstream SVN information from ",
814 "working tree history\n";
817 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
818 $path = "." if $path eq "";
820 my $full_url = $url . ($path eq "." ? "" : "/$path");
822 if ($_url) {
823 print $full_url, "\n";
824 return;
827 my $result = "Path: $path\n";
828 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
829 $result .= "URL: " . $full_url . "\n";
831 eval {
832 my $repos_root = $gs->repos_root;
833 Git::SVN::remove_username($repos_root);
834 $result .= "Repository Root: $repos_root\n";
836 if ($@) {
837 $result .= "Repository Root: (offline)\n";
839 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
840 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
842 $result .= "Node Kind: " .
843 ($file_type eq "dir" ? "directory" : "file") . "\n";
845 my $schedule = $diff_status eq "A"
846 ? "add"
847 : ($diff_status eq "D" ? "delete" : "normal");
848 $result .= "Schedule: $schedule\n";
850 if ($diff_status eq "A") {
851 print $result, "\n";
852 return;
855 my ($lc_author, $lc_rev, $lc_date_utc);
856 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
857 my $log = command_output_pipe(@args);
858 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
859 while (<$log>) {
860 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
861 $lc_author = $1;
862 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
863 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
864 (undef, $lc_rev, undef) = ::extract_metadata($1);
867 close $log;
869 Git::SVN::Log::set_local_timezone();
871 $result .= "Last Changed Author: $lc_author\n";
872 $result .= "Last Changed Rev: $lc_rev\n";
873 $result .= "Last Changed Date: " .
874 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
876 if ($file_type ne "dir") {
877 my $text_last_updated_date =
878 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
879 $result .=
880 "Text Last Updated: " .
881 Git::SVN::Log::format_svn_date($text_last_updated_date) .
882 "\n";
883 my $checksum;
884 if ($diff_status eq "D") {
885 my ($fh, $ctx) =
886 command_output_pipe(qw(cat-file blob), "HEAD:$path");
887 if ($file_type eq "link") {
888 my $file_name = <$fh>;
889 $checksum = md5sum("link $file_name");
890 } else {
891 $checksum = md5sum($fh);
893 command_close_pipe($fh, $ctx);
894 } elsif ($file_type eq "link") {
895 my $file_name =
896 command(qw(cat-file blob), "HEAD:$path");
897 $checksum =
898 md5sum("link " . $file_name);
899 } else {
900 open FILE, "<", $path or die $!;
901 $checksum = md5sum(\*FILE);
902 close FILE or die $!;
904 $result .= "Checksum: " . $checksum . "\n";
907 print $result, "\n";
910 ########################### utility functions #########################
912 sub rebase_cmd {
913 my @cmd = qw/rebase/;
914 push @cmd, '-v' if $_verbose;
915 push @cmd, qw/--merge/ if $_merge;
916 push @cmd, "--strategy=$_strategy" if $_strategy;
917 @cmd;
920 sub post_fetch_checkout {
921 return if $_no_checkout;
922 my $gs = $Git::SVN::_head or return;
923 return if verify_ref('refs/heads/master^0');
925 my $valid_head = verify_ref('HEAD^0');
926 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
927 return if ($valid_head || !verify_ref('HEAD^0'));
929 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
930 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
931 return if -f $index;
933 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
934 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
935 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
936 print STDERR "Checked out HEAD:\n ",
937 $gs->full_url, " r", $gs->last_rev, "\n";
940 sub complete_svn_url {
941 my ($url, $path) = @_;
942 $path =~ s#/+$##;
943 if ($path !~ m#^[a-z\+]+://#) {
944 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
945 fatal("E: '$path' is not a complete URL ",
946 "and a separate URL is not specified");
948 return ($url, $path);
950 return ($path, '');
953 sub complete_url_ls_init {
954 my ($ra, $repo_path, $switch, $pfx) = @_;
955 unless ($repo_path) {
956 print STDERR "W: $switch not specified\n";
957 return;
959 $repo_path =~ s#/+$##;
960 if ($repo_path =~ m#^[a-z\+]+://#) {
961 $ra = Git::SVN::Ra->new($repo_path);
962 $repo_path = '';
963 } else {
964 $repo_path =~ s#^/+##;
965 unless ($ra) {
966 fatal("E: '$repo_path' is not a complete URL ",
967 "and a separate URL is not specified");
970 my $url = $ra->{url};
971 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
972 my $k = "svn-remote.$gs->{repo_id}.url";
973 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
974 if ($orig_url && ($orig_url ne $gs->{url})) {
975 die "$k already set: $orig_url\n",
976 "wanted to set to: $gs->{url}\n";
978 command_oneline('config', $k, $gs->{url}) unless $orig_url;
979 my $remote_path = "$ra->{svn_path}/$repo_path";
980 $remote_path =~ s#/+#/#g;
981 $remote_path =~ s#^/##g;
982 $remote_path .= "/*" if $remote_path !~ /\*/;
983 my ($n) = ($switch =~ /^--(\w+)/);
984 if (length $pfx && $pfx !~ m#/$#) {
985 die "--prefix='$pfx' must have a trailing slash '/'\n";
987 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
988 "$remote_path:refs/remotes/$pfx*");
991 sub verify_ref {
992 my ($ref) = @_;
993 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
994 { STDERR => 0 }); };
997 sub get_tree_from_treeish {
998 my ($treeish) = @_;
999 # $treeish can be a symbolic ref, too:
1000 my $type = command_oneline(qw/cat-file -t/, $treeish);
1001 my $expected;
1002 while ($type eq 'tag') {
1003 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1005 if ($type eq 'commit') {
1006 $expected = (grep /^tree /, command(qw/cat-file commit/,
1007 $treeish))[0];
1008 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1009 die "Unable to get tree from $treeish\n" unless $expected;
1010 } elsif ($type eq 'tree') {
1011 $expected = $treeish;
1012 } else {
1013 die "$treeish is a $type, expected tree, tag or commit\n";
1015 return $expected;
1018 sub get_commit_entry {
1019 my ($treeish) = shift;
1020 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1021 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1022 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1023 open my $log_fh, '>', $commit_editmsg or croak $!;
1025 my $type = command_oneline(qw/cat-file -t/, $treeish);
1026 if ($type eq 'commit' || $type eq 'tag') {
1027 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1028 $type, $treeish);
1029 my $in_msg = 0;
1030 my $author;
1031 my $saw_from = 0;
1032 my $msgbuf = "";
1033 while (<$msg_fh>) {
1034 if (!$in_msg) {
1035 $in_msg = 1 if (/^\s*$/);
1036 $author = $1 if (/^author (.*>)/);
1037 } elsif (/^git-svn-id: /) {
1038 # skip this for now, we regenerate the
1039 # correct one on re-fetch anyways
1040 # TODO: set *:merge properties or like...
1041 } else {
1042 if (/^From:/ || /^Signed-off-by:/) {
1043 $saw_from = 1;
1045 $msgbuf .= $_;
1048 $msgbuf =~ s/\s+$//s;
1049 if ($Git::SVN::_add_author_from && defined($author)
1050 && !$saw_from) {
1051 $msgbuf .= "\n\nFrom: $author";
1053 print $log_fh $msgbuf or croak $!;
1054 command_close_pipe($msg_fh, $ctx);
1056 close $log_fh or croak $!;
1058 if ($_edit || ($type eq 'tree')) {
1059 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1060 # TODO: strip out spaces, comments, like git-commit.sh
1061 system($editor, $commit_editmsg);
1063 rename $commit_editmsg, $commit_msg or croak $!;
1064 open $log_fh, '<', $commit_msg or croak $!;
1065 { local $/; chomp($log_entry{log} = <$log_fh>); }
1066 close $log_fh or croak $!;
1067 unlink $commit_msg;
1068 \%log_entry;
1071 sub s_to_file {
1072 my ($str, $file, $mode) = @_;
1073 open my $fd,'>',$file or croak $!;
1074 print $fd $str,"\n" or croak $!;
1075 close $fd or croak $!;
1076 chmod ($mode &~ umask, $file) if (defined $mode);
1079 sub file_to_s {
1080 my $file = shift;
1081 open my $fd,'<',$file or croak "$!: file: $file\n";
1082 local $/;
1083 my $ret = <$fd>;
1084 close $fd or croak $!;
1085 $ret =~ s/\s*$//s;
1086 return $ret;
1089 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1090 sub load_authors {
1091 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1092 my $log = $cmd eq 'log';
1093 while (<$authors>) {
1094 chomp;
1095 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1096 my ($user, $name, $email) = ($1, $2, $3);
1097 if ($log) {
1098 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1099 } else {
1100 $users{$user} = [$name, $email];
1103 close $authors or croak $!;
1106 # convert GetOpt::Long specs for use by git-config
1107 sub read_repo_config {
1108 return unless -d $ENV{GIT_DIR};
1109 my $opts = shift;
1110 my @config_only;
1111 foreach my $o (keys %$opts) {
1112 # if we have mixedCase and a long option-only, then
1113 # it's a config-only variable that we don't need for
1114 # the command-line.
1115 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1116 my $v = $opts->{$o};
1117 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1118 $key =~ s/-//g;
1119 my $arg = 'git-config';
1120 $arg .= ' --int' if ($o =~ /[:=]i$/);
1121 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1122 if (ref $v eq 'ARRAY') {
1123 chomp(my @tmp = `$arg --get-all svn.$key`);
1124 @$v = @tmp if @tmp;
1125 } else {
1126 chomp(my $tmp = `$arg --get svn.$key`);
1127 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1128 $$v = $tmp;
1132 delete @$opts{@config_only} if @config_only;
1135 sub extract_metadata {
1136 my $id = shift or return (undef, undef, undef);
1137 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1138 \s([a-f\d\-]+)$/x);
1139 if (!defined $rev || !$uuid || !$url) {
1140 # some of the original repositories I made had
1141 # identifiers like this:
1142 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1144 return ($url, $rev, $uuid);
1147 sub cmt_metadata {
1148 return extract_metadata((grep(/^git-svn-id: /,
1149 command(qw/cat-file commit/, shift)))[-1]);
1152 sub working_head_info {
1153 my ($head, $refs) = @_;
1154 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1155 my ($fh, $ctx) = command_output_pipe(@args, $head);
1156 my $hash;
1157 my %max;
1158 while (<$fh>) {
1159 if ( m{^commit ($::sha1)$} ) {
1160 unshift @$refs, $hash if $hash and $refs;
1161 $hash = $1;
1162 next;
1164 next unless s{^\s*(git-svn-id:)}{$1};
1165 my ($url, $rev, $uuid) = extract_metadata($_);
1166 if (defined $url && defined $rev) {
1167 next if $max{$url} and $max{$url} < $rev;
1168 if (my $gs = Git::SVN->find_by_url($url)) {
1169 my $c = $gs->rev_map_get($rev, $uuid);
1170 if ($c && $c eq $hash) {
1171 close $fh; # break the pipe
1172 return ($url, $rev, $uuid, $gs);
1173 } else {
1174 $max{$url} ||= $gs->rev_map_max;
1179 command_close_pipe($fh, $ctx);
1180 (undef, undef, undef, undef);
1183 sub read_commit_parents {
1184 my ($parents, $c) = @_;
1185 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1186 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1187 @{$parents->{$c}} = split(/ /, $p);
1190 sub linearize_history {
1191 my ($gs, $refs) = @_;
1192 my %parents;
1193 foreach my $c (@$refs) {
1194 read_commit_parents(\%parents, $c);
1197 my @linear_refs;
1198 my %skip = ();
1199 my $last_svn_commit = $gs->last_commit;
1200 foreach my $c (reverse @$refs) {
1201 next if $c eq $last_svn_commit;
1202 last if $skip{$c};
1204 unshift @linear_refs, $c;
1205 $skip{$c} = 1;
1207 # we only want the first parent to diff against for linear
1208 # history, we save the rest to inject when we finalize the
1209 # svn commit
1210 my $fp_a = verify_ref("$c~1");
1211 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1212 if (!$fp_a || !$fp_b) {
1213 die "Commit $c\n",
1214 "has no parent commit, and therefore ",
1215 "nothing to diff against.\n",
1216 "You should be working from a repository ",
1217 "originally created by git-svn\n";
1219 if ($fp_a ne $fp_b) {
1220 die "$c~1 = $fp_a, however parsing commit $c ",
1221 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1224 foreach my $p (@{$parents{$c}}) {
1225 $skip{$p} = 1;
1228 (\@linear_refs, \%parents);
1231 sub find_file_type_and_diff_status {
1232 my ($path) = @_;
1233 return ('dir', '') if $path eq '';
1235 my $diff_output =
1236 command_oneline(qw(diff --cached --name-status --), $path) || "";
1237 my $diff_status = (split(' ', $diff_output))[0] || "";
1239 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1241 return (undef, undef) if !$diff_status && !$ls_tree;
1243 if ($diff_status eq "A") {
1244 return ("link", $diff_status) if -l $path;
1245 return ("dir", $diff_status) if -d $path;
1246 return ("file", $diff_status);
1249 my $mode = (split(' ', $ls_tree))[0] || "";
1251 return ("link", $diff_status) if $mode eq "120000";
1252 return ("dir", $diff_status) if $mode eq "040000";
1253 return ("file", $diff_status);
1256 sub md5sum {
1257 my $arg = shift;
1258 my $ref = ref $arg;
1259 my $md5 = Digest::MD5->new();
1260 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1261 $md5->addfile($arg) or croak $!;
1262 } elsif ($ref eq 'SCALAR') {
1263 $md5->add($$arg) or croak $!;
1264 } elsif (!$ref) {
1265 $md5->add($arg) or croak $!;
1266 } else {
1267 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1269 return $md5->hexdigest();
1272 package Git::SVN;
1273 use strict;
1274 use warnings;
1275 use Fcntl qw/:DEFAULT :seek/;
1276 use constant rev_map_fmt => 'NH40';
1277 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1278 $_repack $_repack_flags $_use_svm_props $_head
1279 $_use_svnsync_props $no_reuse_existing $_minimize_url
1280 $_use_log_author $_add_author_from/;
1281 use Carp qw/croak/;
1282 use File::Path qw/mkpath/;
1283 use File::Copy qw/copy/;
1284 use IPC::Open3;
1286 my ($_gc_nr, $_gc_period);
1288 # properties that we do not log:
1289 my %SKIP_PROP;
1290 BEGIN {
1291 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1292 svn:special svn:executable
1293 svn:entry:committed-rev
1294 svn:entry:last-author
1295 svn:entry:uuid
1296 svn:entry:committed-date/;
1298 # some options are read globally, but can be overridden locally
1299 # per [svn-remote "..."] section. Command-line options will *NOT*
1300 # override options set in an [svn-remote "..."] section
1301 no strict 'refs';
1302 for my $option (qw/follow_parent no_metadata use_svm_props
1303 use_svnsync_props/) {
1304 my $key = $option;
1305 $key =~ tr/_//d;
1306 my $prop = "-$option";
1307 *$option = sub {
1308 my ($self) = @_;
1309 return $self->{$prop} if exists $self->{$prop};
1310 my $k = "svn-remote.$self->{repo_id}.$key";
1311 eval { command_oneline(qw/config --get/, $k) };
1312 if ($@) {
1313 $self->{$prop} = ${"Git::SVN::_$option"};
1314 } else {
1315 my $v = command_oneline(qw/config --bool/,$k);
1316 $self->{$prop} = $v eq 'false' ? 0 : 1;
1318 return $self->{$prop};
1323 my (%LOCKFILES, %INDEX_FILES);
1324 END {
1325 unlink keys %LOCKFILES if %LOCKFILES;
1326 unlink keys %INDEX_FILES if %INDEX_FILES;
1329 sub resolve_local_globs {
1330 my ($url, $fetch, $glob_spec) = @_;
1331 return unless defined $glob_spec;
1332 my $ref = $glob_spec->{ref};
1333 my $path = $glob_spec->{path};
1334 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1335 next unless m#^refs/remotes/$ref->{regex}$#;
1336 my $p = $1;
1337 my $pathname = desanitize_refname($path->full_path($p));
1338 my $refname = desanitize_refname($ref->full_path($p));
1339 if (my $existing = $fetch->{$pathname}) {
1340 if ($existing ne $refname) {
1341 die "Refspec conflict:\n",
1342 "existing: refs/remotes/$existing\n",
1343 " globbed: refs/remotes/$refname\n";
1345 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1346 $u =~ s!^\Q$url\E(/|$)!! or die
1347 "refs/remotes/$refname: '$url' not found in '$u'\n";
1348 if ($pathname ne $u) {
1349 warn "W: Refspec glob conflict ",
1350 "(ref: refs/remotes/$refname):\n",
1351 "expected path: $pathname\n",
1352 " real path: $u\n",
1353 "Continuing ahead with $u\n";
1354 next;
1356 } else {
1357 $fetch->{$pathname} = $refname;
1362 sub parse_revision_argument {
1363 my ($base, $head) = @_;
1364 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1365 return ($base, $head);
1367 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1368 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1369 return ($head, $head) if ($::_revision eq 'HEAD');
1370 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1371 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1372 die "revision argument: $::_revision not understood by git-svn\n";
1375 sub fetch_all {
1376 my ($repo_id, $remotes) = @_;
1377 if (ref $repo_id) {
1378 my $gs = $repo_id;
1379 $repo_id = undef;
1380 $repo_id = $gs->{repo_id};
1382 $remotes ||= read_all_remotes();
1383 my $remote = $remotes->{$repo_id} or
1384 die "[svn-remote \"$repo_id\"] unknown\n";
1385 my $fetch = $remote->{fetch};
1386 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1387 my (@gs, @globs);
1388 my $ra = Git::SVN::Ra->new($url);
1389 my $uuid = $ra->get_uuid;
1390 my $head = $ra->get_latest_revnum;
1391 my $base = defined $fetch ? $head : 0;
1393 # read the max revs for wildcard expansion (branches/*, tags/*)
1394 foreach my $t (qw/branches tags/) {
1395 defined $remote->{$t} or next;
1396 push @globs, $remote->{$t};
1397 my $max_rev = eval { tmp_config(qw/--int --get/,
1398 "svn-remote.$repo_id.${t}-maxRev") };
1399 if (defined $max_rev && ($max_rev < $base)) {
1400 $base = $max_rev;
1401 } elsif (!defined $max_rev) {
1402 $base = 0;
1406 if ($fetch) {
1407 foreach my $p (sort keys %$fetch) {
1408 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1409 my $lr = $gs->rev_map_max;
1410 if (defined $lr) {
1411 $base = $lr if ($lr < $base);
1413 push @gs, $gs;
1417 ($base, $head) = parse_revision_argument($base, $head);
1418 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1421 sub read_all_remotes {
1422 my $r = {};
1423 my $use_svm_props = eval { command_oneline(qw/config --bool
1424 svn.useSvmProps/) };
1425 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1426 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1427 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1428 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1429 die("svn-remote.$remote: remote ref '$_remote_ref' "
1430 . "must start with 'refs/remotes/'\n")
1431 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1432 my $remote_ref = $1;
1433 $local_ref =~ s{^/}{};
1434 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1435 $r->{$remote}->{svm} = {} if $use_svm_props;
1436 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1437 $r->{$1}->{svm} = {};
1438 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1439 $r->{$1}->{url} = $2;
1440 } elsif (m!^(.+)\.(branches|tags)=
1441 (.*):refs/remotes/(.+)\s*$/!x) {
1442 my ($p, $g) = ($3, $4);
1443 my $rs = $r->{$1}->{$2} = {
1444 t => $2,
1445 remote => $1,
1446 path => Git::SVN::GlobSpec->new($p),
1447 ref => Git::SVN::GlobSpec->new($g) };
1448 if (length($rs->{ref}->{right}) != 0) {
1449 die "The '*' glob character must be the last ",
1450 "character of '$g'\n";
1455 map {
1456 if (defined $r->{$_}->{svm}) {
1457 my $svm;
1458 eval {
1459 my $section = "svn-remote.$_";
1460 $svm = {
1461 source => tmp_config('--get',
1462 "$section.svm-source"),
1463 replace => tmp_config('--get',
1464 "$section.svm-replace"),
1467 $r->{$_}->{svm} = $svm;
1469 } keys %$r;
1474 sub init_vars {
1475 $_gc_nr = $_gc_period = 1000;
1476 if (defined $_repack || defined $_repack_flags) {
1477 warn "Repack options are obsolete; they have no effect.\n";
1481 sub verify_remotes_sanity {
1482 return unless -d $ENV{GIT_DIR};
1483 my %seen;
1484 foreach (command(qw/config -l/)) {
1485 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1486 if ($seen{$1}) {
1487 die "Remote ref refs/remote/$1 is tracked by",
1488 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1489 "Please resolve this ambiguity in ",
1490 "your git configuration file before ",
1491 "continuing\n";
1493 $seen{$1} = $_;
1498 sub find_existing_remote {
1499 my ($url, $remotes) = @_;
1500 return undef if $no_reuse_existing;
1501 my $existing;
1502 foreach my $repo_id (keys %$remotes) {
1503 my $u = $remotes->{$repo_id}->{url} or next;
1504 next if $u ne $url;
1505 $existing = $repo_id;
1506 last;
1508 $existing;
1511 sub init_remote_config {
1512 my ($self, $url, $no_write) = @_;
1513 $url =~ s!/+$!!; # strip trailing slash
1514 my $r = read_all_remotes();
1515 my $existing = find_existing_remote($url, $r);
1516 if ($existing) {
1517 unless ($no_write) {
1518 print STDERR "Using existing ",
1519 "[svn-remote \"$existing\"]\n";
1521 $self->{repo_id} = $existing;
1522 } elsif ($_minimize_url) {
1523 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1524 $existing = find_existing_remote($min_url, $r);
1525 if ($existing) {
1526 unless ($no_write) {
1527 print STDERR "Using existing ",
1528 "[svn-remote \"$existing\"]\n";
1530 $self->{repo_id} = $existing;
1532 if ($min_url ne $url) {
1533 unless ($no_write) {
1534 print STDERR "Using higher level of URL: ",
1535 "$url => $min_url\n";
1537 my $old_path = $self->{path};
1538 $self->{path} = $url;
1539 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1540 if (length $old_path) {
1541 $self->{path} .= "/$old_path";
1543 $url = $min_url;
1546 my $orig_url;
1547 if (!$existing) {
1548 # verify that we aren't overwriting anything:
1549 $orig_url = eval {
1550 command_oneline('config', '--get',
1551 "svn-remote.$self->{repo_id}.url")
1553 if ($orig_url && ($orig_url ne $url)) {
1554 die "svn-remote.$self->{repo_id}.url already set: ",
1555 "$orig_url\nwanted to set to: $url\n";
1558 my ($xrepo_id, $xpath) = find_ref($self->refname);
1559 if (defined $xpath) {
1560 die "svn-remote.$xrepo_id.fetch already set to track ",
1561 "$xpath:refs/remotes/", $self->refname, "\n";
1563 unless ($no_write) {
1564 command_noisy('config',
1565 "svn-remote.$self->{repo_id}.url", $url);
1566 $self->{path} =~ s{^/}{};
1567 command_noisy('config', '--add',
1568 "svn-remote.$self->{repo_id}.fetch",
1569 "$self->{path}:".$self->refname);
1571 $self->{url} = $url;
1574 sub find_by_url { # repos_root and, path are optional
1575 my ($class, $full_url, $repos_root, $path) = @_;
1577 return undef unless defined $full_url;
1578 remove_username($full_url);
1579 remove_username($repos_root) if defined $repos_root;
1580 my $remotes = read_all_remotes();
1581 if (defined $full_url && defined $repos_root && !defined $path) {
1582 $path = $full_url;
1583 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1585 foreach my $repo_id (keys %$remotes) {
1586 my $u = $remotes->{$repo_id}->{url} or next;
1587 remove_username($u);
1588 next if defined $repos_root && $repos_root ne $u;
1590 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1591 foreach (qw/branches tags/) {
1592 resolve_local_globs($u, $fetch,
1593 $remotes->{$repo_id}->{$_});
1595 my $p = $path;
1596 my $rwr = rewrite_root({repo_id => $repo_id});
1597 my $svm = $remotes->{$repo_id}->{svm}
1598 if defined $remotes->{$repo_id}->{svm};
1599 unless (defined $p) {
1600 $p = $full_url;
1601 my $z = $u;
1602 my $prefix = '';
1603 if ($rwr) {
1604 $z = $rwr;
1605 } elsif (defined $svm) {
1606 $z = $svm->{source};
1607 $prefix = $svm->{replace};
1608 $prefix =~ s#^\Q$u\E(?:/|$)##;
1609 $prefix =~ s#/$##;
1611 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1613 foreach my $f (keys %$fetch) {
1614 next if $f ne $p;
1615 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1618 undef;
1621 sub init {
1622 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1623 my $self = _new($class, $repo_id, $ref_id, $path);
1624 if (defined $url) {
1625 $self->init_remote_config($url, $no_write);
1627 $self;
1630 sub find_ref {
1631 my ($ref_id) = @_;
1632 foreach (command(qw/config -l/)) {
1633 next unless m!^svn-remote\.(.+)\.fetch=
1634 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1635 my ($repo_id, $path, $ref) = ($1, $2, $3);
1636 if ($ref eq $ref_id) {
1637 $path = '' if ($path =~ m#^\./?#);
1638 return ($repo_id, $path);
1641 (undef, undef, undef);
1644 sub new {
1645 my ($class, $ref_id, $repo_id, $path) = @_;
1646 if (defined $ref_id && !defined $repo_id && !defined $path) {
1647 ($repo_id, $path) = find_ref($ref_id);
1648 if (!defined $repo_id) {
1649 die "Could not find a \"svn-remote.*.fetch\" key ",
1650 "in the repository configuration matching: ",
1651 "refs/remotes/$ref_id\n";
1654 my $self = _new($class, $repo_id, $ref_id, $path);
1655 if (!defined $self->{path} || !length $self->{path}) {
1656 my $fetch = command_oneline('config', '--get',
1657 "svn-remote.$repo_id.fetch",
1658 ":refs/remotes/$ref_id\$") or
1659 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1660 "\":refs/remotes/$ref_id\$\" in config\n";
1661 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1663 $self->{url} = command_oneline('config', '--get',
1664 "svn-remote.$repo_id.url") or
1665 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1666 $self->rebuild;
1667 $self;
1670 sub refname {
1671 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1673 # It cannot end with a slash /, we'll throw up on this because
1674 # SVN can't have directories with a slash in their name, either:
1675 if ($refname =~ m{/$}) {
1676 die "ref: '$refname' ends with a trailing slash, this is ",
1677 "not permitted by git nor Subversion\n";
1680 # It cannot have ASCII control character space, tilde ~, caret ^,
1681 # colon :, question-mark ?, asterisk *, space, or open bracket [
1682 # anywhere.
1684 # Additionally, % must be escaped because it is used for escaping
1685 # and we want our escaped refname to be reversible
1686 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1688 # no slash-separated component can begin with a dot .
1689 # /.* becomes /%2E*
1690 $refname =~ s{/\.}{/%2E}g;
1692 # It cannot have two consecutive dots .. anywhere
1693 # .. becomes %2E%2E
1694 $refname =~ s{\.\.}{%2E%2E}g;
1696 return $refname;
1699 sub desanitize_refname {
1700 my ($refname) = @_;
1701 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1702 return $refname;
1705 sub svm_uuid {
1706 my ($self) = @_;
1707 return $self->{svm}->{uuid} if $self->svm;
1708 $self->ra;
1709 unless ($self->{svm}) {
1710 die "SVM UUID not cached, and reading remotely failed\n";
1712 $self->{svm}->{uuid};
1715 sub svm {
1716 my ($self) = @_;
1717 return $self->{svm} if $self->{svm};
1718 my $svm;
1719 # see if we have it in our config, first:
1720 eval {
1721 my $section = "svn-remote.$self->{repo_id}";
1722 $svm = {
1723 source => tmp_config('--get', "$section.svm-source"),
1724 uuid => tmp_config('--get', "$section.svm-uuid"),
1725 replace => tmp_config('--get', "$section.svm-replace"),
1728 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1729 $self->{svm} = $svm;
1731 $self->{svm};
1734 sub _set_svm_vars {
1735 my ($self, $ra) = @_;
1736 return $ra if $self->svm;
1738 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1739 "(svm:source, svm:uuid) ",
1740 "from the following URLs:\n" );
1741 sub read_svm_props {
1742 my ($self, $ra, $path, $r) = @_;
1743 my $props = ($ra->get_dir($path, $r))[2];
1744 my $src = $props->{'svm:source'};
1745 my $uuid = $props->{'svm:uuid'};
1746 return undef if (!$src || !$uuid);
1748 chomp($src, $uuid);
1750 $uuid =~ m{^[0-9a-f\-]{30,}$}
1751 or die "doesn't look right - svm:uuid is '$uuid'\n";
1753 # the '!' is used to mark the repos_root!/relative/path
1754 $src =~ s{/?!/?}{/};
1755 $src =~ s{/+$}{}; # no trailing slashes please
1756 # username is of no interest
1757 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1759 my $replace = $ra->{url};
1760 $replace .= "/$path" if length $path;
1762 my $section = "svn-remote.$self->{repo_id}";
1763 tmp_config("$section.svm-source", $src);
1764 tmp_config("$section.svm-replace", $replace);
1765 tmp_config("$section.svm-uuid", $uuid);
1766 $self->{svm} = {
1767 source => $src,
1768 uuid => $uuid,
1769 replace => $replace
1773 my $r = $ra->get_latest_revnum;
1774 my $path = $self->{path};
1775 my %tried;
1776 while (length $path) {
1777 unless ($tried{"$self->{url}/$path"}) {
1778 return $ra if $self->read_svm_props($ra, $path, $r);
1779 $tried{"$self->{url}/$path"} = 1;
1781 $path =~ s#/?[^/]+$##;
1783 die "Path: '$path' should be ''\n" if $path ne '';
1784 return $ra if $self->read_svm_props($ra, $path, $r);
1785 $tried{"$self->{url}/$path"} = 1;
1787 if ($ra->{repos_root} eq $self->{url}) {
1788 die @err, (map { " $_\n" } keys %tried), "\n";
1791 # nope, make sure we're connected to the repository root:
1792 my $ok;
1793 my @tried_b;
1794 $path = $ra->{svn_path};
1795 $ra = Git::SVN::Ra->new($ra->{repos_root});
1796 while (length $path) {
1797 unless ($tried{"$ra->{url}/$path"}) {
1798 $ok = $self->read_svm_props($ra, $path, $r);
1799 last if $ok;
1800 $tried{"$ra->{url}/$path"} = 1;
1802 $path =~ s#/?[^/]+$##;
1804 die "Path: '$path' should be ''\n" if $path ne '';
1805 $ok ||= $self->read_svm_props($ra, $path, $r);
1806 $tried{"$ra->{url}/$path"} = 1;
1807 if (!$ok) {
1808 die @err, (map { " $_\n" } keys %tried), "\n";
1810 Git::SVN::Ra->new($self->{url});
1813 sub svnsync {
1814 my ($self) = @_;
1815 return $self->{svnsync} if $self->{svnsync};
1817 if ($self->no_metadata) {
1818 die "Can't have both 'noMetadata' and ",
1819 "'useSvnsyncProps' options set!\n";
1821 if ($self->rewrite_root) {
1822 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1823 "options set!\n";
1826 my $svnsync;
1827 # see if we have it in our config, first:
1828 eval {
1829 my $section = "svn-remote.$self->{repo_id}";
1831 my $url = tmp_config('--get', "$section.svnsync-url");
1832 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1833 die "doesn't look right - svn:sync-from-url is '$url'\n";
1835 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1836 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1837 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1839 $svnsync = { url => $url, uuid => $uuid }
1841 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1842 return $self->{svnsync} = $svnsync;
1845 my $err = "useSvnsyncProps set, but failed to read " .
1846 "svnsync property: svn:sync-from-";
1847 my $rp = $self->ra->rev_proplist(0);
1849 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1850 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1851 die "doesn't look right - svn:sync-from-url is '$url'\n";
1853 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1854 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1855 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1857 my $section = "svn-remote.$self->{repo_id}";
1858 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1859 tmp_config('--add', "$section.svnsync-url", $url);
1860 return $self->{svnsync} = { url => $url, uuid => $uuid };
1863 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1864 # remote lookup (useful for 'git svn log').
1865 sub ra_uuid {
1866 my ($self) = @_;
1867 unless ($self->{ra_uuid}) {
1868 my $key = "svn-remote.$self->{repo_id}.uuid";
1869 my $uuid = eval { tmp_config('--get', $key) };
1870 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1871 $self->{ra_uuid} = $uuid;
1872 } else {
1873 die "ra_uuid called without URL\n" unless $self->{url};
1874 $self->{ra_uuid} = $self->ra->get_uuid;
1875 tmp_config('--add', $key, $self->{ra_uuid});
1878 $self->{ra_uuid};
1881 sub _set_repos_root {
1882 my ($self, $repos_root) = @_;
1883 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1884 $repos_root ||= $self->ra->{repos_root};
1885 tmp_config($k, $repos_root);
1886 $repos_root;
1889 sub repos_root {
1890 my ($self) = @_;
1891 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1892 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1895 sub ra {
1896 my ($self) = shift;
1897 my $ra = Git::SVN::Ra->new($self->{url});
1898 $self->_set_repos_root($ra->{repos_root});
1899 if ($self->use_svm_props && !$self->{svm}) {
1900 if ($self->no_metadata) {
1901 die "Can't have both 'noMetadata' and ",
1902 "'useSvmProps' options set!\n";
1903 } elsif ($self->use_svnsync_props) {
1904 die "Can't have both 'useSvnsyncProps' and ",
1905 "'useSvmProps' options set!\n";
1907 $ra = $self->_set_svm_vars($ra);
1908 $self->{-want_revprops} = 1;
1910 $ra;
1913 sub rel_path {
1914 my ($self) = @_;
1915 my $repos_root = $self->ra->{repos_root};
1916 return $self->{path} if ($self->{url} eq $repos_root);
1917 my $url = $self->{url} .
1918 (length $self->{path} ? "/$self->{path}" : $self->{path});
1919 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1920 $url;
1923 # prop_walk(PATH, REV, SUB)
1924 # -------------------------
1925 # Recursively traverse PATH at revision REV and invoke SUB for each
1926 # directory that contains a SVN property. SUB will be invoked as
1927 # follows: &SUB(gs, path, props); where `gs' is this instance of
1928 # Git::SVN, `path' the path to the directory where the properties
1929 # `props' were found. The `path' will be relative to point of checkout,
1930 # that is, if url://repo/trunk is the current Git branch, and that
1931 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1932 # as `path' (note the trailing `/').
1933 sub prop_walk {
1934 my ($self, $path, $rev, $sub) = @_;
1936 $path =~ s#^/##;
1937 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1938 $path =~ s#^/*#/#g;
1939 my $p = $path;
1940 # Strip the irrelevant part of the path.
1941 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1942 # Ensure the path is terminated by a `/'.
1943 $p =~ s#/*$#/#;
1945 # The properties contain all the internal SVN stuff nobody
1946 # (usually) cares about.
1947 my $interesting_props = 0;
1948 foreach (keys %{$props}) {
1949 # If it doesn't start with `svn:', it must be a
1950 # user-defined property.
1951 ++$interesting_props and next if $_ !~ /^svn:/;
1952 # FIXME: Fragile, if SVN adds new public properties,
1953 # this needs to be updated.
1954 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1955 |eol-style|mime-type
1956 |externals|needs-lock)$/x;
1958 &$sub($self, $p, $props) if $interesting_props;
1960 foreach (sort keys %$dirent) {
1961 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1962 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1966 sub last_rev { ($_[0]->last_rev_commit)[0] }
1967 sub last_commit { ($_[0]->last_rev_commit)[1] }
1969 # returns the newest SVN revision number and newest commit SHA1
1970 sub last_rev_commit {
1971 my ($self) = @_;
1972 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1973 return ($self->{last_rev}, $self->{last_commit});
1975 my $c = ::verify_ref($self->refname.'^0');
1976 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1977 my $rev = (::cmt_metadata($c))[1];
1978 if (defined $rev) {
1979 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1980 return ($rev, $c);
1983 my $map_path = $self->map_path;
1984 unless (-e $map_path) {
1985 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1986 return (undef, undef);
1988 my ($rev, $commit) = $self->rev_map_max(1);
1989 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1990 return ($rev, $commit);
1993 sub get_fetch_range {
1994 my ($self, $min, $max) = @_;
1995 $max ||= $self->ra->get_latest_revnum;
1996 $min ||= $self->rev_map_max;
1997 (++$min, $max);
2000 sub tmp_config {
2001 my (@args) = @_;
2002 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2003 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2004 if (! -f $config && -f $old_def_config) {
2005 rename $old_def_config, $config or
2006 die "Failed rename $old_def_config => $config: $!\n";
2008 my $old_config = $ENV{GIT_CONFIG};
2009 $ENV{GIT_CONFIG} = $config;
2010 $@ = undef;
2011 my @ret = eval {
2012 unless (-f $config) {
2013 mkfile($config);
2014 open my $fh, '>', $config or
2015 die "Can't open $config: $!\n";
2016 print $fh "; This file is used internally by ",
2017 "git-svn\n" or die
2018 "Couldn't write to $config: $!\n";
2019 print $fh "; You should not have to edit it\n" or
2020 die "Couldn't write to $config: $!\n";
2021 close $fh or die "Couldn't close $config: $!\n";
2023 command('config', @args);
2025 my $err = $@;
2026 if (defined $old_config) {
2027 $ENV{GIT_CONFIG} = $old_config;
2028 } else {
2029 delete $ENV{GIT_CONFIG};
2031 die $err if $err;
2032 wantarray ? @ret : $ret[0];
2035 sub tmp_index_do {
2036 my ($self, $sub) = @_;
2037 my $old_index = $ENV{GIT_INDEX_FILE};
2038 $ENV{GIT_INDEX_FILE} = $self->{index};
2039 $@ = undef;
2040 my @ret = eval {
2041 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2042 mkpath([$dir]) unless -d $dir;
2043 &$sub;
2045 my $err = $@;
2046 if (defined $old_index) {
2047 $ENV{GIT_INDEX_FILE} = $old_index;
2048 } else {
2049 delete $ENV{GIT_INDEX_FILE};
2051 die $err if $err;
2052 wantarray ? @ret : $ret[0];
2055 sub assert_index_clean {
2056 my ($self, $treeish) = @_;
2058 $self->tmp_index_do(sub {
2059 command_noisy('read-tree', $treeish) unless -e $self->{index};
2060 my $x = command_oneline('write-tree');
2061 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2062 /^tree ($::sha1)/mo);
2063 return if $y eq $x;
2065 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2066 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2067 command_noisy('read-tree', $treeish);
2068 $x = command_oneline('write-tree');
2069 if ($y ne $x) {
2070 ::fatal "trees ($treeish) $y != $x\n",
2071 "Something is seriously wrong...";
2076 sub get_commit_parents {
2077 my ($self, $log_entry) = @_;
2078 my (%seen, @ret, @tmp);
2079 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2080 if (my $ip = $self->{inject_parents}) {
2081 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2082 push @tmp, $commit;
2085 if (my $cur = ::verify_ref($self->refname.'^0')) {
2086 push @tmp, $cur;
2088 if (my $ipd = $self->{inject_parents_dcommit}) {
2089 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2090 push @tmp, @$commit;
2093 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2094 while (my $p = shift @tmp) {
2095 next if $seen{$p};
2096 $seen{$p} = 1;
2097 push @ret, $p;
2098 # MAXPARENT is defined to 16 in commit-tree.c:
2099 last if @ret >= 16;
2101 if (@tmp) {
2102 die "r$log_entry->{revision}: No room for parents:\n\t",
2103 join("\n\t", @tmp), "\n";
2105 @ret;
2108 sub rewrite_root {
2109 my ($self) = @_;
2110 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2111 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2112 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2113 if ($rwr) {
2114 $rwr =~ s#/+$##;
2115 if ($rwr !~ m#^[a-z\+]+://#) {
2116 die "$rwr is not a valid URL (key: $k)\n";
2119 $self->{-rewrite_root} = $rwr;
2122 sub metadata_url {
2123 my ($self) = @_;
2124 ($self->rewrite_root || $self->{url}) .
2125 (length $self->{path} ? '/' . $self->{path} : '');
2128 sub full_url {
2129 my ($self) = @_;
2130 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2134 sub set_commit_header_env {
2135 my ($log_entry) = @_;
2136 my %env;
2137 foreach my $ned (qw/NAME EMAIL DATE/) {
2138 foreach my $ac (qw/AUTHOR COMMITTER/) {
2139 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2143 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2144 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2145 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2147 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2148 ? $log_entry->{commit_name}
2149 : $log_entry->{name};
2150 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2151 ? $log_entry->{commit_email}
2152 : $log_entry->{email};
2153 \%env;
2156 sub restore_commit_header_env {
2157 my ($env) = @_;
2158 foreach my $ned (qw/NAME EMAIL DATE/) {
2159 foreach my $ac (qw/AUTHOR COMMITTER/) {
2160 my $k = "GIT_${ac}_${ned}";
2161 if (defined $env->{$k}) {
2162 $ENV{$k} = $env->{$k};
2163 } else {
2164 delete $ENV{$k};
2170 sub gc {
2171 command_noisy('gc', '--auto');
2174 sub do_git_commit {
2175 my ($self, $log_entry) = @_;
2176 my $lr = $self->last_rev;
2177 if (defined $lr && $lr >= $log_entry->{revision}) {
2178 die "Last fetched revision of ", $self->refname,
2179 " was r$lr, but we are about to fetch: ",
2180 "r$log_entry->{revision}!\n";
2182 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2183 croak "$log_entry->{revision} = $c already exists! ",
2184 "Why are we refetching it?\n";
2186 my $old_env = set_commit_header_env($log_entry);
2187 my $tree = $log_entry->{tree};
2188 if (!defined $tree) {
2189 $tree = $self->tmp_index_do(sub {
2190 command_oneline('write-tree') });
2192 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2194 my @exec = ('git-commit-tree', $tree);
2195 foreach ($self->get_commit_parents($log_entry)) {
2196 push @exec, '-p', $_;
2198 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2199 or croak $!;
2200 print $msg_fh $log_entry->{log} or croak $!;
2201 restore_commit_header_env($old_env);
2202 unless ($self->no_metadata) {
2203 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2204 or croak $!;
2206 $msg_fh->flush == 0 or croak $!;
2207 close $msg_fh or croak $!;
2208 chomp(my $commit = do { local $/; <$out_fh> });
2209 close $out_fh or croak $!;
2210 waitpid $pid, 0;
2211 croak $? if $?;
2212 if ($commit !~ /^$::sha1$/o) {
2213 die "Failed to commit, invalid sha1: $commit\n";
2216 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2218 $self->{last_rev} = $log_entry->{revision};
2219 $self->{last_commit} = $commit;
2220 print "r$log_entry->{revision}";
2221 if (defined $log_entry->{svm_revision}) {
2222 print " (\@$log_entry->{svm_revision})";
2223 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2224 0, $self->svm_uuid);
2226 print " = $commit ($self->{ref_id})\n";
2227 if (--$_gc_nr == 0) {
2228 $_gc_nr = $_gc_period;
2229 gc();
2231 return $commit;
2234 sub match_paths {
2235 my ($self, $paths, $r) = @_;
2236 return 1 if $self->{path} eq '';
2237 if (my $path = $paths->{"/$self->{path}"}) {
2238 return ($path->{action} eq 'D') ? 0 : 1;
2240 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2241 if (grep /$self->{path_regex}/, keys %$paths) {
2242 return 1;
2244 my $c = '';
2245 foreach (split m#/#, $self->{path}) {
2246 $c .= "/$_";
2247 next unless ($paths->{$c} &&
2248 ($paths->{$c}->{action} =~ /^[AR]$/));
2249 if ($self->ra->check_path($self->{path}, $r) ==
2250 $SVN::Node::dir) {
2251 return 1;
2254 return 0;
2257 sub find_parent_branch {
2258 my ($self, $paths, $rev) = @_;
2259 return undef unless $self->follow_parent;
2260 unless (defined $paths) {
2261 my $err_handler = $SVN::Error::handler;
2262 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2263 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2264 $paths =
2265 Git::SVN::Ra::dup_changed_paths($_[0]) });
2266 $SVN::Error::handler = $err_handler;
2268 return undef unless defined $paths;
2270 # look for a parent from another branch:
2271 my @b_path_components = split m#/#, $self->rel_path;
2272 my @a_path_components;
2273 my $i;
2274 while (@b_path_components) {
2275 $i = $paths->{'/'.join('/', @b_path_components)};
2276 last if $i && defined $i->{copyfrom_path};
2277 unshift(@a_path_components, pop(@b_path_components));
2279 return undef unless defined $i && defined $i->{copyfrom_path};
2280 my $branch_from = $i->{copyfrom_path};
2281 if (@a_path_components) {
2282 print STDERR "branch_from: $branch_from => ";
2283 $branch_from .= '/'.join('/', @a_path_components);
2284 print STDERR $branch_from, "\n";
2286 my $r = $i->{copyfrom_rev};
2287 my $repos_root = $self->ra->{repos_root};
2288 my $url = $self->ra->{url};
2289 my $new_url = $repos_root . $branch_from;
2290 print STDERR "Found possible branch point: ",
2291 "$new_url => ", $self->full_url, ", $r\n";
2292 $branch_from =~ s#^/##;
2293 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2294 unless ($gs) {
2295 my $ref_id = $self->{ref_id};
2296 $ref_id =~ s/\@\d+$//;
2297 $ref_id .= "\@$r";
2298 # just grow a tail if we're not unique enough :x
2299 $ref_id .= '-' while find_ref($ref_id);
2300 print STDERR "Initializing parent: $ref_id\n";
2301 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2302 if ($u =~ s#^\Q$url\E(/|$)##) {
2303 $p = $u;
2304 $u = $url;
2305 $repo_id = $self->{repo_id};
2307 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2309 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2310 if (!defined $r0 || !defined $parent) {
2311 my ($base, $head) = parse_revision_argument(0, $r);
2312 if ($base <= $r) {
2313 $gs->fetch($base, $r);
2315 ($r0, $parent) = $gs->last_rev_commit;
2317 if (defined $r0 && defined $parent) {
2318 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2319 my $ed;
2320 if ($self->ra->can_do_switch) {
2321 $self->assert_index_clean($parent);
2322 print STDERR "Following parent with do_switch\n";
2323 # do_switch works with svn/trunk >= r22312, but that
2324 # is not included with SVN 1.4.3 (the latest version
2325 # at the moment), so we can't rely on it
2326 $self->{last_commit} = $parent;
2327 $ed = SVN::Git::Fetcher->new($self);
2328 $gs->ra->gs_do_switch($r0, $rev, $gs,
2329 $self->full_url, $ed)
2330 or die "SVN connection failed somewhere...\n";
2331 } elsif ($self->ra->trees_match($new_url, $r0,
2332 $self->full_url, $rev)) {
2333 print STDERR "Trees match:\n",
2334 " $new_url\@$r0\n",
2335 " ${\$self->full_url}\@$rev\n",
2336 "Following parent with no changes\n";
2337 $self->tmp_index_do(sub {
2338 command_noisy('read-tree', $parent);
2340 $self->{last_commit} = $parent;
2341 } else {
2342 print STDERR "Following parent with do_update\n";
2343 $ed = SVN::Git::Fetcher->new($self);
2344 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2345 or die "SVN connection failed somewhere...\n";
2347 print STDERR "Successfully followed parent\n";
2348 return $self->make_log_entry($rev, [$parent], $ed);
2350 return undef;
2353 sub do_fetch {
2354 my ($self, $paths, $rev) = @_;
2355 my $ed;
2356 my ($last_rev, @parents);
2357 if (my $lc = $self->last_commit) {
2358 # we can have a branch that was deleted, then re-added
2359 # under the same name but copied from another path, in
2360 # which case we'll have multiple parents (we don't
2361 # want to break the original ref, nor lose copypath info):
2362 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2363 push @{$log_entry->{parents}}, $lc;
2364 return $log_entry;
2366 $ed = SVN::Git::Fetcher->new($self);
2367 $last_rev = $self->{last_rev};
2368 $ed->{c} = $lc;
2369 @parents = ($lc);
2370 } else {
2371 $last_rev = $rev;
2372 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2373 return $log_entry;
2375 $ed = SVN::Git::Fetcher->new($self);
2377 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2378 die "SVN connection failed somewhere...\n";
2380 $self->make_log_entry($rev, \@parents, $ed);
2383 sub get_untracked {
2384 my ($self, $ed) = @_;
2385 my @out;
2386 my $h = $ed->{empty};
2387 foreach (sort keys %$h) {
2388 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2389 push @out, " $act: " . uri_encode($_);
2390 warn "W: $act: $_\n";
2392 foreach my $t (qw/dir_prop file_prop/) {
2393 $h = $ed->{$t} or next;
2394 foreach my $path (sort keys %$h) {
2395 my $ppath = $path eq '' ? '.' : $path;
2396 foreach my $prop (sort keys %{$h->{$path}}) {
2397 next if $SKIP_PROP{$prop};
2398 my $v = $h->{$path}->{$prop};
2399 my $t_ppath_prop = "$t: " .
2400 uri_encode($ppath) . ' ' .
2401 uri_encode($prop);
2402 if (defined $v) {
2403 push @out, " +$t_ppath_prop " .
2404 uri_encode($v);
2405 } else {
2406 push @out, " -$t_ppath_prop";
2411 foreach my $t (qw/absent_file absent_directory/) {
2412 $h = $ed->{$t} or next;
2413 foreach my $parent (sort keys %$h) {
2414 foreach my $path (sort @{$h->{$parent}}) {
2415 push @out, " $t: " .
2416 uri_encode("$parent/$path");
2417 warn "W: $t: $parent/$path ",
2418 "Insufficient permissions?\n";
2422 \@out;
2425 sub parse_svn_date {
2426 my $date = shift || return '+0000 1970-01-01 00:00:00';
2427 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2428 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2429 croak "Unable to parse date: $date\n";
2430 "+0000 $Y-$m-$d $H:$M:$S";
2433 sub check_author {
2434 my ($author) = @_;
2435 if (!defined $author || length $author == 0) {
2436 $author = '(no author)';
2437 } elsif (defined $::_authors && ! defined $::users{$author}) {
2438 die "Author: $author not defined in $::_authors file\n";
2440 $author;
2443 sub make_log_entry {
2444 my ($self, $rev, $parents, $ed) = @_;
2445 my $untracked = $self->get_untracked($ed);
2447 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2448 print $un "r$rev\n" or croak $!;
2449 print $un $_, "\n" foreach @$untracked;
2450 my %log_entry = ( parents => $parents || [], revision => $rev,
2451 log => '');
2453 my $headrev;
2454 my $logged = delete $self->{logged_rev_props};
2455 if (!$logged || $self->{-want_revprops}) {
2456 my $rp = $self->ra->rev_proplist($rev);
2457 foreach (sort keys %$rp) {
2458 my $v = $rp->{$_};
2459 if (/^svn:(author|date|log)$/) {
2460 $log_entry{$1} = $v;
2461 } elsif ($_ eq 'svm:headrev') {
2462 $headrev = $v;
2463 } else {
2464 print $un " rev_prop: ", uri_encode($_), ' ',
2465 uri_encode($v), "\n";
2468 } else {
2469 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2471 close $un or croak $!;
2473 $log_entry{date} = parse_svn_date($log_entry{date});
2474 $log_entry{log} .= "\n";
2475 my $author = $log_entry{author} = check_author($log_entry{author});
2476 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2477 : ($author, undef);
2479 my ($commit_name, $commit_email) = ($name, $email);
2480 if ($_use_log_author) {
2481 my $name_field;
2482 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2483 $name_field = $1;
2484 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2485 $name_field = $1;
2487 if (!defined $name_field) {
2488 if (!defined $email) {
2489 $email = $name;
2491 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2492 ($name, $email) = ($1, $2);
2493 } elsif ($name_field =~ /(.*)@/) {
2494 ($name, $email) = ($1, $name_field);
2495 } else {
2496 ($name, $email) = ($name_field, $name_field);
2499 if (defined $headrev && $self->use_svm_props) {
2500 if ($self->rewrite_root) {
2501 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2502 "options set!\n";
2504 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2505 # we don't want "SVM: initializing mirror for junk" ...
2506 return undef if $r == 0;
2507 my $svm = $self->svm;
2508 if ($uuid ne $svm->{uuid}) {
2509 die "UUID mismatch on SVM path:\n",
2510 "expected: $svm->{uuid}\n",
2511 " got: $uuid\n";
2513 my $full_url = $self->full_url;
2514 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2515 die "Failed to replace '$svm->{replace}' with ",
2516 "'$svm->{source}' in $full_url\n";
2517 # throw away username for storing in records
2518 remove_username($full_url);
2519 $log_entry{metadata} = "$full_url\@$r $uuid";
2520 $log_entry{svm_revision} = $r;
2521 $email ||= "$author\@$uuid";
2522 $commit_email ||= "$author\@$uuid";
2523 } elsif ($self->use_svnsync_props) {
2524 my $full_url = $self->svnsync->{url};
2525 $full_url .= "/$self->{path}" if length $self->{path};
2526 remove_username($full_url);
2527 my $uuid = $self->svnsync->{uuid};
2528 $log_entry{metadata} = "$full_url\@$rev $uuid";
2529 $email ||= "$author\@$uuid";
2530 $commit_email ||= "$author\@$uuid";
2531 } else {
2532 my $url = $self->metadata_url;
2533 remove_username($url);
2534 $log_entry{metadata} = "$url\@$rev " .
2535 $self->ra->get_uuid;
2536 $email ||= "$author\@" . $self->ra->get_uuid;
2537 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2539 $log_entry{name} = $name;
2540 $log_entry{email} = $email;
2541 $log_entry{commit_name} = $commit_name;
2542 $log_entry{commit_email} = $commit_email;
2543 \%log_entry;
2546 sub fetch {
2547 my ($self, $min_rev, $max_rev, @parents) = @_;
2548 my ($last_rev, $last_commit) = $self->last_rev_commit;
2549 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2550 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2553 sub set_tree_cb {
2554 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2555 $self->{inject_parents} = { $rev => $tree };
2556 $self->fetch(undef, undef);
2559 sub set_tree {
2560 my ($self, $tree) = (shift, shift);
2561 my $log_entry = ::get_commit_entry($tree);
2562 unless ($self->{last_rev}) {
2563 fatal("Must have an existing revision to commit");
2565 my %ed_opts = ( r => $self->{last_rev},
2566 log => $log_entry->{log},
2567 ra => $self->ra,
2568 tree_a => $self->{last_commit},
2569 tree_b => $tree,
2570 editor_cb => sub {
2571 $self->set_tree_cb($log_entry, $tree, @_) },
2572 svn_path => $self->{path} );
2573 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2574 print "No changes\nr$self->{last_rev} = $tree\n";
2578 sub rebuild_from_rev_db {
2579 my ($self, $path) = @_;
2580 my $r = -1;
2581 open my $fh, '<', $path or croak "open: $!";
2582 binmode $fh or croak "binmode: $!";
2583 while (<$fh>) {
2584 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2585 chomp($_);
2586 ++$r;
2587 next if $_ eq ('0' x 40);
2588 $self->rev_map_set($r, $_);
2589 print "r$r = $_\n";
2591 close $fh or croak "close: $!";
2592 unlink $path or croak "unlink: $!";
2595 sub rebuild {
2596 my ($self) = @_;
2597 my $map_path = $self->map_path;
2598 return if (-e $map_path && ! -z $map_path);
2599 return unless ::verify_ref($self->refname.'^0');
2600 if ($self->use_svm_props || $self->no_metadata) {
2601 my $rev_db = $self->rev_db_path;
2602 $self->rebuild_from_rev_db($rev_db);
2603 if ($self->use_svm_props) {
2604 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2605 $self->rebuild_from_rev_db($svm_rev_db);
2607 $self->unlink_rev_db_symlink;
2608 return;
2610 print "Rebuilding $map_path ...\n";
2611 my ($log, $ctx) =
2612 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2613 $self->refname, '--');
2614 my $metadata_url = $self->metadata_url;
2615 remove_username($metadata_url);
2616 my $svn_uuid = $self->ra_uuid;
2617 my $c;
2618 while (<$log>) {
2619 if ( m{^commit ($::sha1)$} ) {
2620 $c = $1;
2621 next;
2623 next unless s{^\s*(git-svn-id:)}{$1};
2624 my ($url, $rev, $uuid) = ::extract_metadata($_);
2625 remove_username($url);
2627 # ignore merges (from set-tree)
2628 next if (!defined $rev || !$uuid);
2630 # if we merged or otherwise started elsewhere, this is
2631 # how we break out of it
2632 if (($uuid ne $svn_uuid) ||
2633 ($metadata_url && $url && ($url ne $metadata_url))) {
2634 next;
2637 $self->rev_map_set($rev, $c);
2638 print "r$rev = $c\n";
2640 command_close_pipe($log, $ctx);
2641 print "Done rebuilding $map_path\n";
2642 my $rev_db_path = $self->rev_db_path;
2643 if (-f $self->rev_db_path) {
2644 unlink $self->rev_db_path or croak "unlink: $!";
2646 $self->unlink_rev_db_symlink;
2649 # rev_map:
2650 # Tie::File seems to be prone to offset errors if revisions get sparse,
2651 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2652 # one of my favorite modules is out :< Next up would be one of the DBM
2653 # modules, but I'm not sure which is most portable...
2655 # This is the replacement for the rev_db format, which was too big
2656 # and inefficient for large repositories with a lot of sparse history
2657 # (mainly tags)
2659 # The format is this:
2660 # - 24 bytes for every record,
2661 # * 4 bytes for the integer representing an SVN revision number
2662 # * 20 bytes representing the sha1 of a git commit
2663 # - No empty padding records like the old format
2664 # (except the last record, which can be overwritten)
2665 # - new records are written append-only since SVN revision numbers
2666 # increase monotonically
2667 # - lookups on SVN revision number are done via a binary search
2668 # - Piping the file to xxd -c24 is a good way of dumping it for
2669 # viewing or editing (piped back through xxd -r), should the need
2670 # ever arise.
2671 # - The last record can be padding revision with an all-zero sha1
2672 # This is used to optimize fetch performance when using multiple
2673 # "fetch" directives in .git/config
2675 # These files are disposable unless noMetadata or useSvmProps is set
2677 sub _rev_map_set {
2678 my ($fh, $rev, $commit) = @_;
2680 binmode $fh or croak "binmode: $!";
2681 my $size = (stat($fh))[7];
2682 ($size % 24) == 0 or croak "inconsistent size: $size";
2684 my $wr_offset = 0;
2685 if ($size > 0) {
2686 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2687 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2688 $read == 24 or croak "read only $read bytes (!= 24)";
2689 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2690 if ($last_commit eq ('0' x40)) {
2691 if ($size >= 48) {
2692 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2693 $read = sysread($fh, $buf, 24) or
2694 croak "read: $!";
2695 $read == 24 or
2696 croak "read only $read bytes (!= 24)";
2697 ($last_rev, $last_commit) =
2698 unpack(rev_map_fmt, $buf);
2699 if ($last_commit eq ('0' x40)) {
2700 croak "inconsistent .rev_map\n";
2703 if ($last_rev >= $rev) {
2704 croak "last_rev is higher!: $last_rev >= $rev";
2706 $wr_offset = -24;
2709 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2710 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2711 croak "write: $!";
2714 sub mkfile {
2715 my ($path) = @_;
2716 unless (-e $path) {
2717 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2718 mkpath([$dir]) unless -d $dir;
2719 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2720 close $fh or die "Couldn't close (create) $path: $!\n";
2724 sub rev_map_set {
2725 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2726 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2727 my $db = $self->map_path($uuid);
2728 my $db_lock = "$db.lock";
2729 my $sig;
2730 if ($update_ref) {
2731 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2732 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2734 mkfile($db);
2736 $LOCKFILES{$db_lock} = 1;
2737 my $sync;
2738 # both of these options make our .rev_db file very, very important
2739 # and we can't afford to lose it because rebuild() won't work
2740 if ($self->use_svm_props || $self->no_metadata) {
2741 $sync = 1;
2742 copy($db, $db_lock) or die "rev_map_set(@_): ",
2743 "Failed to copy: ",
2744 "$db => $db_lock ($!)\n";
2745 } else {
2746 rename $db, $db_lock or die "rev_map_set(@_): ",
2747 "Failed to rename: ",
2748 "$db => $db_lock ($!)\n";
2751 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2752 or croak "Couldn't open $db_lock: $!\n";
2753 _rev_map_set($fh, $rev, $commit);
2754 if ($sync) {
2755 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2756 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2758 close $fh or croak $!;
2759 if ($update_ref) {
2760 $_head = $self;
2761 command_noisy('update-ref', '-m', "r$rev",
2762 $self->refname, $commit);
2764 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2765 "$db_lock => $db ($!)\n";
2766 delete $LOCKFILES{$db_lock};
2767 if ($update_ref) {
2768 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2769 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2770 kill $sig, $$ if defined $sig;
2774 # If want_commit, this will return an array of (rev, commit) where
2775 # commit _must_ be a valid commit in the archive.
2776 # Otherwise, it'll return the max revision (whether or not the
2777 # commit is valid or just a 0x40 placeholder).
2778 sub rev_map_max {
2779 my ($self, $want_commit) = @_;
2780 $self->rebuild;
2781 my $map_path = $self->map_path;
2782 stat $map_path or return $want_commit ? (0, undef) : 0;
2783 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2784 binmode $fh or croak "binmode: $!";
2785 my $size = (stat($fh))[7];
2786 ($size % 24) == 0 or croak "inconsistent size: $size";
2788 if ($size == 0) {
2789 close $fh or croak "close: $!";
2790 return $want_commit ? (0, undef) : 0;
2793 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2794 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2795 my ($r, $c) = unpack(rev_map_fmt, $buf);
2796 if ($want_commit && $c eq ('0' x40)) {
2797 if ($size < 48) {
2798 return $want_commit ? (0, undef) : 0;
2800 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2801 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2802 ($r, $c) = unpack(rev_map_fmt, $buf);
2803 if ($c eq ('0'x40)) {
2804 croak "Penultimate record is all-zeroes in $map_path";
2807 close $fh or croak "close: $!";
2808 $want_commit ? ($r, $c) : $r;
2811 sub rev_map_get {
2812 my ($self, $rev, $uuid) = @_;
2813 my $map_path = $self->map_path($uuid);
2814 return undef unless -e $map_path;
2816 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2817 binmode $fh or croak "binmode: $!";
2818 my $size = (stat($fh))[7];
2819 ($size % 24) == 0 or croak "inconsistent size: $size";
2821 if ($size == 0) {
2822 close $fh or croak "close: $fh";
2823 return undef;
2826 my ($l, $u) = (0, $size - 24);
2827 my ($r, $c, $buf);
2829 while ($l <= $u) {
2830 my $i = int(($l/24 + $u/24) / 2) * 24;
2831 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2832 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2833 my ($r, $c) = unpack('NH40', $buf);
2835 if ($r < $rev) {
2836 $l = $i + 24;
2837 } elsif ($r > $rev) {
2838 $u = $i - 24;
2839 } else { # $r == $rev
2840 close($fh) or croak "close: $!";
2841 return $c eq ('0' x 40) ? undef : $c;
2844 close($fh) or croak "close: $!";
2845 undef;
2848 # Finds the first svn revision that exists on (if $eq_ok is true) or
2849 # before $rev for the current branch. It will not search any lower
2850 # than $min_rev. Returns the git commit hash and svn revision number
2851 # if found, else (undef, undef).
2852 sub find_rev_before {
2853 my ($self, $rev, $eq_ok, $min_rev) = @_;
2854 --$rev unless $eq_ok;
2855 $min_rev ||= 1;
2856 while ($rev >= $min_rev) {
2857 if (my $c = $self->rev_map_get($rev)) {
2858 return ($rev, $c);
2860 --$rev;
2862 return (undef, undef);
2865 # Finds the first svn revision that exists on (if $eq_ok is true) or
2866 # after $rev for the current branch. It will not search any higher
2867 # than $max_rev. Returns the git commit hash and svn revision number
2868 # if found, else (undef, undef).
2869 sub find_rev_after {
2870 my ($self, $rev, $eq_ok, $max_rev) = @_;
2871 ++$rev unless $eq_ok;
2872 $max_rev ||= $self->rev_map_max;
2873 while ($rev <= $max_rev) {
2874 if (my $c = $self->rev_map_get($rev)) {
2875 return ($rev, $c);
2877 ++$rev;
2879 return (undef, undef);
2882 sub _new {
2883 my ($class, $repo_id, $ref_id, $path) = @_;
2884 unless (defined $repo_id && length $repo_id) {
2885 $repo_id = $Git::SVN::default_repo_id;
2887 unless (defined $ref_id && length $ref_id) {
2888 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2890 $_[1] = $repo_id;
2891 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2892 $_[3] = $path = '' unless (defined $path);
2893 mkpath(["$ENV{GIT_DIR}/svn"]);
2894 bless {
2895 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2896 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2897 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2900 # for read-only access of old .rev_db formats
2901 sub unlink_rev_db_symlink {
2902 my ($self) = @_;
2903 my $link = $self->rev_db_path;
2904 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2905 if (-l $link) {
2906 unlink $link or croak "unlink: $link failed!";
2910 sub rev_db_path {
2911 my ($self, $uuid) = @_;
2912 my $db_path = $self->map_path($uuid);
2913 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2914 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2915 $db_path;
2918 # the new replacement for .rev_db
2919 sub map_path {
2920 my ($self, $uuid) = @_;
2921 $uuid ||= $self->ra_uuid;
2922 "$self->{map_root}.$uuid";
2925 sub uri_encode {
2926 my ($f) = @_;
2927 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2931 sub remove_username {
2932 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2935 package Git::SVN::Prompt;
2936 use strict;
2937 use warnings;
2938 require SVN::Core;
2939 use vars qw/$_no_auth_cache $_username/;
2941 sub simple {
2942 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2943 $may_save = undef if $_no_auth_cache;
2944 $default_username = $_username if defined $_username;
2945 if (defined $default_username && length $default_username) {
2946 if (defined $realm && length $realm) {
2947 print STDERR "Authentication realm: $realm\n";
2948 STDERR->flush;
2950 $cred->username($default_username);
2951 } else {
2952 username($cred, $realm, $may_save, $pool);
2954 $cred->password(_read_password("Password for '" .
2955 $cred->username . "': ", $realm));
2956 $cred->may_save($may_save);
2957 $SVN::_Core::SVN_NO_ERROR;
2960 sub ssl_server_trust {
2961 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2962 $may_save = undef if $_no_auth_cache;
2963 print STDERR "Error validating server certificate for '$realm':\n";
2965 no warnings 'once';
2966 # All variables SVN::Auth::SSL::* are used only once,
2967 # so we're shutting up Perl warnings about this.
2968 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2969 print STDERR " - The certificate is not issued ",
2970 "by a trusted authority. Use the\n",
2971 " fingerprint to validate ",
2972 "the certificate manually!\n";
2974 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2975 print STDERR " - The certificate hostname ",
2976 "does not match.\n";
2978 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2979 print STDERR " - The certificate is not yet valid.\n";
2981 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2982 print STDERR " - The certificate has expired.\n";
2984 if ($failures & $SVN::Auth::SSL::OTHER) {
2985 print STDERR " - The certificate has ",
2986 "an unknown error.\n";
2988 } # no warnings 'once'
2989 printf STDERR
2990 "Certificate information:\n".
2991 " - Hostname: %s\n".
2992 " - Valid: from %s until %s\n".
2993 " - Issuer: %s\n".
2994 " - Fingerprint: %s\n",
2995 map $cert_info->$_, qw(hostname valid_from valid_until
2996 issuer_dname fingerprint);
2997 my $choice;
2998 prompt:
2999 print STDERR $may_save ?
3000 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3001 "(R)eject or accept (t)emporarily? ";
3002 STDERR->flush;
3003 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3004 if ($choice =~ /^t$/i) {
3005 $cred->may_save(undef);
3006 } elsif ($choice =~ /^r$/i) {
3007 return -1;
3008 } elsif ($may_save && $choice =~ /^p$/i) {
3009 $cred->may_save($may_save);
3010 } else {
3011 goto prompt;
3013 $cred->accepted_failures($failures);
3014 $SVN::_Core::SVN_NO_ERROR;
3017 sub ssl_client_cert {
3018 my ($cred, $realm, $may_save, $pool) = @_;
3019 $may_save = undef if $_no_auth_cache;
3020 print STDERR "Client certificate filename: ";
3021 STDERR->flush;
3022 chomp(my $filename = <STDIN>);
3023 $cred->cert_file($filename);
3024 $cred->may_save($may_save);
3025 $SVN::_Core::SVN_NO_ERROR;
3028 sub ssl_client_cert_pw {
3029 my ($cred, $realm, $may_save, $pool) = @_;
3030 $may_save = undef if $_no_auth_cache;
3031 $cred->password(_read_password("Password: ", $realm));
3032 $cred->may_save($may_save);
3033 $SVN::_Core::SVN_NO_ERROR;
3036 sub username {
3037 my ($cred, $realm, $may_save, $pool) = @_;
3038 $may_save = undef if $_no_auth_cache;
3039 if (defined $realm && length $realm) {
3040 print STDERR "Authentication realm: $realm\n";
3042 my $username;
3043 if (defined $_username) {
3044 $username = $_username;
3045 } else {
3046 print STDERR "Username: ";
3047 STDERR->flush;
3048 chomp($username = <STDIN>);
3050 $cred->username($username);
3051 $cred->may_save($may_save);
3052 $SVN::_Core::SVN_NO_ERROR;
3055 sub _read_password {
3056 my ($prompt, $realm) = @_;
3057 print STDERR $prompt;
3058 STDERR->flush;
3059 require Term::ReadKey;
3060 Term::ReadKey::ReadMode('noecho');
3061 my $password = '';
3062 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3063 last if $key =~ /[\012\015]/; # \n\r
3064 $password .= $key;
3066 Term::ReadKey::ReadMode('restore');
3067 print STDERR "\n";
3068 STDERR->flush;
3069 $password;
3072 package SVN::Git::Fetcher;
3073 use vars qw/@ISA/;
3074 use strict;
3075 use warnings;
3076 use Carp qw/croak/;
3077 use File::Temp qw/tempfile/;
3078 use IO::File qw//;
3080 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3081 sub new {
3082 my ($class, $git_svn) = @_;
3083 my $self = SVN::Delta::Editor->new;
3084 bless $self, $class;
3085 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3086 $self->{empty} = {};
3087 $self->{dir_prop} = {};
3088 $self->{file_prop} = {};
3089 $self->{absent_dir} = {};
3090 $self->{absent_file} = {};
3091 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3092 $self;
3095 sub set_path_strip {
3096 my ($self, $path) = @_;
3097 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3100 sub open_root {
3101 { path => '' };
3104 sub open_directory {
3105 my ($self, $path, $pb, $rev) = @_;
3106 { path => $path };
3109 sub git_path {
3110 my ($self, $path) = @_;
3111 if ($self->{path_strip}) {
3112 $path =~ s!$self->{path_strip}!! or
3113 die "Failed to strip path '$path' ($self->{path_strip})\n";
3115 $path;
3118 sub delete_entry {
3119 my ($self, $path, $rev, $pb) = @_;
3121 my $gpath = $self->git_path($path);
3122 return undef if ($gpath eq '');
3124 # remove entire directories.
3125 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3126 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3127 -r --name-only -z/,
3128 $self->{c}, '--', $gpath);
3129 local $/ = "\0";
3130 while (<$ls>) {
3131 chomp;
3132 $self->{gii}->remove($_);
3133 print "\tD\t$_\n" unless $::_q;
3135 print "\tD\t$gpath/\n" unless $::_q;
3136 command_close_pipe($ls, $ctx);
3137 $self->{empty}->{$path} = 0
3138 } else {
3139 $self->{gii}->remove($gpath);
3140 print "\tD\t$gpath\n" unless $::_q;
3142 undef;
3145 sub open_file {
3146 my ($self, $path, $pb, $rev) = @_;
3147 my $gpath = $self->git_path($path);
3148 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3149 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3150 unless (defined $mode && defined $blob) {
3151 die "$path was not found in commit $self->{c} (r$rev)\n";
3153 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3154 pool => SVN::Pool->new, action => 'M' };
3157 sub add_file {
3158 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3159 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3160 delete $self->{empty}->{$dir};
3161 { path => $path, mode_a => 100644, mode_b => 100644,
3162 pool => SVN::Pool->new, action => 'A' };
3165 sub add_directory {
3166 my ($self, $path, $cp_path, $cp_rev) = @_;
3167 my $gpath = $self->git_path($path);
3168 if ($gpath eq '') {
3169 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3170 -r --name-only -z/,
3171 $self->{c});
3172 local $/ = "\0";
3173 while (<$ls>) {
3174 chomp;
3175 $self->{gii}->remove($_);
3176 print "\tD\t$_\n" unless $::_q;
3178 command_close_pipe($ls, $ctx);
3179 $self->{empty}->{$path} = 0;
3181 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3182 delete $self->{empty}->{$dir};
3183 $self->{empty}->{$path} = 1;
3184 { path => $path };
3187 sub change_dir_prop {
3188 my ($self, $db, $prop, $value) = @_;
3189 $self->{dir_prop}->{$db->{path}} ||= {};
3190 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3191 undef;
3194 sub absent_directory {
3195 my ($self, $path, $pb) = @_;
3196 $self->{absent_dir}->{$pb->{path}} ||= [];
3197 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3198 undef;
3201 sub absent_file {
3202 my ($self, $path, $pb) = @_;
3203 $self->{absent_file}->{$pb->{path}} ||= [];
3204 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3205 undef;
3208 sub change_file_prop {
3209 my ($self, $fb, $prop, $value) = @_;
3210 if ($prop eq 'svn:executable') {
3211 if ($fb->{mode_b} != 120000) {
3212 $fb->{mode_b} = defined $value ? 100755 : 100644;
3214 } elsif ($prop eq 'svn:special') {
3215 $fb->{mode_b} = defined $value ? 120000 : 100644;
3216 } else {
3217 $self->{file_prop}->{$fb->{path}} ||= {};
3218 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3220 undef;
3223 sub apply_textdelta {
3224 my ($self, $fb, $exp) = @_;
3225 my $fh = IO::File->new_tmpfile;
3226 $fh->autoflush(1);
3227 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3228 # (but $base does not,) so dup() it for reading in close_file
3229 open my $dup, '<&', $fh or croak $!;
3230 my $base = IO::File->new_tmpfile;
3231 $base->autoflush(1);
3232 if ($fb->{blob}) {
3233 print $base 'link ' if ($fb->{mode_a} == 120000);
3234 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3235 die "Failed to read object $fb->{blob}" if ($size < 0);
3237 if (defined $exp) {
3238 seek $base, 0, 0 or croak $!;
3239 my $got = ::md5sum($base);
3240 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3241 "expected: $exp\n",
3242 " got: $got\n" if ($got ne $exp);
3245 seek $base, 0, 0 or croak $!;
3246 $fb->{fh} = $dup;
3247 $fb->{base} = $base;
3248 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3251 sub close_file {
3252 my ($self, $fb, $exp) = @_;
3253 my $hash;
3254 my $path = $self->git_path($fb->{path});
3255 if (my $fh = $fb->{fh}) {
3256 if (defined $exp) {
3257 seek($fh, 0, 0) or croak $!;
3258 my $got = ::md5sum($fh);
3259 if ($got ne $exp) {
3260 die "Checksum mismatch: $path\n",
3261 "expected: $exp\n got: $got\n";
3264 sysseek($fh, 0, 0) or croak $!;
3265 if ($fb->{mode_b} == 120000) {
3266 eval {
3267 sysread($fh, my $buf, 5) == 5 or croak $!;
3268 $buf eq 'link ' or die "$path has mode 120000",
3269 " but is not a link";
3271 if ($@) {
3272 warn "$@\n";
3273 sysseek($fh, 0, 0) or croak $!;
3277 my ($tmp_fh, $tmp_filename) = File::Temp::tempfile(UNLINK => 1);
3278 my $result;
3279 while ($result = sysread($fh, my $string, 1024)) {
3280 my $wrote = syswrite($tmp_fh, $string, $result);
3281 defined($wrote) && $wrote == $result
3282 or croak("write $tmp_filename: $!\n");
3284 defined $result or croak $!;
3285 close $tmp_fh or croak $!;
3287 close $fh or croak $!;
3289 $hash = $::_repository->hash_and_insert_object($tmp_filename);
3290 unlink($tmp_filename);
3291 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3292 close $fb->{base} or croak $!;
3293 } else {
3294 $hash = $fb->{blob} or die "no blob information\n";
3296 $fb->{pool}->clear;
3297 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3298 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3299 undef;
3302 sub abort_edit {
3303 my $self = shift;
3304 $self->{nr} = $self->{gii}->{nr};
3305 delete $self->{gii};
3306 $self->SUPER::abort_edit(@_);
3309 sub close_edit {
3310 my $self = shift;
3311 $self->{git_commit_ok} = 1;
3312 $self->{nr} = $self->{gii}->{nr};
3313 delete $self->{gii};
3314 $self->SUPER::close_edit(@_);
3317 package SVN::Git::Editor;
3318 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3319 use strict;
3320 use warnings;
3321 use Carp qw/croak/;
3322 use IO::File;
3324 sub new {
3325 my ($class, $opts) = @_;
3326 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3327 die "$_ required!\n" unless (defined $opts->{$_});
3330 my $pool = SVN::Pool->new;
3331 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3332 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3333 $opts->{r}, $mods);
3335 # $opts->{ra} functions should not be used after this:
3336 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3337 $opts->{editor_cb}, $pool);
3338 my $self = SVN::Delta::Editor->new(@ce, $pool);
3339 bless $self, $class;
3340 foreach (qw/svn_path r tree_a tree_b/) {
3341 $self->{$_} = $opts->{$_};
3343 $self->{url} = $opts->{ra}->{url};
3344 $self->{mods} = $mods;
3345 $self->{types} = $types;
3346 $self->{pool} = $pool;
3347 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3348 $self->{rm} = { };
3349 $self->{path_prefix} = length $self->{svn_path} ?
3350 "$self->{svn_path}/" : '';
3351 $self->{config} = $opts->{config};
3352 return $self;
3355 sub generate_diff {
3356 my ($tree_a, $tree_b) = @_;
3357 my @diff_tree = qw(diff-tree -z -r);
3358 if ($_cp_similarity) {
3359 push @diff_tree, "-C$_cp_similarity";
3360 } else {
3361 push @diff_tree, '-C';
3363 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3364 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3365 push @diff_tree, $tree_a, $tree_b;
3366 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3367 local $/ = "\0";
3368 my $state = 'meta';
3369 my @mods;
3370 while (<$diff_fh>) {
3371 chomp $_; # this gets rid of the trailing "\0"
3372 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3373 $::sha1\s($::sha1)\s
3374 ([MTCRAD])\d*$/xo) {
3375 push @mods, { mode_a => $1, mode_b => $2,
3376 sha1_b => $3, chg => $4 };
3377 if ($4 =~ /^(?:C|R)$/) {
3378 $state = 'file_a';
3379 } else {
3380 $state = 'file_b';
3382 } elsif ($state eq 'file_a') {
3383 my $x = $mods[$#mods] or croak "Empty array\n";
3384 if ($x->{chg} !~ /^(?:C|R)$/) {
3385 croak "Error parsing $_, $x->{chg}\n";
3387 $x->{file_a} = $_;
3388 $state = 'file_b';
3389 } elsif ($state eq 'file_b') {
3390 my $x = $mods[$#mods] or croak "Empty array\n";
3391 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3392 croak "Error parsing $_, $x->{chg}\n";
3394 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3395 croak "Error parsing $_, $x->{chg}\n";
3397 $x->{file_b} = $_;
3398 $state = 'meta';
3399 } else {
3400 croak "Error parsing $_\n";
3403 command_close_pipe($diff_fh, $ctx);
3404 \@mods;
3407 sub check_diff_paths {
3408 my ($ra, $pfx, $rev, $mods) = @_;
3409 my %types;
3410 $pfx .= '/' if length $pfx;
3412 sub type_diff_paths {
3413 my ($ra, $types, $path, $rev) = @_;
3414 my @p = split m#/+#, $path;
3415 my $c = shift @p;
3416 unless (defined $types->{$c}) {
3417 $types->{$c} = $ra->check_path($c, $rev);
3419 while (@p) {
3420 $c .= '/' . shift @p;
3421 next if defined $types->{$c};
3422 $types->{$c} = $ra->check_path($c, $rev);
3426 foreach my $m (@$mods) {
3427 foreach my $f (qw/file_a file_b/) {
3428 next unless defined $m->{$f};
3429 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3430 if (length $pfx.$dir && ! defined $types{$dir}) {
3431 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3435 \%types;
3438 sub split_path {
3439 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3442 sub repo_path {
3443 my ($self, $path) = @_;
3444 $self->{path_prefix}.(defined $path ? $path : '');
3447 sub url_path {
3448 my ($self, $path) = @_;
3449 if ($self->{url} =~ m#^https?://#) {
3450 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3452 $self->{url} . '/' . $self->repo_path($path);
3455 sub rmdirs {
3456 my ($self) = @_;
3457 my $rm = $self->{rm};
3458 delete $rm->{''}; # we never delete the url we're tracking
3459 return unless %$rm;
3461 foreach (keys %$rm) {
3462 my @d = split m#/#, $_;
3463 my $c = shift @d;
3464 $rm->{$c} = 1;
3465 while (@d) {
3466 $c .= '/' . shift @d;
3467 $rm->{$c} = 1;
3470 delete $rm->{$self->{svn_path}};
3471 delete $rm->{''}; # we never delete the url we're tracking
3472 return unless %$rm;
3474 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3475 $self->{tree_b});
3476 local $/ = "\0";
3477 while (<$fh>) {
3478 chomp;
3479 my @dn = split m#/#, $_;
3480 while (pop @dn) {
3481 delete $rm->{join '/', @dn};
3483 unless (%$rm) {
3484 close $fh;
3485 return;
3488 command_close_pipe($fh, $ctx);
3490 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3491 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3492 $self->close_directory($bat->{$d}, $p);
3493 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3494 print "\tD+\t$d/\n" unless $::_q;
3495 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3496 delete $bat->{$d};
3500 sub open_or_add_dir {
3501 my ($self, $full_path, $baton) = @_;
3502 my $t = $self->{types}->{$full_path};
3503 if (!defined $t) {
3504 die "$full_path not known in r$self->{r} or we have a bug!\n";
3507 no warnings 'once';
3508 # SVN::Node::none and SVN::Node::file are used only once,
3509 # so we're shutting up Perl's warnings about them.
3510 if ($t == $SVN::Node::none) {
3511 return $self->add_directory($full_path, $baton,
3512 undef, -1, $self->{pool});
3513 } elsif ($t == $SVN::Node::dir) {
3514 return $self->open_directory($full_path, $baton,
3515 $self->{r}, $self->{pool});
3516 } # no warnings 'once'
3517 print STDERR "$full_path already exists in repository at ",
3518 "r$self->{r} and it is not a directory (",
3519 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3520 } # no warnings 'once'
3521 exit 1;
3524 sub ensure_path {
3525 my ($self, $path) = @_;
3526 my $bat = $self->{bat};
3527 my $repo_path = $self->repo_path($path);
3528 return $bat->{''} unless (length $repo_path);
3529 my @p = split m#/+#, $repo_path;
3530 my $c = shift @p;
3531 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3532 while (@p) {
3533 my $c0 = $c;
3534 $c .= '/' . shift @p;
3535 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3537 return $bat->{$c};
3540 # Subroutine to convert a globbing pattern to a regular expression.
3541 # From perl cookbook.
3542 sub glob2pat {
3543 my $globstr = shift;
3544 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3545 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3546 return '^' . $globstr . '$';
3549 sub check_autoprop {
3550 my ($self, $pattern, $properties, $file, $fbat) = @_;
3551 # Convert the globbing pattern to a regular expression.
3552 my $regex = glob2pat($pattern);
3553 # Check if the pattern matches the file name.
3554 if($file =~ m/($regex)/) {
3555 # Parse the list of properties to set.
3556 my @props = split(/;/, $properties);
3557 foreach my $prop (@props) {
3558 # Parse 'name=value' syntax and set the property.
3559 if ($prop =~ /([^=]+)=(.*)/) {
3560 my ($n,$v) = ($1,$2);
3561 for ($n, $v) {
3562 s/^\s+//; s/\s+$//;
3564 $self->change_file_prop($fbat, $n, $v);
3570 sub apply_autoprops {
3571 my ($self, $file, $fbat) = @_;
3572 my $conf_t = ${$self->{config}}{'config'};
3573 no warnings 'once';
3574 # Check [miscellany]/enable-auto-props in svn configuration.
3575 if (SVN::_Core::svn_config_get_bool(
3576 $conf_t,
3577 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3578 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3579 0)) {
3580 # Auto-props are enabled. Enumerate them to look for matches.
3581 my $callback = sub {
3582 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3584 SVN::_Core::svn_config_enumerate(
3585 $conf_t,
3586 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3587 $callback);
3591 sub A {
3592 my ($self, $m) = @_;
3593 my ($dir, $file) = split_path($m->{file_b});
3594 my $pbat = $self->ensure_path($dir);
3595 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3596 undef, -1);
3597 print "\tA\t$m->{file_b}\n" unless $::_q;
3598 $self->apply_autoprops($file, $fbat);
3599 $self->chg_file($fbat, $m);
3600 $self->close_file($fbat,undef,$self->{pool});
3603 sub C {
3604 my ($self, $m) = @_;
3605 my ($dir, $file) = split_path($m->{file_b});
3606 my $pbat = $self->ensure_path($dir);
3607 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3608 $self->url_path($m->{file_a}), $self->{r});
3609 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3610 $self->chg_file($fbat, $m);
3611 $self->close_file($fbat,undef,$self->{pool});
3614 sub delete_entry {
3615 my ($self, $path, $pbat) = @_;
3616 my $rpath = $self->repo_path($path);
3617 my ($dir, $file) = split_path($rpath);
3618 $self->{rm}->{$dir} = 1;
3619 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3622 sub R {
3623 my ($self, $m) = @_;
3624 my ($dir, $file) = split_path($m->{file_b});
3625 my $pbat = $self->ensure_path($dir);
3626 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3627 $self->url_path($m->{file_a}), $self->{r});
3628 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3629 $self->chg_file($fbat, $m);
3630 $self->close_file($fbat,undef,$self->{pool});
3632 ($dir, $file) = split_path($m->{file_a});
3633 $pbat = $self->ensure_path($dir);
3634 $self->delete_entry($m->{file_a}, $pbat);
3637 sub M {
3638 my ($self, $m) = @_;
3639 my ($dir, $file) = split_path($m->{file_b});
3640 my $pbat = $self->ensure_path($dir);
3641 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3642 $pbat,$self->{r},$self->{pool});
3643 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3644 $self->chg_file($fbat, $m);
3645 $self->close_file($fbat,undef,$self->{pool});
3648 sub T { shift->M(@_) }
3650 sub change_file_prop {
3651 my ($self, $fbat, $pname, $pval) = @_;
3652 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3655 sub chg_file {
3656 my ($self, $fbat, $m) = @_;
3657 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3658 $self->change_file_prop($fbat,'svn:executable','*');
3659 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3660 $self->change_file_prop($fbat,'svn:executable',undef);
3662 my $fh = IO::File->new_tmpfile or croak $!;
3663 if ($m->{mode_b} =~ /^120/) {
3664 print $fh 'link ' or croak $!;
3665 $self->change_file_prop($fbat,'svn:special','*');
3666 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3667 $self->change_file_prop($fbat,'svn:special',undef);
3669 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
3670 croak "Failed to read object $m->{sha1_b}" if ($size < 0);
3671 $fh->flush == 0 or croak $!;
3672 seek $fh, 0, 0 or croak $!;
3674 my $exp = ::md5sum($fh);
3675 seek $fh, 0, 0 or croak $!;
3677 my $pool = SVN::Pool->new;
3678 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3679 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3680 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3681 $pool->clear;
3683 close $fh or croak $!;
3686 sub D {
3687 my ($self, $m) = @_;
3688 my ($dir, $file) = split_path($m->{file_b});
3689 my $pbat = $self->ensure_path($dir);
3690 print "\tD\t$m->{file_b}\n" unless $::_q;
3691 $self->delete_entry($m->{file_b}, $pbat);
3694 sub close_edit {
3695 my ($self) = @_;
3696 my ($p,$bat) = ($self->{pool}, $self->{bat});
3697 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3698 next if $_ eq '';
3699 $self->close_directory($bat->{$_}, $p);
3701 $self->close_directory($bat->{''}, $p);
3702 $self->SUPER::close_edit($p);
3703 $p->clear;
3706 sub abort_edit {
3707 my ($self) = @_;
3708 $self->SUPER::abort_edit($self->{pool});
3711 sub DESTROY {
3712 my $self = shift;
3713 $self->SUPER::DESTROY(@_);
3714 $self->{pool}->clear;
3717 # this drives the editor
3718 sub apply_diff {
3719 my ($self) = @_;
3720 my $mods = $self->{mods};
3721 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3722 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3723 my $f = $m->{chg};
3724 if (defined $o{$f}) {
3725 $self->$f($m);
3726 } else {
3727 fatal("Invalid change type: $f");
3730 $self->rmdirs if $_rmdir;
3731 if (@$mods == 0) {
3732 $self->abort_edit;
3733 } else {
3734 $self->close_edit;
3736 return scalar @$mods;
3739 package Git::SVN::Ra;
3740 use vars qw/@ISA $config_dir $_log_window_size/;
3741 use strict;
3742 use warnings;
3743 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3745 BEGIN {
3746 # enforce temporary pool usage for some simple functions
3747 no strict 'refs';
3748 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3749 my $SUPER = "SUPER::$f";
3750 *$f = sub {
3751 my $self = shift;
3752 my $pool = SVN::Pool->new;
3753 my @ret = $self->$SUPER(@_,$pool);
3754 $pool->clear;
3755 wantarray ? @ret : $ret[0];
3760 sub _auth_providers () {
3762 SVN::Client::get_simple_provider(),
3763 SVN::Client::get_ssl_server_trust_file_provider(),
3764 SVN::Client::get_simple_prompt_provider(
3765 \&Git::SVN::Prompt::simple, 2),
3766 SVN::Client::get_ssl_client_cert_file_provider(),
3767 SVN::Client::get_ssl_client_cert_prompt_provider(
3768 \&Git::SVN::Prompt::ssl_client_cert, 2),
3769 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3770 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3771 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3772 SVN::Client::get_username_provider(),
3773 SVN::Client::get_ssl_server_trust_prompt_provider(
3774 \&Git::SVN::Prompt::ssl_server_trust),
3775 SVN::Client::get_username_prompt_provider(
3776 \&Git::SVN::Prompt::username, 2)
3780 sub escape_uri_only {
3781 my ($uri) = @_;
3782 my @tmp;
3783 foreach (split m{/}, $uri) {
3784 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3785 push @tmp, $_;
3787 join('/', @tmp);
3790 sub escape_url {
3791 my ($url) = @_;
3792 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3793 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3794 $url = "$scheme://$domain$uri";
3796 $url;
3799 sub new {
3800 my ($class, $url) = @_;
3801 $url =~ s!/+$!!;
3802 return $RA if ($RA && $RA->{url} eq $url);
3804 SVN::_Core::svn_config_ensure($config_dir, undef);
3805 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3806 my $config = SVN::Core::config_get_config($config_dir);
3807 $RA = undef;
3808 my $dont_store_passwords = 1;
3809 my $conf_t = ${$config}{'config'};
3811 no warnings 'once';
3812 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3813 # produces warnings that variables are used only once.
3814 # I had not found the better way to shut them up, so
3815 # the warnings of type 'once' are disabled in this block.
3816 if (SVN::_Core::svn_config_get_bool($conf_t,
3817 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3818 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3819 1) == 0) {
3820 SVN::_Core::svn_auth_set_parameter($baton,
3821 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3822 bless (\$dont_store_passwords, "_p_void"));
3824 if (SVN::_Core::svn_config_get_bool($conf_t,
3825 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3826 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3827 1) == 0) {
3828 $Git::SVN::Prompt::_no_auth_cache = 1;
3830 } # no warnings 'once'
3831 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3832 config => $config,
3833 pool => SVN::Pool->new,
3834 auth_provider_callbacks => $callbacks);
3835 $self->{url} = $url;
3836 $self->{svn_path} = $url;
3837 $self->{repos_root} = $self->get_repos_root;
3838 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3839 $self->{cache} = { check_path => { r => 0, data => {} },
3840 get_dir => { r => 0, data => {} } };
3841 $RA = bless $self, $class;
3844 sub check_path {
3845 my ($self, $path, $r) = @_;
3846 my $cache = $self->{cache}->{check_path};
3847 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3848 return $cache->{data}->{$path};
3850 my $pool = SVN::Pool->new;
3851 my $t = $self->SUPER::check_path($path, $r, $pool);
3852 $pool->clear;
3853 if ($r != $cache->{r}) {
3854 %{$cache->{data}} = ();
3855 $cache->{r} = $r;
3857 $cache->{data}->{$path} = $t;
3860 sub get_dir {
3861 my ($self, $dir, $r) = @_;
3862 my $cache = $self->{cache}->{get_dir};
3863 if ($r == $cache->{r}) {
3864 if (my $x = $cache->{data}->{$dir}) {
3865 return wantarray ? @$x : $x->[0];
3868 my $pool = SVN::Pool->new;
3869 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3870 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3871 $pool->clear;
3872 if ($r != $cache->{r}) {
3873 %{$cache->{data}} = ();
3874 $cache->{r} = $r;
3876 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3877 wantarray ? (\%dirents, $r, $props) : \%dirents;
3880 sub DESTROY {
3881 # do not call the real DESTROY since we store ourselves in $RA
3884 sub get_log {
3885 my ($self, @args) = @_;
3886 my $pool = SVN::Pool->new;
3887 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3888 my $ret = $self->SUPER::get_log(@args, $pool);
3889 $pool->clear;
3890 $ret;
3893 sub trees_match {
3894 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3895 my $ctx = SVN::Client->new(auth => _auth_providers);
3896 my $out = IO::File->new_tmpfile;
3898 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3899 # $ctx->diff(), so we'll create a default one
3900 my $pool = SVN::Pool->new_default_sub;
3902 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3903 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3904 $out->flush;
3905 my $ret = (($out->stat)[7] == 0);
3906 close $out or croak $!;
3908 $ret;
3911 sub get_commit_editor {
3912 my ($self, $log, $cb, $pool) = @_;
3913 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3914 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3917 sub gs_do_update {
3918 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3919 my $new = ($rev_a == $rev_b);
3920 my $path = $gs->{path};
3922 if ($new && -e $gs->{index}) {
3923 unlink $gs->{index} or die
3924 "Couldn't unlink index: $gs->{index}: $!\n";
3926 my $pool = SVN::Pool->new;
3927 $editor->set_path_strip($path);
3928 my (@pc) = split m#/#, $path;
3929 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3930 1, $editor, $pool);
3931 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3933 # Since we can't rely on svn_ra_reparent being available, we'll
3934 # just have to do some magic with set_path to make it so
3935 # we only want a partial path.
3936 my $sp = '';
3937 my $final = join('/', @pc);
3938 while (@pc) {
3939 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3940 $sp .= '/' if length $sp;
3941 $sp .= shift @pc;
3943 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3945 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3947 $reporter->finish_report($pool);
3948 $pool->clear;
3949 $editor->{git_commit_ok};
3952 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3953 # svn_ra_reparent didn't work before 1.4)
3954 sub gs_do_switch {
3955 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3956 my $path = $gs->{path};
3957 my $pool = SVN::Pool->new;
3959 my $full_url = $self->{url};
3960 my $old_url = $full_url;
3961 $full_url .= '/' . escape_uri_only($path) if length $path;
3962 my ($ra, $reparented);
3963 if ($old_url ne $full_url) {
3964 if ($old_url !~ m#^svn(\+ssh)?://#) {
3965 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3966 $pool);
3967 $self->{url} = $full_url;
3968 $reparented = 1;
3969 } else {
3970 $_[0] = undef;
3971 $self = undef;
3972 $RA = undef;
3973 $ra = Git::SVN::Ra->new($full_url);
3974 $ra_invalid = 1;
3977 $ra ||= $self;
3978 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3979 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3980 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3981 $reporter->finish_report($pool);
3983 if ($reparented) {
3984 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3985 $self->{url} = $old_url;
3988 $pool->clear;
3989 $editor->{git_commit_ok};
3992 sub longest_common_path {
3993 my ($gsv, $globs) = @_;
3994 my %common;
3995 my $common_max = scalar @$gsv;
3997 foreach my $gs (@$gsv) {
3998 my @tmp = split m#/#, $gs->{path};
3999 my $p = '';
4000 foreach (@tmp) {
4001 $p .= length($p) ? "/$_" : $_;
4002 $common{$p} ||= 0;
4003 $common{$p}++;
4006 $globs ||= [];
4007 $common_max += scalar @$globs;
4008 foreach my $glob (@$globs) {
4009 my @tmp = split m#/#, $glob->{path}->{left};
4010 my $p = '';
4011 foreach (@tmp) {
4012 $p .= length($p) ? "/$_" : $_;
4013 $common{$p} ||= 0;
4014 $common{$p}++;
4018 my $longest_path = '';
4019 foreach (sort {length $b <=> length $a} keys %common) {
4020 if ($common{$_} == $common_max) {
4021 $longest_path = $_;
4022 last;
4025 $longest_path;
4028 sub gs_fetch_loop_common {
4029 my ($self, $base, $head, $gsv, $globs) = @_;
4030 return if ($base > $head);
4031 my $inc = $_log_window_size;
4032 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4033 my $longest_path = longest_common_path($gsv, $globs);
4034 my $ra_url = $self->{url};
4035 while (1) {
4036 my %revs;
4037 my $err;
4038 my $err_handler = $SVN::Error::handler;
4039 $SVN::Error::handler = sub {
4040 ($err) = @_;
4041 skip_unknown_revs($err);
4043 sub _cb {
4044 my ($paths, $r, $author, $date, $log) = @_;
4045 [ dup_changed_paths($paths),
4046 { author => $author, date => $date, log => $log } ];
4048 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4049 sub { $revs{$_[1]} = _cb(@_) });
4050 if ($err && $max >= $head) {
4051 print STDERR "Path '$longest_path' ",
4052 "was probably deleted:\n",
4053 $err->expanded_message,
4054 "\nWill attempt to follow ",
4055 "revisions r$min .. r$max ",
4056 "committed before the deletion\n";
4057 my $hi = $max;
4058 while (--$hi >= $min) {
4059 my $ok;
4060 $self->get_log([$longest_path], $min, $hi,
4061 0, 1, 1, sub {
4062 $ok ||= $_[1];
4063 $revs{$_[1]} = _cb(@_) });
4064 if ($ok) {
4065 print STDERR "r$min .. r$ok OK\n";
4066 last;
4070 $SVN::Error::handler = $err_handler;
4072 my %exists = map { $_->{path} => $_ } @$gsv;
4073 foreach my $r (sort {$a <=> $b} keys %revs) {
4074 my ($paths, $logged) = @{$revs{$r}};
4076 foreach my $gs ($self->match_globs(\%exists, $paths,
4077 $globs, $r)) {
4078 if ($gs->rev_map_max >= $r) {
4079 next;
4081 next unless $gs->match_paths($paths, $r);
4082 $gs->{logged_rev_props} = $logged;
4083 if (my $last_commit = $gs->last_commit) {
4084 $gs->assert_index_clean($last_commit);
4086 my $log_entry = $gs->do_fetch($paths, $r);
4087 if ($log_entry) {
4088 $gs->do_git_commit($log_entry);
4090 $INDEX_FILES{$gs->{index}} = 1;
4092 foreach my $g (@$globs) {
4093 my $k = "svn-remote.$g->{remote}." .
4094 "$g->{t}-maxRev";
4095 Git::SVN::tmp_config($k, $r);
4097 if ($ra_invalid) {
4098 $_[0] = undef;
4099 $self = undef;
4100 $RA = undef;
4101 $self = Git::SVN::Ra->new($ra_url);
4102 $ra_invalid = undef;
4105 # pre-fill the .rev_db since it'll eventually get filled in
4106 # with '0' x40 if something new gets committed
4107 foreach my $gs (@$gsv) {
4108 next if $gs->rev_map_max >= $max;
4109 next if defined $gs->rev_map_get($max);
4110 $gs->rev_map_set($max, 0 x40);
4112 foreach my $g (@$globs) {
4113 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4114 Git::SVN::tmp_config($k, $max);
4116 last if $max >= $head;
4117 $min = $max + 1;
4118 $max += $inc;
4119 $max = $head if ($max > $head);
4121 Git::SVN::gc();
4124 sub match_globs {
4125 my ($self, $exists, $paths, $globs, $r) = @_;
4127 sub get_dir_check {
4128 my ($self, $exists, $g, $r) = @_;
4129 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
4130 return unless scalar @x == 3;
4131 my $dirents = $x[0];
4132 foreach my $de (keys %$dirents) {
4133 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4134 my $p = $g->{path}->full_path($de);
4135 next if $exists->{$p};
4136 next if (length $g->{path}->{right} &&
4137 ($self->check_path($p, $r) !=
4138 $SVN::Node::dir));
4139 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4140 $g->{ref}->full_path($de), 1);
4143 foreach my $g (@$globs) {
4144 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4145 if ($path->{action} =~ /^[AR]$/) {
4146 get_dir_check($self, $exists, $g, $r);
4149 foreach (keys %$paths) {
4150 if (/$g->{path}->{left_regex}/ &&
4151 !/$g->{path}->{regex}/) {
4152 next if $paths->{$_}->{action} !~ /^[AR]$/;
4153 get_dir_check($self, $exists, $g, $r);
4155 next unless /$g->{path}->{regex}/;
4156 my $p = $1;
4157 my $pathname = $g->{path}->full_path($p);
4158 next if $exists->{$pathname};
4159 next if ($self->check_path($pathname, $r) !=
4160 $SVN::Node::dir);
4161 $exists->{$pathname} = Git::SVN->init(
4162 $self->{url}, $pathname, undef,
4163 $g->{ref}->full_path($p), 1);
4165 my $c = '';
4166 foreach (split m#/#, $g->{path}->{left}) {
4167 $c .= "/$_";
4168 next unless ($paths->{$c} &&
4169 ($paths->{$c}->{action} =~ /^[AR]$/));
4170 get_dir_check($self, $exists, $g, $r);
4173 values %$exists;
4176 sub minimize_url {
4177 my ($self) = @_;
4178 return $self->{url} if ($self->{url} eq $self->{repos_root});
4179 my $url = $self->{repos_root};
4180 my @components = split(m!/!, $self->{svn_path});
4181 my $c = '';
4182 do {
4183 $url .= "/$c" if length $c;
4184 eval { (ref $self)->new($url)->get_latest_revnum };
4185 } while ($@ && ($c = shift @components));
4186 $url;
4189 sub can_do_switch {
4190 my $self = shift;
4191 unless (defined $can_do_switch) {
4192 my $pool = SVN::Pool->new;
4193 my $rep = eval {
4194 $self->do_switch(1, '', 0, $self->{url},
4195 SVN::Delta::Editor->new, $pool);
4197 if ($@) {
4198 $can_do_switch = 0;
4199 } else {
4200 $rep->abort_report($pool);
4201 $can_do_switch = 1;
4203 $pool->clear;
4205 $can_do_switch;
4208 sub skip_unknown_revs {
4209 my ($err) = @_;
4210 my $errno = $err->apr_err();
4211 # Maybe the branch we're tracking didn't
4212 # exist when the repo started, so it's
4213 # not an error if it doesn't, just continue
4215 # Wonderfully consistent library, eh?
4216 # 160013 - svn:// and file://
4217 # 175002 - http(s)://
4218 # 175007 - http(s):// (this repo required authorization, too...)
4219 # More codes may be discovered later...
4220 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4221 my $err_key = $err->expanded_message;
4222 # revision numbers change every time, filter them out
4223 $err_key =~ s/\d+/\0/g;
4224 $err_key = "$errno\0$err_key";
4225 unless ($ignored_err{$err_key}) {
4226 warn "W: Ignoring error from SVN, path probably ",
4227 "does not exist: ($errno): ",
4228 $err->expanded_message,"\n";
4229 warn "W: Do not be alarmed at the above message ",
4230 "git-svn is just searching aggressively for ",
4231 "old history.\n",
4232 "This may take a while on large repositories\n";
4233 $ignored_err{$err_key} = 1;
4235 return;
4237 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4240 # svn_log_changed_path_t objects passed to get_log are likely to be
4241 # overwritten even if only the refs are copied to an external variable,
4242 # so we should dup the structures in their entirety. Using an externally
4243 # passed pool (instead of our temporary and quickly cleared pool in
4244 # Git::SVN::Ra) does not help matters at all...
4245 sub dup_changed_paths {
4246 my ($paths) = @_;
4247 return undef unless $paths;
4248 my %ret;
4249 foreach my $p (keys %$paths) {
4250 my $i = $paths->{$p};
4251 my %s = map { $_ => $i->$_ }
4252 qw/copyfrom_path copyfrom_rev action/;
4253 $ret{$p} = \%s;
4255 \%ret;
4258 package Git::SVN::Log;
4259 use strict;
4260 use warnings;
4261 use POSIX qw/strftime/;
4262 use constant commit_log_separator => ('-' x 72) . "\n";
4263 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4264 %rusers $show_commit $incremental/;
4265 my $l_fmt;
4267 sub cmt_showable {
4268 my ($c) = @_;
4269 return 1 if defined $c->{r};
4271 # big commit message got truncated by the 16k pretty buffer in rev-list
4272 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4273 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4274 @{$c->{l}} = ();
4275 my @log = command(qw/cat-file commit/, $c->{c});
4277 # shift off the headers
4278 shift @log while ($log[0] ne '');
4279 shift @log;
4281 # TODO: make $c->{l} not have a trailing newline in the future
4282 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4284 (undef, $c->{r}, undef) = ::extract_metadata(
4285 (grep(/^git-svn-id: /, @log))[-1]);
4287 return defined $c->{r};
4290 sub log_use_color {
4291 return $color || Git->repository->get_colorbool('color.diff');
4294 sub git_svn_log_cmd {
4295 my ($r_min, $r_max, @args) = @_;
4296 my $head = 'HEAD';
4297 my (@files, @log_opts);
4298 foreach my $x (@args) {
4299 if ($x eq '--' || @files) {
4300 push @files, $x;
4301 } else {
4302 if (::verify_ref("$x^0")) {
4303 $head = $x;
4304 } else {
4305 push @log_opts, $x;
4310 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4311 $gs ||= Git::SVN->_new;
4312 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4313 $gs->refname);
4314 push @cmd, '-r' unless $non_recursive;
4315 push @cmd, qw/--raw --name-status/ if $verbose;
4316 push @cmd, '--color' if log_use_color();
4317 push @cmd, @log_opts;
4318 if (defined $r_max && $r_max == $r_min) {
4319 push @cmd, '--max-count=1';
4320 if (my $c = $gs->rev_map_get($r_max)) {
4321 push @cmd, $c;
4323 } elsif (defined $r_max) {
4324 if ($r_max < $r_min) {
4325 ($r_min, $r_max) = ($r_max, $r_min);
4327 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4328 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4329 # If there are no commits in the range, both $c_max and $c_min
4330 # will be undefined. If there is at least 1 commit in the
4331 # range, both will be defined.
4332 return () if !defined $c_min || !defined $c_max;
4333 if ($c_min eq $c_max) {
4334 push @cmd, '--max-count=1', $c_min;
4335 } else {
4336 push @cmd, '--boundary', "$c_min..$c_max";
4339 return (@cmd, @files);
4342 # adapted from pager.c
4343 sub config_pager {
4344 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4345 if (!defined $pager) {
4346 $pager = 'less';
4347 } elsif (length $pager == 0 || $pager eq 'cat') {
4348 $pager = undef;
4350 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4353 sub run_pager {
4354 return unless -t *STDOUT && defined $pager;
4355 pipe my $rfd, my $wfd or return;
4356 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4357 if (!$pid) {
4358 open STDOUT, '>&', $wfd or
4359 ::fatal "Can't redirect to stdout: $!";
4360 return;
4362 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4363 $ENV{LESS} ||= 'FRSX';
4364 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4367 sub format_svn_date {
4368 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4371 sub parse_git_date {
4372 my ($t, $tz) = @_;
4373 # Date::Parse isn't in the standard Perl distro :(
4374 if ($tz =~ s/^\+//) {
4375 $t += tz_to_s_offset($tz);
4376 } elsif ($tz =~ s/^\-//) {
4377 $t -= tz_to_s_offset($tz);
4379 return $t;
4382 sub set_local_timezone {
4383 if (defined $TZ) {
4384 $ENV{TZ} = $TZ;
4385 } else {
4386 delete $ENV{TZ};
4390 sub tz_to_s_offset {
4391 my ($tz) = @_;
4392 $tz =~ s/(\d\d)$//;
4393 return ($1 * 60) + ($tz * 3600);
4396 sub get_author_info {
4397 my ($dest, $author, $t, $tz) = @_;
4398 $author =~ s/(?:^\s*|\s*$)//g;
4399 $dest->{a_raw} = $author;
4400 my $au;
4401 if ($::_authors) {
4402 $au = $rusers{$author} || undef;
4404 if (!$au) {
4405 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4407 $dest->{t} = $t;
4408 $dest->{tz} = $tz;
4409 $dest->{a} = $au;
4410 $dest->{t_utc} = parse_git_date($t, $tz);
4413 sub process_commit {
4414 my ($c, $r_min, $r_max, $defer) = @_;
4415 if (defined $r_min && defined $r_max) {
4416 if ($r_min == $c->{r} && $r_min == $r_max) {
4417 show_commit($c);
4418 return 0;
4420 return 1 if $r_min == $r_max;
4421 if ($r_min < $r_max) {
4422 # we need to reverse the print order
4423 return 0 if (defined $limit && --$limit < 0);
4424 push @$defer, $c;
4425 return 1;
4427 if ($r_min != $r_max) {
4428 return 1 if ($r_min < $c->{r});
4429 return 1 if ($r_max > $c->{r});
4432 return 0 if (defined $limit && --$limit < 0);
4433 show_commit($c);
4434 return 1;
4437 sub show_commit {
4438 my $c = shift;
4439 if ($oneline) {
4440 my $x = "\n";
4441 if (my $l = $c->{l}) {
4442 while ($l->[0] =~ /^\s*$/) { shift @$l }
4443 $x = $l->[0];
4445 $l_fmt ||= 'A' . length($c->{r});
4446 print 'r',pack($l_fmt, $c->{r}),' | ';
4447 print "$c->{c} | " if $show_commit;
4448 print $x;
4449 } else {
4450 show_commit_normal($c);
4454 sub show_commit_changed_paths {
4455 my ($c) = @_;
4456 return unless $c->{changed};
4457 print "Changed paths:\n", @{$c->{changed}};
4460 sub show_commit_normal {
4461 my ($c) = @_;
4462 print commit_log_separator, "r$c->{r} | ";
4463 print "$c->{c} | " if $show_commit;
4464 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4465 my $nr_line = 0;
4467 if (my $l = $c->{l}) {
4468 while ($l->[$#$l] eq "\n" && $#$l > 0
4469 && $l->[($#$l - 1)] eq "\n") {
4470 pop @$l;
4472 $nr_line = scalar @$l;
4473 if (!$nr_line) {
4474 print "1 line\n\n\n";
4475 } else {
4476 if ($nr_line == 1) {
4477 $nr_line = '1 line';
4478 } else {
4479 $nr_line .= ' lines';
4481 print $nr_line, "\n";
4482 show_commit_changed_paths($c);
4483 print "\n";
4484 print $_ foreach @$l;
4486 } else {
4487 print "1 line\n";
4488 show_commit_changed_paths($c);
4489 print "\n";
4492 foreach my $x (qw/raw stat diff/) {
4493 if ($c->{$x}) {
4494 print "\n";
4495 print $_ foreach @{$c->{$x}}
4500 sub cmd_show_log {
4501 my (@args) = @_;
4502 my ($r_min, $r_max);
4503 my $r_last = -1; # prevent dupes
4504 set_local_timezone();
4505 if (defined $::_revision) {
4506 if ($::_revision =~ /^(\d+):(\d+)$/) {
4507 ($r_min, $r_max) = ($1, $2);
4508 } elsif ($::_revision =~ /^\d+$/) {
4509 $r_min = $r_max = $::_revision;
4510 } else {
4511 ::fatal "-r$::_revision is not supported, use ",
4512 "standard 'git log' arguments instead";
4516 config_pager();
4517 @args = git_svn_log_cmd($r_min, $r_max, @args);
4518 if (!@args) {
4519 print commit_log_separator unless $incremental || $oneline;
4520 return;
4522 my $log = command_output_pipe(@args);
4523 run_pager();
4524 my (@k, $c, $d, $stat);
4525 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4526 while (<$log>) {
4527 if (/^${esc_color}commit -?($::sha1_short)/o) {
4528 my $cmt = $1;
4529 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4530 $r_last = $c->{r};
4531 process_commit($c, $r_min, $r_max, \@k) or
4532 goto out;
4534 $d = undef;
4535 $c = { c => $cmt };
4536 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4537 get_author_info($c, $1, $2, $3);
4538 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4539 # ignore
4540 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4541 push @{$c->{raw}}, $_;
4542 } elsif (/^${esc_color}[ACRMDT]\t/) {
4543 # we could add $SVN->{svn_path} here, but that requires
4544 # remote access at the moment (repo_path_split)...
4545 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4546 push @{$c->{changed}}, $_;
4547 } elsif (/^${esc_color}diff /o) {
4548 $d = 1;
4549 push @{$c->{diff}}, $_;
4550 } elsif ($d) {
4551 push @{$c->{diff}}, $_;
4552 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4553 $esc_color*[\+\-]*$esc_color$/x) {
4554 $stat = 1;
4555 push @{$c->{stat}}, $_;
4556 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4557 push @{$c->{stat}}, $_;
4558 $stat = undef;
4559 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4560 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4561 } elsif (s/^${esc_color} //o) {
4562 push @{$c->{l}}, $_;
4565 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4566 $r_last = $c->{r};
4567 process_commit($c, $r_min, $r_max, \@k);
4569 if (@k) {
4570 ($r_min, $r_max) = ($r_max, $r_min);
4571 process_commit($_, $r_min, $r_max) foreach reverse @k;
4573 out:
4574 close $log;
4575 print commit_log_separator unless $incremental || $oneline;
4578 sub cmd_blame {
4579 my $path = pop;
4581 config_pager();
4582 run_pager();
4584 my ($fh, $ctx, $rev);
4586 if ($_git_format) {
4587 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4588 while (my $line = <$fh>) {
4589 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4590 # Uncommitted edits show up as a rev ID of
4591 # all zeros, which we can't look up with
4592 # cmt_metadata
4593 if ($1 !~ /^0+$/) {
4594 (undef, $rev, undef) =
4595 ::cmt_metadata($1);
4596 $rev = '0' if (!$rev);
4597 } else {
4598 $rev = '0';
4600 $rev = sprintf('%-10s', $rev);
4601 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4603 print $line;
4605 } else {
4606 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4607 '--', $path);
4608 my ($sha1);
4609 my %authors;
4610 while (my $line = <$fh>) {
4611 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4612 $sha1 = $1;
4613 (undef, $rev, undef) = ::cmt_metadata($1);
4614 $rev = '0' if (!$rev);
4616 elsif ($line =~ /^author (.*)/) {
4617 $authors{$rev} = $1;
4618 $authors{$rev} =~ s/\s/_/g;
4620 elsif ($line =~ /^\t(.*)$/) {
4621 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4625 command_close_pipe($fh, $ctx);
4628 package Git::SVN::Migration;
4629 # these version numbers do NOT correspond to actual version numbers
4630 # of git nor git-svn. They are just relative.
4632 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4634 # v1 layout: .git/$id/info/url, refs/remotes/$id
4636 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4638 # v3 layout: .git/svn/$id, refs/remotes/$id
4639 # - info/url may remain for backwards compatibility
4640 # - this is what we migrate up to this layout automatically,
4641 # - this will be used by git svn init on single branches
4642 # v3.1 layout (auto migrated):
4643 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4644 # for backwards compatibility
4646 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4647 # - this is only created for newly multi-init-ed
4648 # repositories. Similar in spirit to the
4649 # --use-separate-remotes option in git-clone (now default)
4650 # - we do not automatically migrate to this (following
4651 # the example set by core git)
4653 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4654 # - newer, more-efficient format that uses 24-bytes per record
4655 # with no filler space.
4656 # - use xxd -c24 < .rev_map.$UUID to view and debug
4657 # - This is a one-way migration, repositories updated to the
4658 # new format will not be able to use old git-svn without
4659 # rebuilding the .rev_db. Rebuilding the rev_db is not
4660 # possible if noMetadata or useSvmProps are set; but should
4661 # be no problem for users that use the (sensible) defaults.
4662 use strict;
4663 use warnings;
4664 use Carp qw/croak/;
4665 use File::Path qw/mkpath/;
4666 use File::Basename qw/dirname basename/;
4667 use vars qw/$_minimize/;
4669 sub migrate_from_v0 {
4670 my $git_dir = $ENV{GIT_DIR};
4671 return undef unless -d $git_dir;
4672 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4673 my $migrated = 0;
4674 while (<$fh>) {
4675 chomp;
4676 my ($id, $orig_ref) = ($_, $_);
4677 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4678 next unless -f "$git_dir/$id/info/url";
4679 my $new_ref = "refs/remotes/$id";
4680 if (::verify_ref("$new_ref^0")) {
4681 print STDERR "W: $orig_ref is probably an old ",
4682 "branch used by an ancient version of ",
4683 "git-svn.\n",
4684 "However, $new_ref also exists.\n",
4685 "We will not be able ",
4686 "to use this branch until this ",
4687 "ambiguity is resolved.\n";
4688 next;
4690 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4691 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4692 command_noisy('update-ref', $new_ref, $orig_ref);
4693 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4694 $migrated++;
4696 command_close_pipe($fh, $ctx);
4697 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4698 $migrated;
4701 sub migrate_from_v1 {
4702 my $git_dir = $ENV{GIT_DIR};
4703 my $migrated = 0;
4704 return $migrated unless -d $git_dir;
4705 my $svn_dir = "$git_dir/svn";
4707 # just in case somebody used 'svn' as their $id at some point...
4708 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4710 print STDERR "Migrating from a git-svn v1 layout...\n";
4711 mkpath([$svn_dir]);
4712 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4713 "$svn_dir\n\t(required for this version ",
4714 "($::VERSION) of git-svn) does not exist.\n";
4715 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4716 while (<$fh>) {
4717 my $x = $_;
4718 next unless $x =~ s#^refs/remotes/##;
4719 chomp $x;
4720 next unless -f "$git_dir/$x/info/url";
4721 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4722 next unless $u;
4723 my $dn = dirname("$git_dir/svn/$x");
4724 mkpath([$dn]) unless -d $dn;
4725 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4726 mkpath(["$git_dir/svn/svn"]);
4727 print STDERR " - $git_dir/$x/info => ",
4728 "$git_dir/svn/$x/info\n";
4729 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4730 croak "$!: $x";
4731 # don't worry too much about these, they probably
4732 # don't exist with repos this old (save for index,
4733 # and we can easily regenerate that)
4734 foreach my $f (qw/unhandled.log index .rev_db/) {
4735 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4737 } else {
4738 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4739 rename "$git_dir/$x", "$git_dir/svn/$x" or
4740 croak "$!: $x";
4742 $migrated++;
4744 command_close_pipe($fh, $ctx);
4745 print STDERR "Done migrating from a git-svn v1 layout\n";
4746 $migrated;
4749 sub read_old_urls {
4750 my ($l_map, $pfx, $path) = @_;
4751 my @dir;
4752 foreach (<$path/*>) {
4753 if (-r "$_/info/url") {
4754 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4755 my $ref_id = $pfx . basename $_;
4756 my $url = ::file_to_s("$_/info/url");
4757 $l_map->{$ref_id} = $url;
4758 } elsif (-d $_) {
4759 push @dir, $_;
4762 foreach (@dir) {
4763 my $x = $_;
4764 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4765 read_old_urls($l_map, $x, $_);
4769 sub migrate_from_v2 {
4770 my @cfg = command(qw/config -l/);
4771 return if grep /^svn-remote\..+\.url=/, @cfg;
4772 my %l_map;
4773 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4774 my $migrated = 0;
4776 foreach my $ref_id (sort keys %l_map) {
4777 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4778 if ($@) {
4779 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4781 $migrated++;
4783 $migrated;
4786 sub minimize_connections {
4787 my $r = Git::SVN::read_all_remotes();
4788 my $new_urls = {};
4789 my $root_repos = {};
4790 foreach my $repo_id (keys %$r) {
4791 my $url = $r->{$repo_id}->{url} or next;
4792 my $fetch = $r->{$repo_id}->{fetch} or next;
4793 my $ra = Git::SVN::Ra->new($url);
4795 # skip existing cases where we already connect to the root
4796 if (($ra->{url} eq $ra->{repos_root}) ||
4797 ($ra->{repos_root} eq $repo_id)) {
4798 $root_repos->{$ra->{url}} = $repo_id;
4799 next;
4802 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4803 my $root_path = $ra->{url};
4804 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4805 foreach my $path (keys %$fetch) {
4806 my $ref_id = $fetch->{$path};
4807 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4809 # make sure we can read when connecting to
4810 # a higher level of a repository
4811 my ($last_rev, undef) = $gs->last_rev_commit;
4812 if (!defined $last_rev) {
4813 $last_rev = eval {
4814 $root_ra->get_latest_revnum;
4816 next if $@;
4818 my $new = $root_path;
4819 $new .= length $path ? "/$path" : '';
4820 eval {
4821 $root_ra->get_log([$new], $last_rev, $last_rev,
4822 0, 0, 1, sub { });
4824 next if $@;
4825 $new_urls->{$ra->{repos_root}}->{$new} =
4826 { ref_id => $ref_id,
4827 old_repo_id => $repo_id,
4828 old_path => $path };
4832 my @emptied;
4833 foreach my $url (keys %$new_urls) {
4834 # see if we can re-use an existing [svn-remote "repo_id"]
4835 # instead of creating a(n ugly) new section:
4836 my $repo_id = $root_repos->{$url} || $url;
4838 my $fetch = $new_urls->{$url};
4839 foreach my $path (keys %$fetch) {
4840 my $x = $fetch->{$path};
4841 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4842 my $pfx = "svn-remote.$x->{old_repo_id}";
4844 my $old_fetch = quotemeta("$x->{old_path}:".
4845 "refs/remotes/$x->{ref_id}");
4846 command_noisy(qw/config --unset/,
4847 "$pfx.fetch", '^'. $old_fetch . '$');
4848 delete $r->{$x->{old_repo_id}}->
4849 {fetch}->{$x->{old_path}};
4850 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4851 command_noisy(qw/config --unset/,
4852 "$pfx.url");
4853 push @emptied, $x->{old_repo_id}
4857 if (@emptied) {
4858 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4859 "$ENV{GIT_DIR}/config";
4860 print STDERR <<EOF;
4861 The following [svn-remote] sections in your config file ($file) are empty
4862 and can be safely removed:
4864 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4868 sub migration_check {
4869 migrate_from_v0();
4870 migrate_from_v1();
4871 migrate_from_v2();
4872 minimize_connections() if $_minimize;
4875 package Git::IndexInfo;
4876 use strict;
4877 use warnings;
4878 use Git qw/command_input_pipe command_close_pipe/;
4880 sub new {
4881 my ($class) = @_;
4882 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4883 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4886 sub remove {
4887 my ($self, $path) = @_;
4888 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4889 return ++$self->{nr};
4891 undef;
4894 sub update {
4895 my ($self, $mode, $hash, $path) = @_;
4896 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4897 return ++$self->{nr};
4899 undef;
4902 sub DESTROY {
4903 my ($self) = @_;
4904 command_close_pipe($self->{gui}, $self->{ctx});
4907 package Git::SVN::GlobSpec;
4908 use strict;
4909 use warnings;
4911 sub new {
4912 my ($class, $glob) = @_;
4913 my $re = $glob;
4914 $re =~ s!/+$!!g; # no need for trailing slashes
4915 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4916 my ($left, $right) = ($1, $2);
4917 if ($nr > 1) {
4918 die "Only one '*' wildcard expansion ",
4919 "is supported (got $nr): '$glob'\n";
4920 } elsif ($nr == 0) {
4921 die "One '*' is needed for glob: '$glob'\n";
4923 $re = quotemeta($left) . $re . quotemeta($right);
4924 if (length $left && !($left =~ s!/+$!!g)) {
4925 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4927 if (length $right && !($right =~ s!^/+!!g)) {
4928 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4930 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4931 bless { left => $left, right => $right, left_regex => $left_re,
4932 regex => qr/$re/, glob => $glob }, $class;
4935 sub full_path {
4936 my ($self, $path) = @_;
4937 return (length $self->{left} ? "$self->{left}/" : '') .
4938 $path . (length $self->{right} ? "/$self->{right}" : '');
4941 __END__
4943 Data structures:
4946 $remotes = { # returned by read_all_remotes()
4947 'svn' => {
4948 # svn-remote.svn.url=https://svn.musicpd.org
4949 url => 'https://svn.musicpd.org',
4950 # svn-remote.svn.fetch=mpd/trunk:trunk
4951 fetch => {
4952 'mpd/trunk' => 'trunk',
4954 # svn-remote.svn.tags=mpd/tags/*:tags/*
4955 tags => {
4956 path => {
4957 left => 'mpd/tags',
4958 right => '',
4959 regex => qr!mpd/tags/([^/]+)$!,
4960 glob => 'tags/*',
4962 ref => {
4963 left => 'tags',
4964 right => '',
4965 regex => qr!tags/([^/]+)$!,
4966 glob => 'tags/*',
4972 $log_entry hashref as returned by libsvn_log_entry()
4974 log => 'whitespace-formatted log entry
4975 ', # trailing newline is preserved
4976 revision => '8', # integer
4977 date => '2004-02-24T17:01:44.108345Z', # commit date
4978 author => 'committer name'
4982 # this is generated by generate_diff();
4983 @mods = array of diff-index line hashes, each element represents one line
4984 of diff-index output
4986 diff-index line ($m hash)
4988 mode_a => first column of diff-index output, no leading ':',
4989 mode_b => second column of diff-index output,
4990 sha1_b => sha1sum of the final blob,
4991 chg => change type [MCRADT],
4992 file_a => original file name of a file (iff chg is 'C' or 'R')
4993 file_b => new/current file name of a file (any chg)
4997 # retval of read_url_paths{,_all}();
4998 $l_map = {
4999 # repository root url
5000 'https://svn.musicpd.org' => {
5001 # repository path # GIT_SVN_ID
5002 'mpd/trunk' => 'trunk',
5003 'mpd/tags/0.11.5' => 'tags/0.11.5',
5007 Notes:
5008 I don't trust the each() function on unless I created %hash myself
5009 because the internal iterator may not have started at base.