Merge branch 'db/maint-checkout-b'
[git/trast.git] / git-svn.perl
blobaf8279acafd8a0e1701f3547da3011c585051e6d
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, $_commit_url);
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 'commit-url=s' => \$_commit_url,
131 'revision|r=i' => \$_revision,
132 'no-rebase' => \$_no_rebase,
133 %cmt_opts, %fc_opts } ],
134 'set-tree' => [ \&cmd_set_tree,
135 "Set an SVN repository to a git tree-ish",
136 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
137 'create-ignore' => [ \&cmd_create_ignore,
138 'Create a .gitignore per svn:ignore',
139 { 'revision|r=i' => \$_revision
140 } ],
141 'propget' => [ \&cmd_propget,
142 'Print the value of a property on a file or directory',
143 { 'revision|r=i' => \$_revision } ],
144 'proplist' => [ \&cmd_proplist,
145 'List all properties of a file or directory',
146 { 'revision|r=i' => \$_revision } ],
147 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
148 { 'revision|r=i' => \$_revision
149 } ],
150 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
151 { 'revision|r=i' => \$_revision
152 } ],
153 'multi-fetch' => [ \&cmd_multi_fetch,
154 "Deprecated alias for $0 fetch --all",
155 { 'revision|r=s' => \$_revision, %fc_opts } ],
156 'migrate' => [ sub { },
157 # no-op, we automatically run this anyways,
158 'Migrate configuration/metadata/layout from
159 previous versions of git-svn',
160 { 'minimize' => \$Git::SVN::Migration::_minimize,
161 %remote_opts } ],
162 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
163 { 'limit=i' => \$Git::SVN::Log::limit,
164 'revision|r=s' => \$_revision,
165 'verbose|v' => \$Git::SVN::Log::verbose,
166 'incremental' => \$Git::SVN::Log::incremental,
167 'oneline' => \$Git::SVN::Log::oneline,
168 'show-commit' => \$Git::SVN::Log::show_commit,
169 'non-recursive' => \$Git::SVN::Log::non_recursive,
170 'authors-file|A=s' => \$_authors,
171 'color' => \$Git::SVN::Log::color,
172 'pager=s' => \$Git::SVN::Log::pager
173 } ],
174 'find-rev' => [ \&cmd_find_rev,
175 "Translate between SVN revision numbers and tree-ish",
176 {} ],
177 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
178 { 'merge|m|M' => \$_merge,
179 'verbose|v' => \$_verbose,
180 'strategy|s=s' => \$_strategy,
181 'local|l' => \$_local,
182 'fetch-all|all' => \$_fetch_all,
183 'dry-run|n' => \$_dry_run,
184 %fc_opts } ],
185 'commit-diff' => [ \&cmd_commit_diff,
186 'Commit a diff between two trees',
187 { 'message|m=s' => \$_message,
188 'file|F=s' => \$_file,
189 'revision|r=s' => \$_revision,
190 %cmt_opts } ],
191 'info' => [ \&cmd_info,
192 "Show info about the latest SVN revision
193 on the current branch",
194 { 'url' => \$_url, } ],
195 'blame' => [ \&Git::SVN::Log::cmd_blame,
196 "Show what revision and author last modified each line of a file",
197 { 'git-format' => \$_git_format } ],
200 my $cmd;
201 for (my $i = 0; $i < @ARGV; $i++) {
202 if (defined $cmd{$ARGV[$i]}) {
203 $cmd = $ARGV[$i];
204 splice @ARGV, $i, 1;
205 last;
209 # make sure we're always running at the top-level working directory
210 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
211 unless (-d $ENV{GIT_DIR}) {
212 if ($git_dir_user_set) {
213 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
214 "but it is not a directory\n";
216 my $git_dir = delete $ENV{GIT_DIR};
217 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
218 unless (length $cdup) {
219 die "Already at toplevel, but $git_dir ",
220 "not found '$cdup'\n";
222 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
223 unless (-d $git_dir) {
224 die "$git_dir still not found after going to ",
225 "'$cdup'\n";
227 $ENV{GIT_DIR} = $git_dir;
229 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
232 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
234 read_repo_config(\%opts);
235 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
236 Getopt::Long::Configure('pass_through');
238 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
239 'minimize-connections' => \$Git::SVN::Migration::_minimize,
240 'id|i=s' => \$Git::SVN::default_ref_id,
241 'svn-remote|remote|R=s' => sub {
242 $Git::SVN::no_reuse_existing = 1;
243 $Git::SVN::default_repo_id = $_[1] });
244 exit 1 if (!$rv && $cmd && $cmd ne 'log');
246 usage(0) if $_help;
247 version() if $_version;
248 usage(1) unless defined $cmd;
249 load_authors() if $_authors;
251 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
252 Git::SVN::Migration::migration_check();
254 Git::SVN::init_vars();
255 eval {
256 Git::SVN::verify_remotes_sanity();
257 $cmd{$cmd}->[0]->(@ARGV);
259 fatal $@ if $@;
260 post_fetch_checkout();
261 exit 0;
263 ####################### primary functions ######################
264 sub usage {
265 my $exit = shift || 0;
266 my $fd = $exit ? \*STDERR : \*STDOUT;
267 print $fd <<"";
268 git-svn - bidirectional operations between a single Subversion tree and git
269 Usage: git svn <command> [options] [arguments]\n
271 print $fd "Available commands:\n" unless $cmd;
273 foreach (sort keys %cmd) {
274 next if $cmd && $cmd ne $_;
275 next if /^multi-/; # don't show deprecated commands
276 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
277 foreach (sort keys %{$cmd{$_}->[2]}) {
278 # mixed-case options are for .git/config only
279 next if /[A-Z]/ && /^[a-z]+$/i;
280 # prints out arguments as they should be passed:
281 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
282 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
283 "--$_" : "-$_" }
284 split /\|/,$_)," $x\n";
287 print $fd <<"";
288 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
289 arbitrary identifier if you're tracking multiple SVN branches/repositories in
290 one git repository and want to keep them separate. See git-svn(1) for more
291 information.
293 exit $exit;
296 sub version {
297 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
298 exit 0;
301 sub do_git_init_db {
302 unless (-d $ENV{GIT_DIR}) {
303 my @init_db = ('init');
304 push @init_db, "--template=$_template" if defined $_template;
305 if (defined $_shared) {
306 if ($_shared =~ /[a-z]/) {
307 push @init_db, "--shared=$_shared";
308 } else {
309 push @init_db, "--shared";
312 command_noisy(@init_db);
313 $_repository = Git->repository(Repository => ".git");
315 my $set;
316 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
317 foreach my $i (keys %icv) {
318 die "'$set' and '$i' cannot both be set\n" if $set;
319 next unless defined $icv{$i};
320 command_noisy('config', "$pfx.$i", $icv{$i});
321 $set = $i;
325 sub init_subdir {
326 my $repo_path = shift or return;
327 mkpath([$repo_path]) unless -d $repo_path;
328 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
329 $ENV{GIT_DIR} = '.git';
330 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
333 sub cmd_clone {
334 my ($url, $path) = @_;
335 if (!defined $path &&
336 (defined $_trunk || defined $_branches || defined $_tags ||
337 defined $_stdlayout) &&
338 $url !~ m#^[a-z\+]+://#) {
339 $path = $url;
341 $path = basename($url) if !defined $path || !length $path;
342 cmd_init($url, $path);
343 Git::SVN::fetch_all($Git::SVN::default_repo_id);
346 sub cmd_init {
347 if (defined $_stdlayout) {
348 $_trunk = 'trunk' if (!defined $_trunk);
349 $_tags = 'tags' if (!defined $_tags);
350 $_branches = 'branches' if (!defined $_branches);
352 if (defined $_trunk || defined $_branches || defined $_tags) {
353 return cmd_multi_init(@_);
355 my $url = shift or die "SVN repository location required ",
356 "as a command-line argument\n";
357 init_subdir(@_);
358 do_git_init_db();
360 Git::SVN->init($url);
363 sub cmd_fetch {
364 if (grep /^\d+=./, @_) {
365 die "'<rev>=<commit>' fetch arguments are ",
366 "no longer supported.\n";
368 my ($remote) = @_;
369 if (@_ > 1) {
370 die "Usage: $0 fetch [--all] [svn-remote]\n";
372 $remote ||= $Git::SVN::default_repo_id;
373 if ($_fetch_all) {
374 cmd_multi_fetch();
375 } else {
376 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
380 sub cmd_set_tree {
381 my (@commits) = @_;
382 if ($_stdin || !@commits) {
383 print "Reading from stdin...\n";
384 @commits = ();
385 while (<STDIN>) {
386 if (/\b($sha1_short)\b/o) {
387 unshift @commits, $1;
391 my @revs;
392 foreach my $c (@commits) {
393 my @tmp = command('rev-parse',$c);
394 if (scalar @tmp == 1) {
395 push @revs, $tmp[0];
396 } elsif (scalar @tmp > 1) {
397 push @revs, reverse(command('rev-list',@tmp));
398 } else {
399 fatal "Failed to rev-parse $c";
402 my $gs = Git::SVN->new;
403 my ($r_last, $cmt_last) = $gs->last_rev_commit;
404 $gs->fetch;
405 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
406 fatal "There are new revisions that were fetched ",
407 "and need to be merged (or acknowledged) ",
408 "before committing.\nlast rev: $r_last\n",
409 " current: $gs->{last_rev}";
411 $gs->set_tree($_) foreach @revs;
412 print "Done committing ",scalar @revs," revisions to SVN\n";
413 unlink $gs->{index};
416 sub cmd_dcommit {
417 my $head = shift;
418 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
419 'Cannot dcommit with a dirty index. Commit your changes first, '
420 . "or stash them with `git stash'.\n";
421 $head ||= 'HEAD';
422 my @refs;
423 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
424 unless ($gs) {
425 die "Unable to determine upstream SVN information from ",
426 "$head history.\nPerhaps the repository is empty.";
428 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
429 my $last_rev = $_revision if defined $_revision;
430 if ($url) {
431 print "Committing to $url ...\n";
433 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
434 if ($_no_rebase && scalar(@$linear_refs) > 1) {
435 warn "Attempting to commit more than one change while ",
436 "--no-rebase is enabled.\n",
437 "If these changes depend on each other, re-running ",
438 "without --no-rebase may be required."
440 my $expect_url = $url;
441 Git::SVN::remove_username($expect_url);
442 while (1) {
443 my $d = shift @$linear_refs or last;
444 unless (defined $last_rev) {
445 (undef, $last_rev, undef) = cmt_metadata("$d~1");
446 unless (defined $last_rev) {
447 fatal "Unable to extract revision information ",
448 "from commit $d~1";
451 if ($_dry_run) {
452 print "diff-tree $d~1 $d\n";
453 } else {
454 my $cmt_rev;
455 my %ed_opts = ( r => $last_rev,
456 log => get_commit_entry($d)->{log},
457 ra => Git::SVN::Ra->new($url),
458 config => SVN::Core::config_get_config(
459 $Git::SVN::Ra::config_dir
461 tree_a => "$d~1",
462 tree_b => $d,
463 editor_cb => sub {
464 print "Committed r$_[0]\n";
465 $cmt_rev = $_[0];
467 svn_path => '');
468 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
469 print "No changes\n$d~1 == $d\n";
470 } elsif ($parents->{$d} && @{$parents->{$d}}) {
471 $gs->{inject_parents_dcommit}->{$cmt_rev} =
472 $parents->{$d};
474 $_fetch_all ? $gs->fetch_all : $gs->fetch;
475 $last_rev = $cmt_rev;
476 next if $_no_rebase;
478 # we always want to rebase against the current HEAD,
479 # not any head that was passed to us
480 my @diff = command('diff-tree', $d,
481 $gs->refname, '--');
482 my @finish;
483 if (@diff) {
484 @finish = rebase_cmd();
485 print STDERR "W: $d and ", $gs->refname,
486 " differ, using @finish:\n",
487 join("\n", @diff), "\n";
488 } else {
489 print "No changes between current HEAD and ",
490 $gs->refname,
491 "\nResetting to the latest ",
492 $gs->refname, "\n";
493 @finish = qw/reset --mixed/;
495 command_noisy(@finish, $gs->refname);
496 if (@diff) {
497 @refs = ();
498 my ($url_, $rev_, $uuid_, $gs_) =
499 working_head_info($head, \@refs);
500 my ($linear_refs_, $parents_) =
501 linearize_history($gs_, \@refs);
502 if (scalar(@$linear_refs) !=
503 scalar(@$linear_refs_)) {
504 fatal "# of revisions changed ",
505 "\nbefore:\n",
506 join("\n", @$linear_refs),
507 "\n\nafter:\n",
508 join("\n", @$linear_refs_), "\n",
509 'If you are attempting to commit ',
510 "merges, try running:\n\t",
511 'git rebase --interactive',
512 '--preserve-merges ',
513 $gs->refname,
514 "\nBefore dcommitting";
516 if ($url_ ne $expect_url) {
517 fatal "URL mismatch after rebase: ",
518 "$url_ != $expect_url";
520 if ($uuid_ ne $uuid) {
521 fatal "uuid mismatch after rebase: ",
522 "$uuid_ != $uuid";
524 # remap parents
525 my (%p, @l, $i);
526 for ($i = 0; $i < scalar @$linear_refs; $i++) {
527 my $new = $linear_refs_->[$i] or next;
528 $p{$new} =
529 $parents->{$linear_refs->[$i]};
530 push @l, $new;
532 $parents = \%p;
533 $linear_refs = \@l;
537 unlink $gs->{index};
540 sub cmd_find_rev {
541 my $revision_or_hash = shift or die "SVN or git revision required ",
542 "as a command-line argument\n";
543 my $result;
544 if ($revision_or_hash =~ /^r\d+$/) {
545 my $head = shift;
546 $head ||= 'HEAD';
547 my @refs;
548 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
549 unless ($gs) {
550 die "Unable to determine upstream SVN information from ",
551 "$head history\n";
553 my $desired_revision = substr($revision_or_hash, 1);
554 $result = $gs->rev_map_get($desired_revision, $uuid);
555 } else {
556 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
557 $result = $rev;
559 print "$result\n" if $result;
562 sub cmd_rebase {
563 command_noisy(qw/update-index --refresh/);
564 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
565 unless ($gs) {
566 die "Unable to determine upstream SVN information from ",
567 "working tree history\n";
569 if ($_dry_run) {
570 print "Remote Branch: " . $gs->refname . "\n";
571 print "SVN URL: " . $url . "\n";
572 return;
574 if (command(qw/diff-index HEAD --/)) {
575 print STDERR "Cannot rebase with uncommited changes:\n";
576 command_noisy('status');
577 exit 1;
579 unless ($_local) {
580 # rebase will checkout for us, so no need to do it explicitly
581 $_no_checkout = 'true';
582 $_fetch_all ? $gs->fetch_all : $gs->fetch;
584 command_noisy(rebase_cmd(), $gs->refname);
587 sub cmd_show_ignore {
588 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
589 $gs ||= Git::SVN->new;
590 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
591 $gs->prop_walk($gs->{path}, $r, sub {
592 my ($gs, $path, $props) = @_;
593 print STDOUT "\n# $path\n";
594 my $s = $props->{'svn:ignore'} or return;
595 $s =~ s/[\r\n]+/\n/g;
596 chomp $s;
597 $s =~ s#^#$path#gm;
598 print STDOUT "$s\n";
602 sub cmd_show_externals {
603 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
604 $gs ||= Git::SVN->new;
605 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
606 $gs->prop_walk($gs->{path}, $r, sub {
607 my ($gs, $path, $props) = @_;
608 print STDOUT "\n# $path\n";
609 my $s = $props->{'svn:externals'} or return;
610 $s =~ s/[\r\n]+/\n/g;
611 chomp $s;
612 $s =~ s#^#$path#gm;
613 print STDOUT "$s\n";
617 sub cmd_create_ignore {
618 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
619 $gs ||= Git::SVN->new;
620 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
621 $gs->prop_walk($gs->{path}, $r, sub {
622 my ($gs, $path, $props) = @_;
623 # $path is of the form /path/to/dir/
624 my $ignore = '.' . $path . '.gitignore';
625 my $s = $props->{'svn:ignore'} or return;
626 open(GITIGNORE, '>', $ignore)
627 or fatal("Failed to open `$ignore' for writing: $!");
628 $s =~ s/[\r\n]+/\n/g;
629 chomp $s;
630 # Prefix all patterns so that the ignore doesn't apply
631 # to sub-directories.
632 $s =~ s#^#/#gm;
633 print GITIGNORE "$s\n";
634 close(GITIGNORE)
635 or fatal("Failed to close `$ignore': $!");
636 command_noisy('add', '-f', $ignore);
640 sub canonicalize_path {
641 my ($path) = @_;
642 my $dot_slash_added = 0;
643 if (substr($path, 0, 1) ne "/") {
644 $path = "./" . $path;
645 $dot_slash_added = 1;
647 # File::Spec->canonpath doesn't collapse x/../y into y (for a
648 # good reason), so let's do this manually.
649 $path =~ s#/+#/#g;
650 $path =~ s#/\.(?:/|$)#/#g;
651 $path =~ s#/[^/]+/\.\.##g;
652 $path =~ s#/$##g;
653 $path =~ s#^\./## if $dot_slash_added;
654 $path =~ s#^/##;
655 $path =~ s#^\.$##;
656 return $path;
659 # get_svnprops(PATH)
660 # ------------------
661 # Helper for cmd_propget and cmd_proplist below.
662 sub get_svnprops {
663 my $path = shift;
664 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
665 $gs ||= Git::SVN->new;
667 # prefix THE PATH by the sub-directory from which the user
668 # invoked us.
669 $path = $cmd_dir_prefix . $path;
670 fatal("No such file or directory: $path") unless -e $path;
671 my $is_dir = -d $path ? 1 : 0;
672 $path = $gs->{path} . '/' . $path;
674 # canonicalize the path (otherwise libsvn will abort or fail to
675 # find the file)
676 $path = canonicalize_path($path);
678 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
679 my $props;
680 if ($is_dir) {
681 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
683 else {
684 (undef, $props) = $gs->ra->get_file($path, $r, undef);
686 return $props;
689 # cmd_propget (PROP, PATH)
690 # ------------------------
691 # Print the SVN property PROP for PATH.
692 sub cmd_propget {
693 my ($prop, $path) = @_;
694 $path = '.' if not defined $path;
695 usage(1) if not defined $prop;
696 my $props = get_svnprops($path);
697 if (not defined $props->{$prop}) {
698 fatal("`$path' does not have a `$prop' SVN property.");
700 print $props->{$prop} . "\n";
703 # cmd_proplist (PATH)
704 # -------------------
705 # Print the list of SVN properties for PATH.
706 sub cmd_proplist {
707 my $path = shift;
708 $path = '.' if not defined $path;
709 my $props = get_svnprops($path);
710 print "Properties on '$path':\n";
711 foreach (sort keys %{$props}) {
712 print " $_\n";
716 sub cmd_multi_init {
717 my $url = shift;
718 unless (defined $_trunk || defined $_branches || defined $_tags) {
719 usage(1);
722 # there are currently some bugs that prevent multi-init/multi-fetch
723 # setups from working well without this.
724 $Git::SVN::_minimize_url = 1;
726 $_prefix = '' unless defined $_prefix;
727 if (defined $url) {
728 $url =~ s#/+$##;
729 init_subdir(@_);
731 do_git_init_db();
732 if (defined $_trunk) {
733 my $trunk_ref = $_prefix . 'trunk';
734 # try both old-style and new-style lookups:
735 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
736 unless ($gs_trunk) {
737 my ($trunk_url, $trunk_path) =
738 complete_svn_url($url, $_trunk);
739 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
740 undef, $trunk_ref);
743 return unless defined $_branches || defined $_tags;
744 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
745 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
746 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
749 sub cmd_multi_fetch {
750 my $remotes = Git::SVN::read_all_remotes();
751 foreach my $repo_id (sort keys %$remotes) {
752 if ($remotes->{$repo_id}->{url}) {
753 Git::SVN::fetch_all($repo_id, $remotes);
758 # this command is special because it requires no metadata
759 sub cmd_commit_diff {
760 my ($ta, $tb, $url) = @_;
761 my $usage = "Usage: $0 commit-diff -r<revision> ".
762 "<tree-ish> <tree-ish> [<URL>]";
763 fatal($usage) if (!defined $ta || !defined $tb);
764 my $svn_path = '';
765 if (!defined $url) {
766 my $gs = eval { Git::SVN->new };
767 if (!$gs) {
768 fatal("Needed URL or usable git-svn --id in ",
769 "the command-line\n", $usage);
771 $url = $gs->{url};
772 $svn_path = $gs->{path};
774 unless (defined $_revision) {
775 fatal("-r|--revision is a required argument\n", $usage);
777 if (defined $_message && defined $_file) {
778 fatal("Both --message/-m and --file/-F specified ",
779 "for the commit message.\n",
780 "I have no idea what you mean");
782 if (defined $_file) {
783 $_message = file_to_s($_file);
784 } else {
785 $_message ||= get_commit_entry($tb)->{log};
787 my $ra ||= Git::SVN::Ra->new($url);
788 my $r = $_revision;
789 if ($r eq 'HEAD') {
790 $r = $ra->get_latest_revnum;
791 } elsif ($r !~ /^\d+$/) {
792 die "revision argument: $r not understood by git-svn\n";
794 my %ed_opts = ( r => $r,
795 log => $_message,
796 ra => $ra,
797 tree_a => $ta,
798 tree_b => $tb,
799 editor_cb => sub { print "Committed r$_[0]\n" },
800 svn_path => $svn_path );
801 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
802 print "No changes\n$ta == $tb\n";
806 sub escape_uri_only {
807 my ($uri) = @_;
808 my @tmp;
809 foreach (split m{/}, $uri) {
810 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
811 push @tmp, $_;
813 join('/', @tmp);
816 sub escape_url {
817 my ($url) = @_;
818 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
819 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
820 $url = "$scheme://$domain$uri";
822 $url;
825 sub cmd_info {
826 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
827 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
828 if (exists $_[1]) {
829 die "Too many arguments specified\n";
832 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
834 if (!$file_type && !$diff_status) {
835 print STDERR "svn: '$path' is not under version control\n";
836 exit 1;
839 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
840 unless ($gs) {
841 die "Unable to determine upstream SVN information from ",
842 "working tree history\n";
845 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
846 $path = "." if $path eq "";
848 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
850 if ($_url) {
851 print escape_url($full_url), "\n";
852 return;
855 my $result = "Path: $path\n";
856 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
857 $result .= "URL: " . escape_url($full_url) . "\n";
859 eval {
860 my $repos_root = $gs->repos_root;
861 Git::SVN::remove_username($repos_root);
862 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
864 if ($@) {
865 $result .= "Repository Root: (offline)\n";
867 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
868 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
870 $result .= "Node Kind: " .
871 ($file_type eq "dir" ? "directory" : "file") . "\n";
873 my $schedule = $diff_status eq "A"
874 ? "add"
875 : ($diff_status eq "D" ? "delete" : "normal");
876 $result .= "Schedule: $schedule\n";
878 if ($diff_status eq "A") {
879 print $result, "\n";
880 return;
883 my ($lc_author, $lc_rev, $lc_date_utc);
884 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
885 my $log = command_output_pipe(@args);
886 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
887 while (<$log>) {
888 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
889 $lc_author = $1;
890 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
891 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
892 (undef, $lc_rev, undef) = ::extract_metadata($1);
895 close $log;
897 Git::SVN::Log::set_local_timezone();
899 $result .= "Last Changed Author: $lc_author\n";
900 $result .= "Last Changed Rev: $lc_rev\n";
901 $result .= "Last Changed Date: " .
902 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
904 if ($file_type ne "dir") {
905 my $text_last_updated_date =
906 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
907 $result .=
908 "Text Last Updated: " .
909 Git::SVN::Log::format_svn_date($text_last_updated_date) .
910 "\n";
911 my $checksum;
912 if ($diff_status eq "D") {
913 my ($fh, $ctx) =
914 command_output_pipe(qw(cat-file blob), "HEAD:$path");
915 if ($file_type eq "link") {
916 my $file_name = <$fh>;
917 $checksum = md5sum("link $file_name");
918 } else {
919 $checksum = md5sum($fh);
921 command_close_pipe($fh, $ctx);
922 } elsif ($file_type eq "link") {
923 my $file_name =
924 command(qw(cat-file blob), "HEAD:$path");
925 $checksum =
926 md5sum("link " . $file_name);
927 } else {
928 open FILE, "<", $path or die $!;
929 $checksum = md5sum(\*FILE);
930 close FILE or die $!;
932 $result .= "Checksum: " . $checksum . "\n";
935 print $result, "\n";
938 ########################### utility functions #########################
940 sub rebase_cmd {
941 my @cmd = qw/rebase/;
942 push @cmd, '-v' if $_verbose;
943 push @cmd, qw/--merge/ if $_merge;
944 push @cmd, "--strategy=$_strategy" if $_strategy;
945 @cmd;
948 sub post_fetch_checkout {
949 return if $_no_checkout;
950 my $gs = $Git::SVN::_head or return;
951 return if verify_ref('refs/heads/master^0');
953 my $valid_head = verify_ref('HEAD^0');
954 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
955 return if ($valid_head || !verify_ref('HEAD^0'));
957 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
958 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
959 return if -f $index;
961 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
962 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
963 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
964 print STDERR "Checked out HEAD:\n ",
965 $gs->full_url, " r", $gs->last_rev, "\n";
968 sub complete_svn_url {
969 my ($url, $path) = @_;
970 $path =~ s#/+$##;
971 if ($path !~ m#^[a-z\+]+://#) {
972 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
973 fatal("E: '$path' is not a complete URL ",
974 "and a separate URL is not specified");
976 return ($url, $path);
978 return ($path, '');
981 sub complete_url_ls_init {
982 my ($ra, $repo_path, $switch, $pfx) = @_;
983 unless ($repo_path) {
984 print STDERR "W: $switch not specified\n";
985 return;
987 $repo_path =~ s#/+$##;
988 if ($repo_path =~ m#^[a-z\+]+://#) {
989 $ra = Git::SVN::Ra->new($repo_path);
990 $repo_path = '';
991 } else {
992 $repo_path =~ s#^/+##;
993 unless ($ra) {
994 fatal("E: '$repo_path' is not a complete URL ",
995 "and a separate URL is not specified");
998 my $url = $ra->{url};
999 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1000 my $k = "svn-remote.$gs->{repo_id}.url";
1001 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1002 if ($orig_url && ($orig_url ne $gs->{url})) {
1003 die "$k already set: $orig_url\n",
1004 "wanted to set to: $gs->{url}\n";
1006 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1007 my $remote_path = "$ra->{svn_path}/$repo_path";
1008 $remote_path =~ s#/+#/#g;
1009 $remote_path =~ s#^/##g;
1010 $remote_path .= "/*" if $remote_path !~ /\*/;
1011 my ($n) = ($switch =~ /^--(\w+)/);
1012 if (length $pfx && $pfx !~ m#/$#) {
1013 die "--prefix='$pfx' must have a trailing slash '/'\n";
1015 command_noisy('config',
1016 "svn-remote.$gs->{repo_id}.$n",
1017 "$remote_path:refs/remotes/$pfx*" .
1018 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1021 sub verify_ref {
1022 my ($ref) = @_;
1023 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1024 { STDERR => 0 }); };
1027 sub get_tree_from_treeish {
1028 my ($treeish) = @_;
1029 # $treeish can be a symbolic ref, too:
1030 my $type = command_oneline(qw/cat-file -t/, $treeish);
1031 my $expected;
1032 while ($type eq 'tag') {
1033 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1035 if ($type eq 'commit') {
1036 $expected = (grep /^tree /, command(qw/cat-file commit/,
1037 $treeish))[0];
1038 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1039 die "Unable to get tree from $treeish\n" unless $expected;
1040 } elsif ($type eq 'tree') {
1041 $expected = $treeish;
1042 } else {
1043 die "$treeish is a $type, expected tree, tag or commit\n";
1045 return $expected;
1048 sub get_commit_entry {
1049 my ($treeish) = shift;
1050 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1051 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1052 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1053 open my $log_fh, '>', $commit_editmsg or croak $!;
1055 my $type = command_oneline(qw/cat-file -t/, $treeish);
1056 if ($type eq 'commit' || $type eq 'tag') {
1057 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1058 $type, $treeish);
1059 my $in_msg = 0;
1060 my $author;
1061 my $saw_from = 0;
1062 my $msgbuf = "";
1063 while (<$msg_fh>) {
1064 if (!$in_msg) {
1065 $in_msg = 1 if (/^\s*$/);
1066 $author = $1 if (/^author (.*>)/);
1067 } elsif (/^git-svn-id: /) {
1068 # skip this for now, we regenerate the
1069 # correct one on re-fetch anyways
1070 # TODO: set *:merge properties or like...
1071 } else {
1072 if (/^From:/ || /^Signed-off-by:/) {
1073 $saw_from = 1;
1075 $msgbuf .= $_;
1078 $msgbuf =~ s/\s+$//s;
1079 if ($Git::SVN::_add_author_from && defined($author)
1080 && !$saw_from) {
1081 $msgbuf .= "\n\nFrom: $author";
1083 print $log_fh $msgbuf or croak $!;
1084 command_close_pipe($msg_fh, $ctx);
1086 close $log_fh or croak $!;
1088 if ($_edit || ($type eq 'tree')) {
1089 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1090 # TODO: strip out spaces, comments, like git-commit.sh
1091 system($editor, $commit_editmsg);
1093 rename $commit_editmsg, $commit_msg or croak $!;
1094 open $log_fh, '<', $commit_msg or croak $!;
1095 { local $/; chomp($log_entry{log} = <$log_fh>); }
1096 close $log_fh or croak $!;
1097 unlink $commit_msg;
1098 \%log_entry;
1101 sub s_to_file {
1102 my ($str, $file, $mode) = @_;
1103 open my $fd,'>',$file or croak $!;
1104 print $fd $str,"\n" or croak $!;
1105 close $fd or croak $!;
1106 chmod ($mode &~ umask, $file) if (defined $mode);
1109 sub file_to_s {
1110 my $file = shift;
1111 open my $fd,'<',$file or croak "$!: file: $file\n";
1112 local $/;
1113 my $ret = <$fd>;
1114 close $fd or croak $!;
1115 $ret =~ s/\s*$//s;
1116 return $ret;
1119 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1120 sub load_authors {
1121 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1122 my $log = $cmd eq 'log';
1123 while (<$authors>) {
1124 chomp;
1125 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1126 my ($user, $name, $email) = ($1, $2, $3);
1127 if ($log) {
1128 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1129 } else {
1130 $users{$user} = [$name, $email];
1133 close $authors or croak $!;
1136 # convert GetOpt::Long specs for use by git-config
1137 sub read_repo_config {
1138 return unless -d $ENV{GIT_DIR};
1139 my $opts = shift;
1140 my @config_only;
1141 foreach my $o (keys %$opts) {
1142 # if we have mixedCase and a long option-only, then
1143 # it's a config-only variable that we don't need for
1144 # the command-line.
1145 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1146 my $v = $opts->{$o};
1147 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1148 $key =~ s/-//g;
1149 my $arg = 'git-config';
1150 $arg .= ' --int' if ($o =~ /[:=]i$/);
1151 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1152 if (ref $v eq 'ARRAY') {
1153 chomp(my @tmp = `$arg --get-all svn.$key`);
1154 @$v = @tmp if @tmp;
1155 } else {
1156 chomp(my $tmp = `$arg --get svn.$key`);
1157 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1158 $$v = $tmp;
1162 delete @$opts{@config_only} if @config_only;
1165 sub extract_metadata {
1166 my $id = shift or return (undef, undef, undef);
1167 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1168 \s([a-f\d\-]+)$/x);
1169 if (!defined $rev || !$uuid || !$url) {
1170 # some of the original repositories I made had
1171 # identifiers like this:
1172 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1174 return ($url, $rev, $uuid);
1177 sub cmt_metadata {
1178 return extract_metadata((grep(/^git-svn-id: /,
1179 command(qw/cat-file commit/, shift)))[-1]);
1182 sub working_head_info {
1183 my ($head, $refs) = @_;
1184 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1185 my ($fh, $ctx) = command_output_pipe(@args, $head);
1186 my $hash;
1187 my %max;
1188 while (<$fh>) {
1189 if ( m{^commit ($::sha1)$} ) {
1190 unshift @$refs, $hash if $hash and $refs;
1191 $hash = $1;
1192 next;
1194 next unless s{^\s*(git-svn-id:)}{$1};
1195 my ($url, $rev, $uuid) = extract_metadata($_);
1196 if (defined $url && defined $rev) {
1197 next if $max{$url} and $max{$url} < $rev;
1198 if (my $gs = Git::SVN->find_by_url($url)) {
1199 my $c = $gs->rev_map_get($rev, $uuid);
1200 if ($c && $c eq $hash) {
1201 close $fh; # break the pipe
1202 return ($url, $rev, $uuid, $gs);
1203 } else {
1204 $max{$url} ||= $gs->rev_map_max;
1209 command_close_pipe($fh, $ctx);
1210 (undef, undef, undef, undef);
1213 sub read_commit_parents {
1214 my ($parents, $c) = @_;
1215 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1216 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1217 @{$parents->{$c}} = split(/ /, $p);
1220 sub linearize_history {
1221 my ($gs, $refs) = @_;
1222 my %parents;
1223 foreach my $c (@$refs) {
1224 read_commit_parents(\%parents, $c);
1227 my @linear_refs;
1228 my %skip = ();
1229 my $last_svn_commit = $gs->last_commit;
1230 foreach my $c (reverse @$refs) {
1231 next if $c eq $last_svn_commit;
1232 last if $skip{$c};
1234 unshift @linear_refs, $c;
1235 $skip{$c} = 1;
1237 # we only want the first parent to diff against for linear
1238 # history, we save the rest to inject when we finalize the
1239 # svn commit
1240 my $fp_a = verify_ref("$c~1");
1241 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1242 if (!$fp_a || !$fp_b) {
1243 die "Commit $c\n",
1244 "has no parent commit, and therefore ",
1245 "nothing to diff against.\n",
1246 "You should be working from a repository ",
1247 "originally created by git-svn\n";
1249 if ($fp_a ne $fp_b) {
1250 die "$c~1 = $fp_a, however parsing commit $c ",
1251 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1254 foreach my $p (@{$parents{$c}}) {
1255 $skip{$p} = 1;
1258 (\@linear_refs, \%parents);
1261 sub find_file_type_and_diff_status {
1262 my ($path) = @_;
1263 return ('dir', '') if $path eq '';
1265 my $diff_output =
1266 command_oneline(qw(diff --cached --name-status --), $path) || "";
1267 my $diff_status = (split(' ', $diff_output))[0] || "";
1269 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1271 return (undef, undef) if !$diff_status && !$ls_tree;
1273 if ($diff_status eq "A") {
1274 return ("link", $diff_status) if -l $path;
1275 return ("dir", $diff_status) if -d $path;
1276 return ("file", $diff_status);
1279 my $mode = (split(' ', $ls_tree))[0] || "";
1281 return ("link", $diff_status) if $mode eq "120000";
1282 return ("dir", $diff_status) if $mode eq "040000";
1283 return ("file", $diff_status);
1286 sub md5sum {
1287 my $arg = shift;
1288 my $ref = ref $arg;
1289 my $md5 = Digest::MD5->new();
1290 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1291 $md5->addfile($arg) or croak $!;
1292 } elsif ($ref eq 'SCALAR') {
1293 $md5->add($$arg) or croak $!;
1294 } elsif (!$ref) {
1295 $md5->add($arg) or croak $!;
1296 } else {
1297 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1299 return $md5->hexdigest();
1302 package Git::SVN;
1303 use strict;
1304 use warnings;
1305 use Fcntl qw/:DEFAULT :seek/;
1306 use constant rev_map_fmt => 'NH40';
1307 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1308 $_repack $_repack_flags $_use_svm_props $_head
1309 $_use_svnsync_props $no_reuse_existing $_minimize_url
1310 $_use_log_author $_add_author_from/;
1311 use Carp qw/croak/;
1312 use File::Path qw/mkpath/;
1313 use File::Copy qw/copy/;
1314 use IPC::Open3;
1316 my ($_gc_nr, $_gc_period);
1318 # properties that we do not log:
1319 my %SKIP_PROP;
1320 BEGIN {
1321 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1322 svn:special svn:executable
1323 svn:entry:committed-rev
1324 svn:entry:last-author
1325 svn:entry:uuid
1326 svn:entry:committed-date/;
1328 # some options are read globally, but can be overridden locally
1329 # per [svn-remote "..."] section. Command-line options will *NOT*
1330 # override options set in an [svn-remote "..."] section
1331 no strict 'refs';
1332 for my $option (qw/follow_parent no_metadata use_svm_props
1333 use_svnsync_props/) {
1334 my $key = $option;
1335 $key =~ tr/_//d;
1336 my $prop = "-$option";
1337 *$option = sub {
1338 my ($self) = @_;
1339 return $self->{$prop} if exists $self->{$prop};
1340 my $k = "svn-remote.$self->{repo_id}.$key";
1341 eval { command_oneline(qw/config --get/, $k) };
1342 if ($@) {
1343 $self->{$prop} = ${"Git::SVN::_$option"};
1344 } else {
1345 my $v = command_oneline(qw/config --bool/,$k);
1346 $self->{$prop} = $v eq 'false' ? 0 : 1;
1348 return $self->{$prop};
1354 my (%LOCKFILES, %INDEX_FILES);
1355 END {
1356 unlink keys %LOCKFILES if %LOCKFILES;
1357 unlink keys %INDEX_FILES if %INDEX_FILES;
1360 sub resolve_local_globs {
1361 my ($url, $fetch, $glob_spec) = @_;
1362 return unless defined $glob_spec;
1363 my $ref = $glob_spec->{ref};
1364 my $path = $glob_spec->{path};
1365 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1366 next unless m#^refs/remotes/$ref->{regex}$#;
1367 my $p = $1;
1368 my $pathname = desanitize_refname($path->full_path($p));
1369 my $refname = desanitize_refname($ref->full_path($p));
1370 if (my $existing = $fetch->{$pathname}) {
1371 if ($existing ne $refname) {
1372 die "Refspec conflict:\n",
1373 "existing: refs/remotes/$existing\n",
1374 " globbed: refs/remotes/$refname\n";
1376 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1377 $u =~ s!^\Q$url\E(/|$)!! or die
1378 "refs/remotes/$refname: '$url' not found in '$u'\n";
1379 if ($pathname ne $u) {
1380 warn "W: Refspec glob conflict ",
1381 "(ref: refs/remotes/$refname):\n",
1382 "expected path: $pathname\n",
1383 " real path: $u\n",
1384 "Continuing ahead with $u\n";
1385 next;
1387 } else {
1388 $fetch->{$pathname} = $refname;
1393 sub parse_revision_argument {
1394 my ($base, $head) = @_;
1395 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1396 return ($base, $head);
1398 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1399 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1400 return ($head, $head) if ($::_revision eq 'HEAD');
1401 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1402 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1403 die "revision argument: $::_revision not understood by git-svn\n";
1406 sub fetch_all {
1407 my ($repo_id, $remotes) = @_;
1408 if (ref $repo_id) {
1409 my $gs = $repo_id;
1410 $repo_id = undef;
1411 $repo_id = $gs->{repo_id};
1413 $remotes ||= read_all_remotes();
1414 my $remote = $remotes->{$repo_id} or
1415 die "[svn-remote \"$repo_id\"] unknown\n";
1416 my $fetch = $remote->{fetch};
1417 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1418 my (@gs, @globs);
1419 my $ra = Git::SVN::Ra->new($url);
1420 my $uuid = $ra->get_uuid;
1421 my $head = $ra->get_latest_revnum;
1422 my $base = defined $fetch ? $head : 0;
1424 # read the max revs for wildcard expansion (branches/*, tags/*)
1425 foreach my $t (qw/branches tags/) {
1426 defined $remote->{$t} or next;
1427 push @globs, $remote->{$t};
1428 my $max_rev = eval { tmp_config(qw/--int --get/,
1429 "svn-remote.$repo_id.${t}-maxRev") };
1430 if (defined $max_rev && ($max_rev < $base)) {
1431 $base = $max_rev;
1432 } elsif (!defined $max_rev) {
1433 $base = 0;
1437 if ($fetch) {
1438 foreach my $p (sort keys %$fetch) {
1439 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1440 my $lr = $gs->rev_map_max;
1441 if (defined $lr) {
1442 $base = $lr if ($lr < $base);
1444 push @gs, $gs;
1448 ($base, $head) = parse_revision_argument($base, $head);
1449 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1452 sub read_all_remotes {
1453 my $r = {};
1454 my $use_svm_props = eval { command_oneline(qw/config --bool
1455 svn.useSvmProps/) };
1456 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1457 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1458 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1459 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1460 die("svn-remote.$remote: remote ref '$_remote_ref' "
1461 . "must start with 'refs/remotes/'\n")
1462 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1463 my $remote_ref = $1;
1464 $local_ref =~ s{^/}{};
1465 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1466 $r->{$remote}->{svm} = {} if $use_svm_props;
1467 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1468 $r->{$1}->{svm} = {};
1469 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1470 $r->{$1}->{url} = $2;
1471 } elsif (m!^(.+)\.(branches|tags)=
1472 (.*):refs/remotes/(.+)\s*$/!x) {
1473 my ($p, $g) = ($3, $4);
1474 my $rs = $r->{$1}->{$2} = {
1475 t => $2,
1476 remote => $1,
1477 path => Git::SVN::GlobSpec->new($p),
1478 ref => Git::SVN::GlobSpec->new($g) };
1479 if (length($rs->{ref}->{right}) != 0) {
1480 die "The '*' glob character must be the last ",
1481 "character of '$g'\n";
1486 map {
1487 if (defined $r->{$_}->{svm}) {
1488 my $svm;
1489 eval {
1490 my $section = "svn-remote.$_";
1491 $svm = {
1492 source => tmp_config('--get',
1493 "$section.svm-source"),
1494 replace => tmp_config('--get',
1495 "$section.svm-replace"),
1498 $r->{$_}->{svm} = $svm;
1500 } keys %$r;
1505 sub init_vars {
1506 $_gc_nr = $_gc_period = 1000;
1507 if (defined $_repack || defined $_repack_flags) {
1508 warn "Repack options are obsolete; they have no effect.\n";
1512 sub verify_remotes_sanity {
1513 return unless -d $ENV{GIT_DIR};
1514 my %seen;
1515 foreach (command(qw/config -l/)) {
1516 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1517 if ($seen{$1}) {
1518 die "Remote ref refs/remote/$1 is tracked by",
1519 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1520 "Please resolve this ambiguity in ",
1521 "your git configuration file before ",
1522 "continuing\n";
1524 $seen{$1} = $_;
1529 sub find_existing_remote {
1530 my ($url, $remotes) = @_;
1531 return undef if $no_reuse_existing;
1532 my $existing;
1533 foreach my $repo_id (keys %$remotes) {
1534 my $u = $remotes->{$repo_id}->{url} or next;
1535 next if $u ne $url;
1536 $existing = $repo_id;
1537 last;
1539 $existing;
1542 sub init_remote_config {
1543 my ($self, $url, $no_write) = @_;
1544 $url =~ s!/+$!!; # strip trailing slash
1545 my $r = read_all_remotes();
1546 my $existing = find_existing_remote($url, $r);
1547 if ($existing) {
1548 unless ($no_write) {
1549 print STDERR "Using existing ",
1550 "[svn-remote \"$existing\"]\n";
1552 $self->{repo_id} = $existing;
1553 } elsif ($_minimize_url) {
1554 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1555 $existing = find_existing_remote($min_url, $r);
1556 if ($existing) {
1557 unless ($no_write) {
1558 print STDERR "Using existing ",
1559 "[svn-remote \"$existing\"]\n";
1561 $self->{repo_id} = $existing;
1563 if ($min_url ne $url) {
1564 unless ($no_write) {
1565 print STDERR "Using higher level of URL: ",
1566 "$url => $min_url\n";
1568 my $old_path = $self->{path};
1569 $self->{path} = $url;
1570 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1571 if (length $old_path) {
1572 $self->{path} .= "/$old_path";
1574 $url = $min_url;
1577 my $orig_url;
1578 if (!$existing) {
1579 # verify that we aren't overwriting anything:
1580 $orig_url = eval {
1581 command_oneline('config', '--get',
1582 "svn-remote.$self->{repo_id}.url")
1584 if ($orig_url && ($orig_url ne $url)) {
1585 die "svn-remote.$self->{repo_id}.url already set: ",
1586 "$orig_url\nwanted to set to: $url\n";
1589 my ($xrepo_id, $xpath) = find_ref($self->refname);
1590 if (defined $xpath) {
1591 die "svn-remote.$xrepo_id.fetch already set to track ",
1592 "$xpath:refs/remotes/", $self->refname, "\n";
1594 unless ($no_write) {
1595 command_noisy('config',
1596 "svn-remote.$self->{repo_id}.url", $url);
1597 $self->{path} =~ s{^/}{};
1598 command_noisy('config', '--add',
1599 "svn-remote.$self->{repo_id}.fetch",
1600 "$self->{path}:".$self->refname);
1602 $self->{url} = $url;
1605 sub find_by_url { # repos_root and, path are optional
1606 my ($class, $full_url, $repos_root, $path) = @_;
1608 return undef unless defined $full_url;
1609 remove_username($full_url);
1610 remove_username($repos_root) if defined $repos_root;
1611 my $remotes = read_all_remotes();
1612 if (defined $full_url && defined $repos_root && !defined $path) {
1613 $path = $full_url;
1614 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1616 foreach my $repo_id (keys %$remotes) {
1617 my $u = $remotes->{$repo_id}->{url} or next;
1618 remove_username($u);
1619 next if defined $repos_root && $repos_root ne $u;
1621 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1622 foreach (qw/branches tags/) {
1623 resolve_local_globs($u, $fetch,
1624 $remotes->{$repo_id}->{$_});
1626 my $p = $path;
1627 my $rwr = rewrite_root({repo_id => $repo_id});
1628 my $svm = $remotes->{$repo_id}->{svm}
1629 if defined $remotes->{$repo_id}->{svm};
1630 unless (defined $p) {
1631 $p = $full_url;
1632 my $z = $u;
1633 my $prefix = '';
1634 if ($rwr) {
1635 $z = $rwr;
1636 } elsif (defined $svm) {
1637 $z = $svm->{source};
1638 $prefix = $svm->{replace};
1639 $prefix =~ s#^\Q$u\E(?:/|$)##;
1640 $prefix =~ s#/$##;
1642 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1644 foreach my $f (keys %$fetch) {
1645 next if $f ne $p;
1646 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1649 undef;
1652 sub init {
1653 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1654 my $self = _new($class, $repo_id, $ref_id, $path);
1655 if (defined $url) {
1656 $self->init_remote_config($url, $no_write);
1658 $self;
1661 sub find_ref {
1662 my ($ref_id) = @_;
1663 foreach (command(qw/config -l/)) {
1664 next unless m!^svn-remote\.(.+)\.fetch=
1665 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1666 my ($repo_id, $path, $ref) = ($1, $2, $3);
1667 if ($ref eq $ref_id) {
1668 $path = '' if ($path =~ m#^\./?#);
1669 return ($repo_id, $path);
1672 (undef, undef, undef);
1675 sub new {
1676 my ($class, $ref_id, $repo_id, $path) = @_;
1677 if (defined $ref_id && !defined $repo_id && !defined $path) {
1678 ($repo_id, $path) = find_ref($ref_id);
1679 if (!defined $repo_id) {
1680 die "Could not find a \"svn-remote.*.fetch\" key ",
1681 "in the repository configuration matching: ",
1682 "refs/remotes/$ref_id\n";
1685 my $self = _new($class, $repo_id, $ref_id, $path);
1686 if (!defined $self->{path} || !length $self->{path}) {
1687 my $fetch = command_oneline('config', '--get',
1688 "svn-remote.$repo_id.fetch",
1689 ":refs/remotes/$ref_id\$") or
1690 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1691 "\":refs/remotes/$ref_id\$\" in config\n";
1692 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1694 $self->{url} = command_oneline('config', '--get',
1695 "svn-remote.$repo_id.url") or
1696 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1697 $self->rebuild;
1698 $self;
1701 sub refname {
1702 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1704 # It cannot end with a slash /, we'll throw up on this because
1705 # SVN can't have directories with a slash in their name, either:
1706 if ($refname =~ m{/$}) {
1707 die "ref: '$refname' ends with a trailing slash, this is ",
1708 "not permitted by git nor Subversion\n";
1711 # It cannot have ASCII control character space, tilde ~, caret ^,
1712 # colon :, question-mark ?, asterisk *, space, or open bracket [
1713 # anywhere.
1715 # Additionally, % must be escaped because it is used for escaping
1716 # and we want our escaped refname to be reversible
1717 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1719 # no slash-separated component can begin with a dot .
1720 # /.* becomes /%2E*
1721 $refname =~ s{/\.}{/%2E}g;
1723 # It cannot have two consecutive dots .. anywhere
1724 # .. becomes %2E%2E
1725 $refname =~ s{\.\.}{%2E%2E}g;
1727 return $refname;
1730 sub desanitize_refname {
1731 my ($refname) = @_;
1732 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1733 return $refname;
1736 sub svm_uuid {
1737 my ($self) = @_;
1738 return $self->{svm}->{uuid} if $self->svm;
1739 $self->ra;
1740 unless ($self->{svm}) {
1741 die "SVM UUID not cached, and reading remotely failed\n";
1743 $self->{svm}->{uuid};
1746 sub svm {
1747 my ($self) = @_;
1748 return $self->{svm} if $self->{svm};
1749 my $svm;
1750 # see if we have it in our config, first:
1751 eval {
1752 my $section = "svn-remote.$self->{repo_id}";
1753 $svm = {
1754 source => tmp_config('--get', "$section.svm-source"),
1755 uuid => tmp_config('--get', "$section.svm-uuid"),
1756 replace => tmp_config('--get', "$section.svm-replace"),
1759 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1760 $self->{svm} = $svm;
1762 $self->{svm};
1765 sub _set_svm_vars {
1766 my ($self, $ra) = @_;
1767 return $ra if $self->svm;
1769 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1770 "(svm:source, svm:uuid) ",
1771 "from the following URLs:\n" );
1772 sub read_svm_props {
1773 my ($self, $ra, $path, $r) = @_;
1774 my $props = ($ra->get_dir($path, $r))[2];
1775 my $src = $props->{'svm:source'};
1776 my $uuid = $props->{'svm:uuid'};
1777 return undef if (!$src || !$uuid);
1779 chomp($src, $uuid);
1781 $uuid =~ m{^[0-9a-f\-]{30,}$}
1782 or die "doesn't look right - svm:uuid is '$uuid'\n";
1784 # the '!' is used to mark the repos_root!/relative/path
1785 $src =~ s{/?!/?}{/};
1786 $src =~ s{/+$}{}; # no trailing slashes please
1787 # username is of no interest
1788 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1790 my $replace = $ra->{url};
1791 $replace .= "/$path" if length $path;
1793 my $section = "svn-remote.$self->{repo_id}";
1794 tmp_config("$section.svm-source", $src);
1795 tmp_config("$section.svm-replace", $replace);
1796 tmp_config("$section.svm-uuid", $uuid);
1797 $self->{svm} = {
1798 source => $src,
1799 uuid => $uuid,
1800 replace => $replace
1804 my $r = $ra->get_latest_revnum;
1805 my $path = $self->{path};
1806 my %tried;
1807 while (length $path) {
1808 unless ($tried{"$self->{url}/$path"}) {
1809 return $ra if $self->read_svm_props($ra, $path, $r);
1810 $tried{"$self->{url}/$path"} = 1;
1812 $path =~ s#/?[^/]+$##;
1814 die "Path: '$path' should be ''\n" if $path ne '';
1815 return $ra if $self->read_svm_props($ra, $path, $r);
1816 $tried{"$self->{url}/$path"} = 1;
1818 if ($ra->{repos_root} eq $self->{url}) {
1819 die @err, (map { " $_\n" } keys %tried), "\n";
1822 # nope, make sure we're connected to the repository root:
1823 my $ok;
1824 my @tried_b;
1825 $path = $ra->{svn_path};
1826 $ra = Git::SVN::Ra->new($ra->{repos_root});
1827 while (length $path) {
1828 unless ($tried{"$ra->{url}/$path"}) {
1829 $ok = $self->read_svm_props($ra, $path, $r);
1830 last if $ok;
1831 $tried{"$ra->{url}/$path"} = 1;
1833 $path =~ s#/?[^/]+$##;
1835 die "Path: '$path' should be ''\n" if $path ne '';
1836 $ok ||= $self->read_svm_props($ra, $path, $r);
1837 $tried{"$ra->{url}/$path"} = 1;
1838 if (!$ok) {
1839 die @err, (map { " $_\n" } keys %tried), "\n";
1841 Git::SVN::Ra->new($self->{url});
1844 sub svnsync {
1845 my ($self) = @_;
1846 return $self->{svnsync} if $self->{svnsync};
1848 if ($self->no_metadata) {
1849 die "Can't have both 'noMetadata' and ",
1850 "'useSvnsyncProps' options set!\n";
1852 if ($self->rewrite_root) {
1853 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1854 "options set!\n";
1857 my $svnsync;
1858 # see if we have it in our config, first:
1859 eval {
1860 my $section = "svn-remote.$self->{repo_id}";
1862 my $url = tmp_config('--get', "$section.svnsync-url");
1863 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1864 die "doesn't look right - svn:sync-from-url is '$url'\n";
1866 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1867 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1868 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1870 $svnsync = { url => $url, uuid => $uuid }
1872 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1873 return $self->{svnsync} = $svnsync;
1876 my $err = "useSvnsyncProps set, but failed to read " .
1877 "svnsync property: svn:sync-from-";
1878 my $rp = $self->ra->rev_proplist(0);
1880 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1881 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1882 die "doesn't look right - svn:sync-from-url is '$url'\n";
1884 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1885 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1886 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1888 my $section = "svn-remote.$self->{repo_id}";
1889 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1890 tmp_config('--add', "$section.svnsync-url", $url);
1891 return $self->{svnsync} = { url => $url, uuid => $uuid };
1894 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1895 # remote lookup (useful for 'git svn log').
1896 sub ra_uuid {
1897 my ($self) = @_;
1898 unless ($self->{ra_uuid}) {
1899 my $key = "svn-remote.$self->{repo_id}.uuid";
1900 my $uuid = eval { tmp_config('--get', $key) };
1901 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1902 $self->{ra_uuid} = $uuid;
1903 } else {
1904 die "ra_uuid called without URL\n" unless $self->{url};
1905 $self->{ra_uuid} = $self->ra->get_uuid;
1906 tmp_config('--add', $key, $self->{ra_uuid});
1909 $self->{ra_uuid};
1912 sub _set_repos_root {
1913 my ($self, $repos_root) = @_;
1914 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1915 $repos_root ||= $self->ra->{repos_root};
1916 tmp_config($k, $repos_root);
1917 $repos_root;
1920 sub repos_root {
1921 my ($self) = @_;
1922 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1923 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1926 sub ra {
1927 my ($self) = shift;
1928 my $ra = Git::SVN::Ra->new($self->{url});
1929 $self->_set_repos_root($ra->{repos_root});
1930 if ($self->use_svm_props && !$self->{svm}) {
1931 if ($self->no_metadata) {
1932 die "Can't have both 'noMetadata' and ",
1933 "'useSvmProps' options set!\n";
1934 } elsif ($self->use_svnsync_props) {
1935 die "Can't have both 'useSvnsyncProps' and ",
1936 "'useSvmProps' options set!\n";
1938 $ra = $self->_set_svm_vars($ra);
1939 $self->{-want_revprops} = 1;
1941 $ra;
1944 sub rel_path {
1945 my ($self) = @_;
1946 my $repos_root = $self->ra->{repos_root};
1947 return $self->{path} if ($self->{url} eq $repos_root);
1948 my $url = $self->{url} .
1949 (length $self->{path} ? "/$self->{path}" : $self->{path});
1950 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1951 $url;
1954 # prop_walk(PATH, REV, SUB)
1955 # -------------------------
1956 # Recursively traverse PATH at revision REV and invoke SUB for each
1957 # directory that contains a SVN property. SUB will be invoked as
1958 # follows: &SUB(gs, path, props); where `gs' is this instance of
1959 # Git::SVN, `path' the path to the directory where the properties
1960 # `props' were found. The `path' will be relative to point of checkout,
1961 # that is, if url://repo/trunk is the current Git branch, and that
1962 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1963 # as `path' (note the trailing `/').
1964 sub prop_walk {
1965 my ($self, $path, $rev, $sub) = @_;
1967 $path =~ s#^/##;
1968 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1969 $path =~ s#^/*#/#g;
1970 my $p = $path;
1971 # Strip the irrelevant part of the path.
1972 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1973 # Ensure the path is terminated by a `/'.
1974 $p =~ s#/*$#/#;
1976 # The properties contain all the internal SVN stuff nobody
1977 # (usually) cares about.
1978 my $interesting_props = 0;
1979 foreach (keys %{$props}) {
1980 # If it doesn't start with `svn:', it must be a
1981 # user-defined property.
1982 ++$interesting_props and next if $_ !~ /^svn:/;
1983 # FIXME: Fragile, if SVN adds new public properties,
1984 # this needs to be updated.
1985 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1986 |eol-style|mime-type
1987 |externals|needs-lock)$/x;
1989 &$sub($self, $p, $props) if $interesting_props;
1991 foreach (sort keys %$dirent) {
1992 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1993 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1997 sub last_rev { ($_[0]->last_rev_commit)[0] }
1998 sub last_commit { ($_[0]->last_rev_commit)[1] }
2000 # returns the newest SVN revision number and newest commit SHA1
2001 sub last_rev_commit {
2002 my ($self) = @_;
2003 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2004 return ($self->{last_rev}, $self->{last_commit});
2006 my $c = ::verify_ref($self->refname.'^0');
2007 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2008 my $rev = (::cmt_metadata($c))[1];
2009 if (defined $rev) {
2010 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2011 return ($rev, $c);
2014 my $map_path = $self->map_path;
2015 unless (-e $map_path) {
2016 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2017 return (undef, undef);
2019 my ($rev, $commit) = $self->rev_map_max(1);
2020 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2021 return ($rev, $commit);
2024 sub get_fetch_range {
2025 my ($self, $min, $max) = @_;
2026 $max ||= $self->ra->get_latest_revnum;
2027 $min ||= $self->rev_map_max;
2028 (++$min, $max);
2031 sub tmp_config {
2032 my (@args) = @_;
2033 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2034 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2035 if (! -f $config && -f $old_def_config) {
2036 rename $old_def_config, $config or
2037 die "Failed rename $old_def_config => $config: $!\n";
2039 my $old_config = $ENV{GIT_CONFIG};
2040 $ENV{GIT_CONFIG} = $config;
2041 $@ = undef;
2042 my @ret = eval {
2043 unless (-f $config) {
2044 mkfile($config);
2045 open my $fh, '>', $config or
2046 die "Can't open $config: $!\n";
2047 print $fh "; This file is used internally by ",
2048 "git-svn\n" or die
2049 "Couldn't write to $config: $!\n";
2050 print $fh "; You should not have to edit it\n" or
2051 die "Couldn't write to $config: $!\n";
2052 close $fh or die "Couldn't close $config: $!\n";
2054 command('config', @args);
2056 my $err = $@;
2057 if (defined $old_config) {
2058 $ENV{GIT_CONFIG} = $old_config;
2059 } else {
2060 delete $ENV{GIT_CONFIG};
2062 die $err if $err;
2063 wantarray ? @ret : $ret[0];
2066 sub tmp_index_do {
2067 my ($self, $sub) = @_;
2068 my $old_index = $ENV{GIT_INDEX_FILE};
2069 $ENV{GIT_INDEX_FILE} = $self->{index};
2070 $@ = undef;
2071 my @ret = eval {
2072 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2073 mkpath([$dir]) unless -d $dir;
2074 &$sub;
2076 my $err = $@;
2077 if (defined $old_index) {
2078 $ENV{GIT_INDEX_FILE} = $old_index;
2079 } else {
2080 delete $ENV{GIT_INDEX_FILE};
2082 die $err if $err;
2083 wantarray ? @ret : $ret[0];
2086 sub assert_index_clean {
2087 my ($self, $treeish) = @_;
2089 $self->tmp_index_do(sub {
2090 command_noisy('read-tree', $treeish) unless -e $self->{index};
2091 my $x = command_oneline('write-tree');
2092 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2093 /^tree ($::sha1)/mo);
2094 return if $y eq $x;
2096 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2097 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2098 command_noisy('read-tree', $treeish);
2099 $x = command_oneline('write-tree');
2100 if ($y ne $x) {
2101 ::fatal "trees ($treeish) $y != $x\n",
2102 "Something is seriously wrong...";
2107 sub get_commit_parents {
2108 my ($self, $log_entry) = @_;
2109 my (%seen, @ret, @tmp);
2110 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2111 if (my $ip = $self->{inject_parents}) {
2112 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2113 push @tmp, $commit;
2116 if (my $cur = ::verify_ref($self->refname.'^0')) {
2117 push @tmp, $cur;
2119 if (my $ipd = $self->{inject_parents_dcommit}) {
2120 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2121 push @tmp, @$commit;
2124 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2125 while (my $p = shift @tmp) {
2126 next if $seen{$p};
2127 $seen{$p} = 1;
2128 push @ret, $p;
2129 # MAXPARENT is defined to 16 in commit-tree.c:
2130 last if @ret >= 16;
2132 if (@tmp) {
2133 die "r$log_entry->{revision}: No room for parents:\n\t",
2134 join("\n\t", @tmp), "\n";
2136 @ret;
2139 sub rewrite_root {
2140 my ($self) = @_;
2141 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2142 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2143 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2144 if ($rwr) {
2145 $rwr =~ s#/+$##;
2146 if ($rwr !~ m#^[a-z\+]+://#) {
2147 die "$rwr is not a valid URL (key: $k)\n";
2150 $self->{-rewrite_root} = $rwr;
2153 sub metadata_url {
2154 my ($self) = @_;
2155 ($self->rewrite_root || $self->{url}) .
2156 (length $self->{path} ? '/' . $self->{path} : '');
2159 sub full_url {
2160 my ($self) = @_;
2161 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2165 sub set_commit_header_env {
2166 my ($log_entry) = @_;
2167 my %env;
2168 foreach my $ned (qw/NAME EMAIL DATE/) {
2169 foreach my $ac (qw/AUTHOR COMMITTER/) {
2170 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2174 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2175 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2176 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2178 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2179 ? $log_entry->{commit_name}
2180 : $log_entry->{name};
2181 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2182 ? $log_entry->{commit_email}
2183 : $log_entry->{email};
2184 \%env;
2187 sub restore_commit_header_env {
2188 my ($env) = @_;
2189 foreach my $ned (qw/NAME EMAIL DATE/) {
2190 foreach my $ac (qw/AUTHOR COMMITTER/) {
2191 my $k = "GIT_${ac}_${ned}";
2192 if (defined $env->{$k}) {
2193 $ENV{$k} = $env->{$k};
2194 } else {
2195 delete $ENV{$k};
2201 sub gc {
2202 command_noisy('gc', '--auto');
2205 sub do_git_commit {
2206 my ($self, $log_entry) = @_;
2207 my $lr = $self->last_rev;
2208 if (defined $lr && $lr >= $log_entry->{revision}) {
2209 die "Last fetched revision of ", $self->refname,
2210 " was r$lr, but we are about to fetch: ",
2211 "r$log_entry->{revision}!\n";
2213 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2214 croak "$log_entry->{revision} = $c already exists! ",
2215 "Why are we refetching it?\n";
2217 my $old_env = set_commit_header_env($log_entry);
2218 my $tree = $log_entry->{tree};
2219 if (!defined $tree) {
2220 $tree = $self->tmp_index_do(sub {
2221 command_oneline('write-tree') });
2223 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2225 my @exec = ('git-commit-tree', $tree);
2226 foreach ($self->get_commit_parents($log_entry)) {
2227 push @exec, '-p', $_;
2229 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2230 or croak $!;
2231 print $msg_fh $log_entry->{log} or croak $!;
2232 restore_commit_header_env($old_env);
2233 unless ($self->no_metadata) {
2234 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2235 or croak $!;
2237 $msg_fh->flush == 0 or croak $!;
2238 close $msg_fh or croak $!;
2239 chomp(my $commit = do { local $/; <$out_fh> });
2240 close $out_fh or croak $!;
2241 waitpid $pid, 0;
2242 croak $? if $?;
2243 if ($commit !~ /^$::sha1$/o) {
2244 die "Failed to commit, invalid sha1: $commit\n";
2247 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2249 $self->{last_rev} = $log_entry->{revision};
2250 $self->{last_commit} = $commit;
2251 print "r$log_entry->{revision}";
2252 if (defined $log_entry->{svm_revision}) {
2253 print " (\@$log_entry->{svm_revision})";
2254 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2255 0, $self->svm_uuid);
2257 print " = $commit ($self->{ref_id})\n";
2258 if (--$_gc_nr == 0) {
2259 $_gc_nr = $_gc_period;
2260 gc();
2262 return $commit;
2265 sub match_paths {
2266 my ($self, $paths, $r) = @_;
2267 return 1 if $self->{path} eq '';
2268 if (my $path = $paths->{"/$self->{path}"}) {
2269 return ($path->{action} eq 'D') ? 0 : 1;
2271 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2272 if (grep /$self->{path_regex}/, keys %$paths) {
2273 return 1;
2275 my $c = '';
2276 foreach (split m#/#, $self->{path}) {
2277 $c .= "/$_";
2278 next unless ($paths->{$c} &&
2279 ($paths->{$c}->{action} =~ /^[AR]$/));
2280 if ($self->ra->check_path($self->{path}, $r) ==
2281 $SVN::Node::dir) {
2282 return 1;
2285 return 0;
2288 sub find_parent_branch {
2289 my ($self, $paths, $rev) = @_;
2290 return undef unless $self->follow_parent;
2291 unless (defined $paths) {
2292 my $err_handler = $SVN::Error::handler;
2293 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2294 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2295 $paths =
2296 Git::SVN::Ra::dup_changed_paths($_[0]) });
2297 $SVN::Error::handler = $err_handler;
2299 return undef unless defined $paths;
2301 # look for a parent from another branch:
2302 my @b_path_components = split m#/#, $self->rel_path;
2303 my @a_path_components;
2304 my $i;
2305 while (@b_path_components) {
2306 $i = $paths->{'/'.join('/', @b_path_components)};
2307 last if $i && defined $i->{copyfrom_path};
2308 unshift(@a_path_components, pop(@b_path_components));
2310 return undef unless defined $i && defined $i->{copyfrom_path};
2311 my $branch_from = $i->{copyfrom_path};
2312 if (@a_path_components) {
2313 print STDERR "branch_from: $branch_from => ";
2314 $branch_from .= '/'.join('/', @a_path_components);
2315 print STDERR $branch_from, "\n";
2317 my $r = $i->{copyfrom_rev};
2318 my $repos_root = $self->ra->{repos_root};
2319 my $url = $self->ra->{url};
2320 my $new_url = $repos_root . $branch_from;
2321 print STDERR "Found possible branch point: ",
2322 "$new_url => ", $self->full_url, ", $r\n";
2323 $branch_from =~ s#^/##;
2324 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2325 unless ($gs) {
2326 my $ref_id = $self->{ref_id};
2327 $ref_id =~ s/\@\d+$//;
2328 $ref_id .= "\@$r";
2329 # just grow a tail if we're not unique enough :x
2330 $ref_id .= '-' while find_ref($ref_id);
2331 print STDERR "Initializing parent: $ref_id\n";
2332 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2333 if ($u =~ s#^\Q$url\E(/|$)##) {
2334 $p = $u;
2335 $u = $url;
2336 $repo_id = $self->{repo_id};
2338 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2340 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2341 if (!defined $r0 || !defined $parent) {
2342 my ($base, $head) = parse_revision_argument(0, $r);
2343 if ($base <= $r) {
2344 $gs->fetch($base, $r);
2346 ($r0, $parent) = $gs->last_rev_commit;
2348 if (defined $r0 && defined $parent) {
2349 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2350 my $ed;
2351 if ($self->ra->can_do_switch) {
2352 $self->assert_index_clean($parent);
2353 print STDERR "Following parent with do_switch\n";
2354 # do_switch works with svn/trunk >= r22312, but that
2355 # is not included with SVN 1.4.3 (the latest version
2356 # at the moment), so we can't rely on it
2357 $self->{last_commit} = $parent;
2358 $ed = SVN::Git::Fetcher->new($self);
2359 $gs->ra->gs_do_switch($r0, $rev, $gs,
2360 $self->full_url, $ed)
2361 or die "SVN connection failed somewhere...\n";
2362 } elsif ($self->ra->trees_match($new_url, $r0,
2363 $self->full_url, $rev)) {
2364 print STDERR "Trees match:\n",
2365 " $new_url\@$r0\n",
2366 " ${\$self->full_url}\@$rev\n",
2367 "Following parent with no changes\n";
2368 $self->tmp_index_do(sub {
2369 command_noisy('read-tree', $parent);
2371 $self->{last_commit} = $parent;
2372 } else {
2373 print STDERR "Following parent with do_update\n";
2374 $ed = SVN::Git::Fetcher->new($self);
2375 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2376 or die "SVN connection failed somewhere...\n";
2378 print STDERR "Successfully followed parent\n";
2379 return $self->make_log_entry($rev, [$parent], $ed);
2381 return undef;
2384 sub do_fetch {
2385 my ($self, $paths, $rev) = @_;
2386 my $ed;
2387 my ($last_rev, @parents);
2388 if (my $lc = $self->last_commit) {
2389 # we can have a branch that was deleted, then re-added
2390 # under the same name but copied from another path, in
2391 # which case we'll have multiple parents (we don't
2392 # want to break the original ref, nor lose copypath info):
2393 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2394 push @{$log_entry->{parents}}, $lc;
2395 return $log_entry;
2397 $ed = SVN::Git::Fetcher->new($self);
2398 $last_rev = $self->{last_rev};
2399 $ed->{c} = $lc;
2400 @parents = ($lc);
2401 } else {
2402 $last_rev = $rev;
2403 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2404 return $log_entry;
2406 $ed = SVN::Git::Fetcher->new($self);
2408 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2409 die "SVN connection failed somewhere...\n";
2411 $self->make_log_entry($rev, \@parents, $ed);
2414 sub get_untracked {
2415 my ($self, $ed) = @_;
2416 my @out;
2417 my $h = $ed->{empty};
2418 foreach (sort keys %$h) {
2419 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2420 push @out, " $act: " . uri_encode($_);
2421 warn "W: $act: $_\n";
2423 foreach my $t (qw/dir_prop file_prop/) {
2424 $h = $ed->{$t} or next;
2425 foreach my $path (sort keys %$h) {
2426 my $ppath = $path eq '' ? '.' : $path;
2427 foreach my $prop (sort keys %{$h->{$path}}) {
2428 next if $SKIP_PROP{$prop};
2429 my $v = $h->{$path}->{$prop};
2430 my $t_ppath_prop = "$t: " .
2431 uri_encode($ppath) . ' ' .
2432 uri_encode($prop);
2433 if (defined $v) {
2434 push @out, " +$t_ppath_prop " .
2435 uri_encode($v);
2436 } else {
2437 push @out, " -$t_ppath_prop";
2442 foreach my $t (qw/absent_file absent_directory/) {
2443 $h = $ed->{$t} or next;
2444 foreach my $parent (sort keys %$h) {
2445 foreach my $path (sort @{$h->{$parent}}) {
2446 push @out, " $t: " .
2447 uri_encode("$parent/$path");
2448 warn "W: $t: $parent/$path ",
2449 "Insufficient permissions?\n";
2453 \@out;
2456 sub parse_svn_date {
2457 my $date = shift || return '+0000 1970-01-01 00:00:00';
2458 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2459 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2460 croak "Unable to parse date: $date\n";
2461 "+0000 $Y-$m-$d $H:$M:$S";
2464 sub check_author {
2465 my ($author) = @_;
2466 if (!defined $author || length $author == 0) {
2467 $author = '(no author)';
2468 } elsif (defined $::_authors && ! defined $::users{$author}) {
2469 die "Author: $author not defined in $::_authors file\n";
2471 $author;
2474 sub make_log_entry {
2475 my ($self, $rev, $parents, $ed) = @_;
2476 my $untracked = $self->get_untracked($ed);
2478 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2479 print $un "r$rev\n" or croak $!;
2480 print $un $_, "\n" foreach @$untracked;
2481 my %log_entry = ( parents => $parents || [], revision => $rev,
2482 log => '');
2484 my $headrev;
2485 my $logged = delete $self->{logged_rev_props};
2486 if (!$logged || $self->{-want_revprops}) {
2487 my $rp = $self->ra->rev_proplist($rev);
2488 foreach (sort keys %$rp) {
2489 my $v = $rp->{$_};
2490 if (/^svn:(author|date|log)$/) {
2491 $log_entry{$1} = $v;
2492 } elsif ($_ eq 'svm:headrev') {
2493 $headrev = $v;
2494 } else {
2495 print $un " rev_prop: ", uri_encode($_), ' ',
2496 uri_encode($v), "\n";
2499 } else {
2500 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2502 close $un or croak $!;
2504 $log_entry{date} = parse_svn_date($log_entry{date});
2505 $log_entry{log} .= "\n";
2506 my $author = $log_entry{author} = check_author($log_entry{author});
2507 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2508 : ($author, undef);
2510 my ($commit_name, $commit_email) = ($name, $email);
2511 if ($_use_log_author) {
2512 my $name_field;
2513 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2514 $name_field = $1;
2515 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2516 $name_field = $1;
2518 if (!defined $name_field) {
2519 if (!defined $email) {
2520 $email = $name;
2522 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2523 ($name, $email) = ($1, $2);
2524 } elsif ($name_field =~ /(.*)@/) {
2525 ($name, $email) = ($1, $name_field);
2526 } else {
2527 ($name, $email) = ($name_field, $name_field);
2530 if (defined $headrev && $self->use_svm_props) {
2531 if ($self->rewrite_root) {
2532 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2533 "options set!\n";
2535 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2536 # we don't want "SVM: initializing mirror for junk" ...
2537 return undef if $r == 0;
2538 my $svm = $self->svm;
2539 if ($uuid ne $svm->{uuid}) {
2540 die "UUID mismatch on SVM path:\n",
2541 "expected: $svm->{uuid}\n",
2542 " got: $uuid\n";
2544 my $full_url = $self->full_url;
2545 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2546 die "Failed to replace '$svm->{replace}' with ",
2547 "'$svm->{source}' in $full_url\n";
2548 # throw away username for storing in records
2549 remove_username($full_url);
2550 $log_entry{metadata} = "$full_url\@$r $uuid";
2551 $log_entry{svm_revision} = $r;
2552 $email ||= "$author\@$uuid";
2553 $commit_email ||= "$author\@$uuid";
2554 } elsif ($self->use_svnsync_props) {
2555 my $full_url = $self->svnsync->{url};
2556 $full_url .= "/$self->{path}" if length $self->{path};
2557 remove_username($full_url);
2558 my $uuid = $self->svnsync->{uuid};
2559 $log_entry{metadata} = "$full_url\@$rev $uuid";
2560 $email ||= "$author\@$uuid";
2561 $commit_email ||= "$author\@$uuid";
2562 } else {
2563 my $url = $self->metadata_url;
2564 remove_username($url);
2565 $log_entry{metadata} = "$url\@$rev " .
2566 $self->ra->get_uuid;
2567 $email ||= "$author\@" . $self->ra->get_uuid;
2568 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2570 $log_entry{name} = $name;
2571 $log_entry{email} = $email;
2572 $log_entry{commit_name} = $commit_name;
2573 $log_entry{commit_email} = $commit_email;
2574 \%log_entry;
2577 sub fetch {
2578 my ($self, $min_rev, $max_rev, @parents) = @_;
2579 my ($last_rev, $last_commit) = $self->last_rev_commit;
2580 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2581 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2584 sub set_tree_cb {
2585 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2586 $self->{inject_parents} = { $rev => $tree };
2587 $self->fetch(undef, undef);
2590 sub set_tree {
2591 my ($self, $tree) = (shift, shift);
2592 my $log_entry = ::get_commit_entry($tree);
2593 unless ($self->{last_rev}) {
2594 fatal("Must have an existing revision to commit");
2596 my %ed_opts = ( r => $self->{last_rev},
2597 log => $log_entry->{log},
2598 ra => $self->ra,
2599 tree_a => $self->{last_commit},
2600 tree_b => $tree,
2601 editor_cb => sub {
2602 $self->set_tree_cb($log_entry, $tree, @_) },
2603 svn_path => $self->{path} );
2604 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2605 print "No changes\nr$self->{last_rev} = $tree\n";
2609 sub rebuild_from_rev_db {
2610 my ($self, $path) = @_;
2611 my $r = -1;
2612 open my $fh, '<', $path or croak "open: $!";
2613 binmode $fh or croak "binmode: $!";
2614 while (<$fh>) {
2615 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2616 chomp($_);
2617 ++$r;
2618 next if $_ eq ('0' x 40);
2619 $self->rev_map_set($r, $_);
2620 print "r$r = $_\n";
2622 close $fh or croak "close: $!";
2623 unlink $path or croak "unlink: $!";
2626 sub rebuild {
2627 my ($self) = @_;
2628 my $map_path = $self->map_path;
2629 return if (-e $map_path && ! -z $map_path);
2630 return unless ::verify_ref($self->refname.'^0');
2631 if ($self->use_svm_props || $self->no_metadata) {
2632 my $rev_db = $self->rev_db_path;
2633 $self->rebuild_from_rev_db($rev_db);
2634 if ($self->use_svm_props) {
2635 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2636 $self->rebuild_from_rev_db($svm_rev_db);
2638 $self->unlink_rev_db_symlink;
2639 return;
2641 print "Rebuilding $map_path ...\n";
2642 my ($log, $ctx) =
2643 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2644 $self->refname, '--');
2645 my $metadata_url = $self->metadata_url;
2646 remove_username($metadata_url);
2647 my $svn_uuid = $self->ra_uuid;
2648 my $c;
2649 while (<$log>) {
2650 if ( m{^commit ($::sha1)$} ) {
2651 $c = $1;
2652 next;
2654 next unless s{^\s*(git-svn-id:)}{$1};
2655 my ($url, $rev, $uuid) = ::extract_metadata($_);
2656 remove_username($url);
2658 # ignore merges (from set-tree)
2659 next if (!defined $rev || !$uuid);
2661 # if we merged or otherwise started elsewhere, this is
2662 # how we break out of it
2663 if (($uuid ne $svn_uuid) ||
2664 ($metadata_url && $url && ($url ne $metadata_url))) {
2665 next;
2668 $self->rev_map_set($rev, $c);
2669 print "r$rev = $c\n";
2671 command_close_pipe($log, $ctx);
2672 print "Done rebuilding $map_path\n";
2673 my $rev_db_path = $self->rev_db_path;
2674 if (-f $self->rev_db_path) {
2675 unlink $self->rev_db_path or croak "unlink: $!";
2677 $self->unlink_rev_db_symlink;
2680 # rev_map:
2681 # Tie::File seems to be prone to offset errors if revisions get sparse,
2682 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2683 # one of my favorite modules is out :< Next up would be one of the DBM
2684 # modules, but I'm not sure which is most portable...
2686 # This is the replacement for the rev_db format, which was too big
2687 # and inefficient for large repositories with a lot of sparse history
2688 # (mainly tags)
2690 # The format is this:
2691 # - 24 bytes for every record,
2692 # * 4 bytes for the integer representing an SVN revision number
2693 # * 20 bytes representing the sha1 of a git commit
2694 # - No empty padding records like the old format
2695 # (except the last record, which can be overwritten)
2696 # - new records are written append-only since SVN revision numbers
2697 # increase monotonically
2698 # - lookups on SVN revision number are done via a binary search
2699 # - Piping the file to xxd -c24 is a good way of dumping it for
2700 # viewing or editing (piped back through xxd -r), should the need
2701 # ever arise.
2702 # - The last record can be padding revision with an all-zero sha1
2703 # This is used to optimize fetch performance when using multiple
2704 # "fetch" directives in .git/config
2706 # These files are disposable unless noMetadata or useSvmProps is set
2708 sub _rev_map_set {
2709 my ($fh, $rev, $commit) = @_;
2711 binmode $fh or croak "binmode: $!";
2712 my $size = (stat($fh))[7];
2713 ($size % 24) == 0 or croak "inconsistent size: $size";
2715 my $wr_offset = 0;
2716 if ($size > 0) {
2717 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2718 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2719 $read == 24 or croak "read only $read bytes (!= 24)";
2720 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2721 if ($last_commit eq ('0' x40)) {
2722 if ($size >= 48) {
2723 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2724 $read = sysread($fh, $buf, 24) or
2725 croak "read: $!";
2726 $read == 24 or
2727 croak "read only $read bytes (!= 24)";
2728 ($last_rev, $last_commit) =
2729 unpack(rev_map_fmt, $buf);
2730 if ($last_commit eq ('0' x40)) {
2731 croak "inconsistent .rev_map\n";
2734 if ($last_rev >= $rev) {
2735 croak "last_rev is higher!: $last_rev >= $rev";
2737 $wr_offset = -24;
2740 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2741 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2742 croak "write: $!";
2745 sub mkfile {
2746 my ($path) = @_;
2747 unless (-e $path) {
2748 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2749 mkpath([$dir]) unless -d $dir;
2750 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2751 close $fh or die "Couldn't close (create) $path: $!\n";
2755 sub rev_map_set {
2756 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2757 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2758 my $db = $self->map_path($uuid);
2759 my $db_lock = "$db.lock";
2760 my $sig;
2761 if ($update_ref) {
2762 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2763 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2765 mkfile($db);
2767 $LOCKFILES{$db_lock} = 1;
2768 my $sync;
2769 # both of these options make our .rev_db file very, very important
2770 # and we can't afford to lose it because rebuild() won't work
2771 if ($self->use_svm_props || $self->no_metadata) {
2772 $sync = 1;
2773 copy($db, $db_lock) or die "rev_map_set(@_): ",
2774 "Failed to copy: ",
2775 "$db => $db_lock ($!)\n";
2776 } else {
2777 rename $db, $db_lock or die "rev_map_set(@_): ",
2778 "Failed to rename: ",
2779 "$db => $db_lock ($!)\n";
2782 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2783 or croak "Couldn't open $db_lock: $!\n";
2784 _rev_map_set($fh, $rev, $commit);
2785 if ($sync) {
2786 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2787 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2789 close $fh or croak $!;
2790 if ($update_ref) {
2791 $_head = $self;
2792 command_noisy('update-ref', '-m', "r$rev",
2793 $self->refname, $commit);
2795 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2796 "$db_lock => $db ($!)\n";
2797 delete $LOCKFILES{$db_lock};
2798 if ($update_ref) {
2799 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2800 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2801 kill $sig, $$ if defined $sig;
2805 # If want_commit, this will return an array of (rev, commit) where
2806 # commit _must_ be a valid commit in the archive.
2807 # Otherwise, it'll return the max revision (whether or not the
2808 # commit is valid or just a 0x40 placeholder).
2809 sub rev_map_max {
2810 my ($self, $want_commit) = @_;
2811 $self->rebuild;
2812 my $map_path = $self->map_path;
2813 stat $map_path or return $want_commit ? (0, undef) : 0;
2814 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2815 binmode $fh or croak "binmode: $!";
2816 my $size = (stat($fh))[7];
2817 ($size % 24) == 0 or croak "inconsistent size: $size";
2819 if ($size == 0) {
2820 close $fh or croak "close: $!";
2821 return $want_commit ? (0, undef) : 0;
2824 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2825 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2826 my ($r, $c) = unpack(rev_map_fmt, $buf);
2827 if ($want_commit && $c eq ('0' x40)) {
2828 if ($size < 48) {
2829 return $want_commit ? (0, undef) : 0;
2831 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2832 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2833 ($r, $c) = unpack(rev_map_fmt, $buf);
2834 if ($c eq ('0'x40)) {
2835 croak "Penultimate record is all-zeroes in $map_path";
2838 close $fh or croak "close: $!";
2839 $want_commit ? ($r, $c) : $r;
2842 sub rev_map_get {
2843 my ($self, $rev, $uuid) = @_;
2844 my $map_path = $self->map_path($uuid);
2845 return undef unless -e $map_path;
2847 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2848 binmode $fh or croak "binmode: $!";
2849 my $size = (stat($fh))[7];
2850 ($size % 24) == 0 or croak "inconsistent size: $size";
2852 if ($size == 0) {
2853 close $fh or croak "close: $fh";
2854 return undef;
2857 my ($l, $u) = (0, $size - 24);
2858 my ($r, $c, $buf);
2860 while ($l <= $u) {
2861 my $i = int(($l/24 + $u/24) / 2) * 24;
2862 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2863 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2864 my ($r, $c) = unpack('NH40', $buf);
2866 if ($r < $rev) {
2867 $l = $i + 24;
2868 } elsif ($r > $rev) {
2869 $u = $i - 24;
2870 } else { # $r == $rev
2871 close($fh) or croak "close: $!";
2872 return $c eq ('0' x 40) ? undef : $c;
2875 close($fh) or croak "close: $!";
2876 undef;
2879 # Finds the first svn revision that exists on (if $eq_ok is true) or
2880 # before $rev for the current branch. It will not search any lower
2881 # than $min_rev. Returns the git commit hash and svn revision number
2882 # if found, else (undef, undef).
2883 sub find_rev_before {
2884 my ($self, $rev, $eq_ok, $min_rev) = @_;
2885 --$rev unless $eq_ok;
2886 $min_rev ||= 1;
2887 while ($rev >= $min_rev) {
2888 if (my $c = $self->rev_map_get($rev)) {
2889 return ($rev, $c);
2891 --$rev;
2893 return (undef, undef);
2896 # Finds the first svn revision that exists on (if $eq_ok is true) or
2897 # after $rev for the current branch. It will not search any higher
2898 # than $max_rev. Returns the git commit hash and svn revision number
2899 # if found, else (undef, undef).
2900 sub find_rev_after {
2901 my ($self, $rev, $eq_ok, $max_rev) = @_;
2902 ++$rev unless $eq_ok;
2903 $max_rev ||= $self->rev_map_max;
2904 while ($rev <= $max_rev) {
2905 if (my $c = $self->rev_map_get($rev)) {
2906 return ($rev, $c);
2908 ++$rev;
2910 return (undef, undef);
2913 sub _new {
2914 my ($class, $repo_id, $ref_id, $path) = @_;
2915 unless (defined $repo_id && length $repo_id) {
2916 $repo_id = $Git::SVN::default_repo_id;
2918 unless (defined $ref_id && length $ref_id) {
2919 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2921 $_[1] = $repo_id;
2922 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2923 $_[3] = $path = '' unless (defined $path);
2924 mkpath(["$ENV{GIT_DIR}/svn"]);
2925 bless {
2926 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2927 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2928 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2931 # for read-only access of old .rev_db formats
2932 sub unlink_rev_db_symlink {
2933 my ($self) = @_;
2934 my $link = $self->rev_db_path;
2935 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2936 if (-l $link) {
2937 unlink $link or croak "unlink: $link failed!";
2941 sub rev_db_path {
2942 my ($self, $uuid) = @_;
2943 my $db_path = $self->map_path($uuid);
2944 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2945 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2946 $db_path;
2949 # the new replacement for .rev_db
2950 sub map_path {
2951 my ($self, $uuid) = @_;
2952 $uuid ||= $self->ra_uuid;
2953 "$self->{map_root}.$uuid";
2956 sub uri_encode {
2957 my ($f) = @_;
2958 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2962 sub remove_username {
2963 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2966 package Git::SVN::Prompt;
2967 use strict;
2968 use warnings;
2969 require SVN::Core;
2970 use vars qw/$_no_auth_cache $_username/;
2972 sub simple {
2973 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2974 $may_save = undef if $_no_auth_cache;
2975 $default_username = $_username if defined $_username;
2976 if (defined $default_username && length $default_username) {
2977 if (defined $realm && length $realm) {
2978 print STDERR "Authentication realm: $realm\n";
2979 STDERR->flush;
2981 $cred->username($default_username);
2982 } else {
2983 username($cred, $realm, $may_save, $pool);
2985 $cred->password(_read_password("Password for '" .
2986 $cred->username . "': ", $realm));
2987 $cred->may_save($may_save);
2988 $SVN::_Core::SVN_NO_ERROR;
2991 sub ssl_server_trust {
2992 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2993 $may_save = undef if $_no_auth_cache;
2994 print STDERR "Error validating server certificate for '$realm':\n";
2996 no warnings 'once';
2997 # All variables SVN::Auth::SSL::* are used only once,
2998 # so we're shutting up Perl warnings about this.
2999 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3000 print STDERR " - The certificate is not issued ",
3001 "by a trusted authority. Use the\n",
3002 " fingerprint to validate ",
3003 "the certificate manually!\n";
3005 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3006 print STDERR " - The certificate hostname ",
3007 "does not match.\n";
3009 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3010 print STDERR " - The certificate is not yet valid.\n";
3012 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3013 print STDERR " - The certificate has expired.\n";
3015 if ($failures & $SVN::Auth::SSL::OTHER) {
3016 print STDERR " - The certificate has ",
3017 "an unknown error.\n";
3019 } # no warnings 'once'
3020 printf STDERR
3021 "Certificate information:\n".
3022 " - Hostname: %s\n".
3023 " - Valid: from %s until %s\n".
3024 " - Issuer: %s\n".
3025 " - Fingerprint: %s\n",
3026 map $cert_info->$_, qw(hostname valid_from valid_until
3027 issuer_dname fingerprint);
3028 my $choice;
3029 prompt:
3030 print STDERR $may_save ?
3031 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3032 "(R)eject or accept (t)emporarily? ";
3033 STDERR->flush;
3034 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3035 if ($choice =~ /^t$/i) {
3036 $cred->may_save(undef);
3037 } elsif ($choice =~ /^r$/i) {
3038 return -1;
3039 } elsif ($may_save && $choice =~ /^p$/i) {
3040 $cred->may_save($may_save);
3041 } else {
3042 goto prompt;
3044 $cred->accepted_failures($failures);
3045 $SVN::_Core::SVN_NO_ERROR;
3048 sub ssl_client_cert {
3049 my ($cred, $realm, $may_save, $pool) = @_;
3050 $may_save = undef if $_no_auth_cache;
3051 print STDERR "Client certificate filename: ";
3052 STDERR->flush;
3053 chomp(my $filename = <STDIN>);
3054 $cred->cert_file($filename);
3055 $cred->may_save($may_save);
3056 $SVN::_Core::SVN_NO_ERROR;
3059 sub ssl_client_cert_pw {
3060 my ($cred, $realm, $may_save, $pool) = @_;
3061 $may_save = undef if $_no_auth_cache;
3062 $cred->password(_read_password("Password: ", $realm));
3063 $cred->may_save($may_save);
3064 $SVN::_Core::SVN_NO_ERROR;
3067 sub username {
3068 my ($cred, $realm, $may_save, $pool) = @_;
3069 $may_save = undef if $_no_auth_cache;
3070 if (defined $realm && length $realm) {
3071 print STDERR "Authentication realm: $realm\n";
3073 my $username;
3074 if (defined $_username) {
3075 $username = $_username;
3076 } else {
3077 print STDERR "Username: ";
3078 STDERR->flush;
3079 chomp($username = <STDIN>);
3081 $cred->username($username);
3082 $cred->may_save($may_save);
3083 $SVN::_Core::SVN_NO_ERROR;
3086 sub _read_password {
3087 my ($prompt, $realm) = @_;
3088 print STDERR $prompt;
3089 STDERR->flush;
3090 require Term::ReadKey;
3091 Term::ReadKey::ReadMode('noecho');
3092 my $password = '';
3093 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3094 last if $key =~ /[\012\015]/; # \n\r
3095 $password .= $key;
3097 Term::ReadKey::ReadMode('restore');
3098 print STDERR "\n";
3099 STDERR->flush;
3100 $password;
3103 package SVN::Git::Fetcher;
3104 use vars qw/@ISA/;
3105 use strict;
3106 use warnings;
3107 use Carp qw/croak/;
3108 use File::Temp qw/tempfile/;
3109 use IO::File qw//;
3111 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3112 sub new {
3113 my ($class, $git_svn) = @_;
3114 my $self = SVN::Delta::Editor->new;
3115 bless $self, $class;
3116 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3117 $self->{empty} = {};
3118 $self->{dir_prop} = {};
3119 $self->{file_prop} = {};
3120 $self->{absent_dir} = {};
3121 $self->{absent_file} = {};
3122 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3123 $self;
3126 sub set_path_strip {
3127 my ($self, $path) = @_;
3128 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3131 sub open_root {
3132 { path => '' };
3135 sub open_directory {
3136 my ($self, $path, $pb, $rev) = @_;
3137 { path => $path };
3140 sub git_path {
3141 my ($self, $path) = @_;
3142 if ($self->{path_strip}) {
3143 $path =~ s!$self->{path_strip}!! or
3144 die "Failed to strip path '$path' ($self->{path_strip})\n";
3146 $path;
3149 sub delete_entry {
3150 my ($self, $path, $rev, $pb) = @_;
3152 my $gpath = $self->git_path($path);
3153 return undef if ($gpath eq '');
3155 # remove entire directories.
3156 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3157 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3158 -r --name-only -z/,
3159 $self->{c}, '--', $gpath);
3160 local $/ = "\0";
3161 while (<$ls>) {
3162 chomp;
3163 $self->{gii}->remove($_);
3164 print "\tD\t$_\n" unless $::_q;
3166 print "\tD\t$gpath/\n" unless $::_q;
3167 command_close_pipe($ls, $ctx);
3168 $self->{empty}->{$path} = 0
3169 } else {
3170 $self->{gii}->remove($gpath);
3171 print "\tD\t$gpath\n" unless $::_q;
3173 undef;
3176 sub open_file {
3177 my ($self, $path, $pb, $rev) = @_;
3178 my $gpath = $self->git_path($path);
3179 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3180 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3181 unless (defined $mode && defined $blob) {
3182 die "$path was not found in commit $self->{c} (r$rev)\n";
3184 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3185 pool => SVN::Pool->new, action => 'M' };
3188 sub add_file {
3189 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3190 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3191 delete $self->{empty}->{$dir};
3192 { path => $path, mode_a => 100644, mode_b => 100644,
3193 pool => SVN::Pool->new, action => 'A' };
3196 sub add_directory {
3197 my ($self, $path, $cp_path, $cp_rev) = @_;
3198 my $gpath = $self->git_path($path);
3199 if ($gpath eq '') {
3200 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3201 -r --name-only -z/,
3202 $self->{c});
3203 local $/ = "\0";
3204 while (<$ls>) {
3205 chomp;
3206 $self->{gii}->remove($_);
3207 print "\tD\t$_\n" unless $::_q;
3209 command_close_pipe($ls, $ctx);
3210 $self->{empty}->{$path} = 0;
3212 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3213 delete $self->{empty}->{$dir};
3214 $self->{empty}->{$path} = 1;
3215 { path => $path };
3218 sub change_dir_prop {
3219 my ($self, $db, $prop, $value) = @_;
3220 $self->{dir_prop}->{$db->{path}} ||= {};
3221 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3222 undef;
3225 sub absent_directory {
3226 my ($self, $path, $pb) = @_;
3227 $self->{absent_dir}->{$pb->{path}} ||= [];
3228 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3229 undef;
3232 sub absent_file {
3233 my ($self, $path, $pb) = @_;
3234 $self->{absent_file}->{$pb->{path}} ||= [];
3235 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3236 undef;
3239 sub change_file_prop {
3240 my ($self, $fb, $prop, $value) = @_;
3241 if ($prop eq 'svn:executable') {
3242 if ($fb->{mode_b} != 120000) {
3243 $fb->{mode_b} = defined $value ? 100755 : 100644;
3245 } elsif ($prop eq 'svn:special') {
3246 $fb->{mode_b} = defined $value ? 120000 : 100644;
3247 } else {
3248 $self->{file_prop}->{$fb->{path}} ||= {};
3249 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3251 undef;
3254 sub apply_textdelta {
3255 my ($self, $fb, $exp) = @_;
3256 my $fh = Git::temp_acquire('svn_delta');
3257 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3258 # (but $base does not,) so dup() it for reading in close_file
3259 open my $dup, '<&', $fh or croak $!;
3260 my $base = Git::temp_acquire('git_blob');
3261 if ($fb->{blob}) {
3262 print $base 'link ' if ($fb->{mode_a} == 120000);
3263 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3264 die "Failed to read object $fb->{blob}" if ($size < 0);
3266 if (defined $exp) {
3267 seek $base, 0, 0 or croak $!;
3268 my $got = ::md5sum($base);
3269 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3270 "expected: $exp\n",
3271 " got: $got\n" if ($got ne $exp);
3274 seek $base, 0, 0 or croak $!;
3275 $fb->{fh} = $fh;
3276 $fb->{base} = $base;
3277 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3280 sub close_file {
3281 my ($self, $fb, $exp) = @_;
3282 my $hash;
3283 my $path = $self->git_path($fb->{path});
3284 if (my $fh = $fb->{fh}) {
3285 if (defined $exp) {
3286 seek($fh, 0, 0) or croak $!;
3287 my $got = ::md5sum($fh);
3288 if ($got ne $exp) {
3289 die "Checksum mismatch: $path\n",
3290 "expected: $exp\n got: $got\n";
3293 if ($fb->{mode_b} == 120000) {
3294 sysseek($fh, 0, 0) or croak $!;
3295 sysread($fh, my $buf, 5) == 5 or croak $!;
3297 unless ($buf eq 'link ') {
3298 warn "$path has mode 120000",
3299 " but is not a link\n";
3300 } else {
3301 my $tmp_fh = Git::temp_acquire('svn_hash');
3302 my $res;
3303 while ($res = sysread($fh, my $str, 1024)) {
3304 my $out = syswrite($tmp_fh, $str, $res);
3305 defined($out) && $out == $res
3306 or croak("write ",
3307 Git::temp_path($tmp_fh),
3308 ": $!\n");
3310 defined $res or croak $!;
3312 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3313 Git::temp_release($tmp_fh, 1);
3317 $hash = $::_repository->hash_and_insert_object(
3318 Git::temp_path($fh));
3319 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3321 Git::temp_release($fb->{base}, 1);
3322 Git::temp_release($fh, 1);
3323 } else {
3324 $hash = $fb->{blob} or die "no blob information\n";
3326 $fb->{pool}->clear;
3327 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3328 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3329 undef;
3332 sub abort_edit {
3333 my $self = shift;
3334 $self->{nr} = $self->{gii}->{nr};
3335 delete $self->{gii};
3336 $self->SUPER::abort_edit(@_);
3339 sub close_edit {
3340 my $self = shift;
3341 $self->{git_commit_ok} = 1;
3342 $self->{nr} = $self->{gii}->{nr};
3343 delete $self->{gii};
3344 $self->SUPER::close_edit(@_);
3347 package SVN::Git::Editor;
3348 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3349 use strict;
3350 use warnings;
3351 use Carp qw/croak/;
3352 use IO::File;
3354 sub new {
3355 my ($class, $opts) = @_;
3356 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3357 die "$_ required!\n" unless (defined $opts->{$_});
3360 my $pool = SVN::Pool->new;
3361 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3362 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3363 $opts->{r}, $mods);
3365 # $opts->{ra} functions should not be used after this:
3366 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3367 $opts->{editor_cb}, $pool);
3368 my $self = SVN::Delta::Editor->new(@ce, $pool);
3369 bless $self, $class;
3370 foreach (qw/svn_path r tree_a tree_b/) {
3371 $self->{$_} = $opts->{$_};
3373 $self->{url} = $opts->{ra}->{url};
3374 $self->{mods} = $mods;
3375 $self->{types} = $types;
3376 $self->{pool} = $pool;
3377 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3378 $self->{rm} = { };
3379 $self->{path_prefix} = length $self->{svn_path} ?
3380 "$self->{svn_path}/" : '';
3381 $self->{config} = $opts->{config};
3382 return $self;
3385 sub generate_diff {
3386 my ($tree_a, $tree_b) = @_;
3387 my @diff_tree = qw(diff-tree -z -r);
3388 if ($_cp_similarity) {
3389 push @diff_tree, "-C$_cp_similarity";
3390 } else {
3391 push @diff_tree, '-C';
3393 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3394 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3395 push @diff_tree, $tree_a, $tree_b;
3396 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3397 local $/ = "\0";
3398 my $state = 'meta';
3399 my @mods;
3400 while (<$diff_fh>) {
3401 chomp $_; # this gets rid of the trailing "\0"
3402 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3403 ($::sha1)\s($::sha1)\s
3404 ([MTCRAD])\d*$/xo) {
3405 push @mods, { mode_a => $1, mode_b => $2,
3406 sha1_a => $3, sha1_b => $4,
3407 chg => $5 };
3408 if ($5 =~ /^(?:C|R)$/) {
3409 $state = 'file_a';
3410 } else {
3411 $state = 'file_b';
3413 } elsif ($state eq 'file_a') {
3414 my $x = $mods[$#mods] or croak "Empty array\n";
3415 if ($x->{chg} !~ /^(?:C|R)$/) {
3416 croak "Error parsing $_, $x->{chg}\n";
3418 $x->{file_a} = $_;
3419 $state = 'file_b';
3420 } elsif ($state eq 'file_b') {
3421 my $x = $mods[$#mods] or croak "Empty array\n";
3422 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3423 croak "Error parsing $_, $x->{chg}\n";
3425 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3426 croak "Error parsing $_, $x->{chg}\n";
3428 $x->{file_b} = $_;
3429 $state = 'meta';
3430 } else {
3431 croak "Error parsing $_\n";
3434 command_close_pipe($diff_fh, $ctx);
3435 \@mods;
3438 sub check_diff_paths {
3439 my ($ra, $pfx, $rev, $mods) = @_;
3440 my %types;
3441 $pfx .= '/' if length $pfx;
3443 sub type_diff_paths {
3444 my ($ra, $types, $path, $rev) = @_;
3445 my @p = split m#/+#, $path;
3446 my $c = shift @p;
3447 unless (defined $types->{$c}) {
3448 $types->{$c} = $ra->check_path($c, $rev);
3450 while (@p) {
3451 $c .= '/' . shift @p;
3452 next if defined $types->{$c};
3453 $types->{$c} = $ra->check_path($c, $rev);
3457 foreach my $m (@$mods) {
3458 foreach my $f (qw/file_a file_b/) {
3459 next unless defined $m->{$f};
3460 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3461 if (length $pfx.$dir && ! defined $types{$dir}) {
3462 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3466 \%types;
3469 sub split_path {
3470 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3473 sub repo_path {
3474 my ($self, $path) = @_;
3475 $self->{path_prefix}.(defined $path ? $path : '');
3478 sub url_path {
3479 my ($self, $path) = @_;
3480 if ($self->{url} =~ m#^https?://#) {
3481 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3483 $self->{url} . '/' . $self->repo_path($path);
3486 sub rmdirs {
3487 my ($self) = @_;
3488 my $rm = $self->{rm};
3489 delete $rm->{''}; # we never delete the url we're tracking
3490 return unless %$rm;
3492 foreach (keys %$rm) {
3493 my @d = split m#/#, $_;
3494 my $c = shift @d;
3495 $rm->{$c} = 1;
3496 while (@d) {
3497 $c .= '/' . shift @d;
3498 $rm->{$c} = 1;
3501 delete $rm->{$self->{svn_path}};
3502 delete $rm->{''}; # we never delete the url we're tracking
3503 return unless %$rm;
3505 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3506 $self->{tree_b});
3507 local $/ = "\0";
3508 while (<$fh>) {
3509 chomp;
3510 my @dn = split m#/#, $_;
3511 while (pop @dn) {
3512 delete $rm->{join '/', @dn};
3514 unless (%$rm) {
3515 close $fh;
3516 return;
3519 command_close_pipe($fh, $ctx);
3521 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3522 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3523 $self->close_directory($bat->{$d}, $p);
3524 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3525 print "\tD+\t$d/\n" unless $::_q;
3526 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3527 delete $bat->{$d};
3531 sub open_or_add_dir {
3532 my ($self, $full_path, $baton) = @_;
3533 my $t = $self->{types}->{$full_path};
3534 if (!defined $t) {
3535 die "$full_path not known in r$self->{r} or we have a bug!\n";
3538 no warnings 'once';
3539 # SVN::Node::none and SVN::Node::file are used only once,
3540 # so we're shutting up Perl's warnings about them.
3541 if ($t == $SVN::Node::none) {
3542 return $self->add_directory($full_path, $baton,
3543 undef, -1, $self->{pool});
3544 } elsif ($t == $SVN::Node::dir) {
3545 return $self->open_directory($full_path, $baton,
3546 $self->{r}, $self->{pool});
3547 } # no warnings 'once'
3548 print STDERR "$full_path already exists in repository at ",
3549 "r$self->{r} and it is not a directory (",
3550 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3551 } # no warnings 'once'
3552 exit 1;
3555 sub ensure_path {
3556 my ($self, $path) = @_;
3557 my $bat = $self->{bat};
3558 my $repo_path = $self->repo_path($path);
3559 return $bat->{''} unless (length $repo_path);
3560 my @p = split m#/+#, $repo_path;
3561 my $c = shift @p;
3562 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3563 while (@p) {
3564 my $c0 = $c;
3565 $c .= '/' . shift @p;
3566 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3568 return $bat->{$c};
3571 # Subroutine to convert a globbing pattern to a regular expression.
3572 # From perl cookbook.
3573 sub glob2pat {
3574 my $globstr = shift;
3575 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3576 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3577 return '^' . $globstr . '$';
3580 sub check_autoprop {
3581 my ($self, $pattern, $properties, $file, $fbat) = @_;
3582 # Convert the globbing pattern to a regular expression.
3583 my $regex = glob2pat($pattern);
3584 # Check if the pattern matches the file name.
3585 if($file =~ m/($regex)/) {
3586 # Parse the list of properties to set.
3587 my @props = split(/;/, $properties);
3588 foreach my $prop (@props) {
3589 # Parse 'name=value' syntax and set the property.
3590 if ($prop =~ /([^=]+)=(.*)/) {
3591 my ($n,$v) = ($1,$2);
3592 for ($n, $v) {
3593 s/^\s+//; s/\s+$//;
3595 $self->change_file_prop($fbat, $n, $v);
3601 sub apply_autoprops {
3602 my ($self, $file, $fbat) = @_;
3603 my $conf_t = ${$self->{config}}{'config'};
3604 no warnings 'once';
3605 # Check [miscellany]/enable-auto-props in svn configuration.
3606 if (SVN::_Core::svn_config_get_bool(
3607 $conf_t,
3608 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3609 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3610 0)) {
3611 # Auto-props are enabled. Enumerate them to look for matches.
3612 my $callback = sub {
3613 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3615 SVN::_Core::svn_config_enumerate(
3616 $conf_t,
3617 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3618 $callback);
3622 sub A {
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 undef, -1);
3628 print "\tA\t$m->{file_b}\n" unless $::_q;
3629 $self->apply_autoprops($file, $fbat);
3630 $self->chg_file($fbat, $m);
3631 $self->close_file($fbat,undef,$self->{pool});
3634 sub C {
3635 my ($self, $m) = @_;
3636 my ($dir, $file) = split_path($m->{file_b});
3637 my $pbat = $self->ensure_path($dir);
3638 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3639 $self->url_path($m->{file_a}), $self->{r});
3640 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3641 $self->chg_file($fbat, $m);
3642 $self->close_file($fbat,undef,$self->{pool});
3645 sub delete_entry {
3646 my ($self, $path, $pbat) = @_;
3647 my $rpath = $self->repo_path($path);
3648 my ($dir, $file) = split_path($rpath);
3649 $self->{rm}->{$dir} = 1;
3650 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3653 sub R {
3654 my ($self, $m) = @_;
3655 my ($dir, $file) = split_path($m->{file_b});
3656 my $pbat = $self->ensure_path($dir);
3657 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3658 $self->url_path($m->{file_a}), $self->{r});
3659 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3660 $self->apply_autoprops($file, $fbat);
3661 $self->chg_file($fbat, $m);
3662 $self->close_file($fbat,undef,$self->{pool});
3664 ($dir, $file) = split_path($m->{file_a});
3665 $pbat = $self->ensure_path($dir);
3666 $self->delete_entry($m->{file_a}, $pbat);
3669 sub M {
3670 my ($self, $m) = @_;
3671 my ($dir, $file) = split_path($m->{file_b});
3672 my $pbat = $self->ensure_path($dir);
3673 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3674 $pbat,$self->{r},$self->{pool});
3675 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3676 $self->chg_file($fbat, $m);
3677 $self->close_file($fbat,undef,$self->{pool});
3680 sub T { shift->M(@_) }
3682 sub change_file_prop {
3683 my ($self, $fbat, $pname, $pval) = @_;
3684 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3687 sub _chg_file_get_blob ($$$$) {
3688 my ($self, $fbat, $m, $which) = @_;
3689 my $fh = Git::temp_acquire("git_blob_$which");
3690 if ($m->{"mode_$which"} =~ /^120/) {
3691 print $fh 'link ' or croak $!;
3692 $self->change_file_prop($fbat,'svn:special','*');
3693 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3694 $self->change_file_prop($fbat,'svn:special',undef);
3696 my $blob = $m->{"sha1_$which"};
3697 return ($fh,) if ($blob =~ /^0{40}$/);
3698 my $size = $::_repository->cat_blob($blob, $fh);
3699 croak "Failed to read object $blob" if ($size < 0);
3700 $fh->flush == 0 or croak $!;
3701 seek $fh, 0, 0 or croak $!;
3703 my $exp = ::md5sum($fh);
3704 seek $fh, 0, 0 or croak $!;
3705 return ($fh, $exp);
3708 sub chg_file {
3709 my ($self, $fbat, $m) = @_;
3710 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3711 $self->change_file_prop($fbat,'svn:executable','*');
3712 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3713 $self->change_file_prop($fbat,'svn:executable',undef);
3715 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3716 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3717 my $pool = SVN::Pool->new;
3718 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3719 if (-s $fh_a) {
3720 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3721 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3722 if (defined $res) {
3723 die "Unexpected result from send_txstream: $res\n",
3724 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3726 } else {
3727 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3728 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3729 if ($got ne $exp_b);
3731 Git::temp_release($fh_b, 1);
3732 Git::temp_release($fh_a, 1);
3733 $pool->clear;
3736 sub D {
3737 my ($self, $m) = @_;
3738 my ($dir, $file) = split_path($m->{file_b});
3739 my $pbat = $self->ensure_path($dir);
3740 print "\tD\t$m->{file_b}\n" unless $::_q;
3741 $self->delete_entry($m->{file_b}, $pbat);
3744 sub close_edit {
3745 my ($self) = @_;
3746 my ($p,$bat) = ($self->{pool}, $self->{bat});
3747 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3748 next if $_ eq '';
3749 $self->close_directory($bat->{$_}, $p);
3751 $self->close_directory($bat->{''}, $p);
3752 $self->SUPER::close_edit($p);
3753 $p->clear;
3756 sub abort_edit {
3757 my ($self) = @_;
3758 $self->SUPER::abort_edit($self->{pool});
3761 sub DESTROY {
3762 my $self = shift;
3763 $self->SUPER::DESTROY(@_);
3764 $self->{pool}->clear;
3767 # this drives the editor
3768 sub apply_diff {
3769 my ($self) = @_;
3770 my $mods = $self->{mods};
3771 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3772 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3773 my $f = $m->{chg};
3774 if (defined $o{$f}) {
3775 $self->$f($m);
3776 } else {
3777 fatal("Invalid change type: $f");
3780 $self->rmdirs if $_rmdir;
3781 if (@$mods == 0) {
3782 $self->abort_edit;
3783 } else {
3784 $self->close_edit;
3786 return scalar @$mods;
3789 package Git::SVN::Ra;
3790 use vars qw/@ISA $config_dir $_log_window_size/;
3791 use strict;
3792 use warnings;
3793 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3795 BEGIN {
3796 # enforce temporary pool usage for some simple functions
3797 no strict 'refs';
3798 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3799 my $SUPER = "SUPER::$f";
3800 *$f = sub {
3801 my $self = shift;
3802 my $pool = SVN::Pool->new;
3803 my @ret = $self->$SUPER(@_,$pool);
3804 $pool->clear;
3805 wantarray ? @ret : $ret[0];
3810 sub _auth_providers () {
3812 SVN::Client::get_simple_provider(),
3813 SVN::Client::get_ssl_server_trust_file_provider(),
3814 SVN::Client::get_simple_prompt_provider(
3815 \&Git::SVN::Prompt::simple, 2),
3816 SVN::Client::get_ssl_client_cert_file_provider(),
3817 SVN::Client::get_ssl_client_cert_prompt_provider(
3818 \&Git::SVN::Prompt::ssl_client_cert, 2),
3819 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3820 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3821 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3822 SVN::Client::get_username_provider(),
3823 SVN::Client::get_ssl_server_trust_prompt_provider(
3824 \&Git::SVN::Prompt::ssl_server_trust),
3825 SVN::Client::get_username_prompt_provider(
3826 \&Git::SVN::Prompt::username, 2)
3830 sub escape_uri_only {
3831 my ($uri) = @_;
3832 my @tmp;
3833 foreach (split m{/}, $uri) {
3834 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3835 push @tmp, $_;
3837 join('/', @tmp);
3840 sub escape_url {
3841 my ($url) = @_;
3842 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3843 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3844 $url = "$scheme://$domain$uri";
3846 $url;
3849 sub new {
3850 my ($class, $url) = @_;
3851 $url =~ s!/+$!!;
3852 return $RA if ($RA && $RA->{url} eq $url);
3854 SVN::_Core::svn_config_ensure($config_dir, undef);
3855 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3856 my $config = SVN::Core::config_get_config($config_dir);
3857 $RA = undef;
3858 my $dont_store_passwords = 1;
3859 my $conf_t = ${$config}{'config'};
3861 no warnings 'once';
3862 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3863 # produces warnings that variables are used only once.
3864 # I had not found the better way to shut them up, so
3865 # the warnings of type 'once' are disabled in this block.
3866 if (SVN::_Core::svn_config_get_bool($conf_t,
3867 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3868 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3869 1) == 0) {
3870 SVN::_Core::svn_auth_set_parameter($baton,
3871 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3872 bless (\$dont_store_passwords, "_p_void"));
3874 if (SVN::_Core::svn_config_get_bool($conf_t,
3875 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3876 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3877 1) == 0) {
3878 $Git::SVN::Prompt::_no_auth_cache = 1;
3880 } # no warnings 'once'
3881 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3882 config => $config,
3883 pool => SVN::Pool->new,
3884 auth_provider_callbacks => $callbacks);
3885 $self->{url} = $url;
3886 $self->{svn_path} = $url;
3887 $self->{repos_root} = $self->get_repos_root;
3888 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3889 $self->{cache} = { check_path => { r => 0, data => {} },
3890 get_dir => { r => 0, data => {} } };
3891 $RA = bless $self, $class;
3894 sub check_path {
3895 my ($self, $path, $r) = @_;
3896 my $cache = $self->{cache}->{check_path};
3897 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3898 return $cache->{data}->{$path};
3900 my $pool = SVN::Pool->new;
3901 my $t = $self->SUPER::check_path($path, $r, $pool);
3902 $pool->clear;
3903 if ($r != $cache->{r}) {
3904 %{$cache->{data}} = ();
3905 $cache->{r} = $r;
3907 $cache->{data}->{$path} = $t;
3910 sub get_dir {
3911 my ($self, $dir, $r) = @_;
3912 my $cache = $self->{cache}->{get_dir};
3913 if ($r == $cache->{r}) {
3914 if (my $x = $cache->{data}->{$dir}) {
3915 return wantarray ? @$x : $x->[0];
3918 my $pool = SVN::Pool->new;
3919 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3920 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3921 $pool->clear;
3922 if ($r != $cache->{r}) {
3923 %{$cache->{data}} = ();
3924 $cache->{r} = $r;
3926 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3927 wantarray ? (\%dirents, $r, $props) : \%dirents;
3930 sub DESTROY {
3931 # do not call the real DESTROY since we store ourselves in $RA
3934 sub get_log {
3935 my ($self, @args) = @_;
3936 my $pool = SVN::Pool->new;
3937 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3938 my $ret = $self->SUPER::get_log(@args, $pool);
3939 $pool->clear;
3940 $ret;
3943 sub trees_match {
3944 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3945 my $ctx = SVN::Client->new(auth => _auth_providers);
3946 my $out = IO::File->new_tmpfile;
3948 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3949 # $ctx->diff(), so we'll create a default one
3950 my $pool = SVN::Pool->new_default_sub;
3952 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3953 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3954 $out->flush;
3955 my $ret = (($out->stat)[7] == 0);
3956 close $out or croak $!;
3958 $ret;
3961 sub get_commit_editor {
3962 my ($self, $log, $cb, $pool) = @_;
3963 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3964 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3967 sub gs_do_update {
3968 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3969 my $new = ($rev_a == $rev_b);
3970 my $path = $gs->{path};
3972 if ($new && -e $gs->{index}) {
3973 unlink $gs->{index} or die
3974 "Couldn't unlink index: $gs->{index}: $!\n";
3976 my $pool = SVN::Pool->new;
3977 $editor->set_path_strip($path);
3978 my (@pc) = split m#/#, $path;
3979 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3980 1, $editor, $pool);
3981 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3983 # Since we can't rely on svn_ra_reparent being available, we'll
3984 # just have to do some magic with set_path to make it so
3985 # we only want a partial path.
3986 my $sp = '';
3987 my $final = join('/', @pc);
3988 while (@pc) {
3989 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3990 $sp .= '/' if length $sp;
3991 $sp .= shift @pc;
3993 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3995 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3997 $reporter->finish_report($pool);
3998 $pool->clear;
3999 $editor->{git_commit_ok};
4002 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4003 # svn_ra_reparent didn't work before 1.4)
4004 sub gs_do_switch {
4005 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4006 my $path = $gs->{path};
4007 my $pool = SVN::Pool->new;
4009 my $full_url = $self->{url};
4010 my $old_url = $full_url;
4011 $full_url .= '/' . escape_uri_only($path) if length $path;
4012 my ($ra, $reparented);
4014 if ($old_url =~ m#^svn(\+ssh)?://#) {
4015 $_[0] = undef;
4016 $self = undef;
4017 $RA = undef;
4018 $ra = Git::SVN::Ra->new($full_url);
4019 $ra_invalid = 1;
4020 } elsif ($old_url ne $full_url) {
4021 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4022 $self->{url} = $full_url;
4023 $reparented = 1;
4026 $ra ||= $self;
4027 $url_b = escape_url($url_b);
4028 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4029 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4030 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4031 $reporter->finish_report($pool);
4033 if ($reparented) {
4034 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4035 $self->{url} = $old_url;
4038 $pool->clear;
4039 $editor->{git_commit_ok};
4042 sub longest_common_path {
4043 my ($gsv, $globs) = @_;
4044 my %common;
4045 my $common_max = scalar @$gsv;
4047 foreach my $gs (@$gsv) {
4048 my @tmp = split m#/#, $gs->{path};
4049 my $p = '';
4050 foreach (@tmp) {
4051 $p .= length($p) ? "/$_" : $_;
4052 $common{$p} ||= 0;
4053 $common{$p}++;
4056 $globs ||= [];
4057 $common_max += scalar @$globs;
4058 foreach my $glob (@$globs) {
4059 my @tmp = split m#/#, $glob->{path}->{left};
4060 my $p = '';
4061 foreach (@tmp) {
4062 $p .= length($p) ? "/$_" : $_;
4063 $common{$p} ||= 0;
4064 $common{$p}++;
4068 my $longest_path = '';
4069 foreach (sort {length $b <=> length $a} keys %common) {
4070 if ($common{$_} == $common_max) {
4071 $longest_path = $_;
4072 last;
4075 $longest_path;
4078 sub gs_fetch_loop_common {
4079 my ($self, $base, $head, $gsv, $globs) = @_;
4080 return if ($base > $head);
4081 my $inc = $_log_window_size;
4082 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4083 my $longest_path = longest_common_path($gsv, $globs);
4084 my $ra_url = $self->{url};
4085 while (1) {
4086 my %revs;
4087 my $err;
4088 my $err_handler = $SVN::Error::handler;
4089 $SVN::Error::handler = sub {
4090 ($err) = @_;
4091 skip_unknown_revs($err);
4093 sub _cb {
4094 my ($paths, $r, $author, $date, $log) = @_;
4095 [ dup_changed_paths($paths),
4096 { author => $author, date => $date, log => $log } ];
4098 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4099 sub { $revs{$_[1]} = _cb(@_) });
4100 if ($err && $max >= $head) {
4101 print STDERR "Path '$longest_path' ",
4102 "was probably deleted:\n",
4103 $err->expanded_message,
4104 "\nWill attempt to follow ",
4105 "revisions r$min .. r$max ",
4106 "committed before the deletion\n";
4107 my $hi = $max;
4108 while (--$hi >= $min) {
4109 my $ok;
4110 $self->get_log([$longest_path], $min, $hi,
4111 0, 1, 1, sub {
4112 $ok ||= $_[1];
4113 $revs{$_[1]} = _cb(@_) });
4114 if ($ok) {
4115 print STDERR "r$min .. r$ok OK\n";
4116 last;
4120 $SVN::Error::handler = $err_handler;
4122 my %exists = map { $_->{path} => $_ } @$gsv;
4123 foreach my $r (sort {$a <=> $b} keys %revs) {
4124 my ($paths, $logged) = @{$revs{$r}};
4126 foreach my $gs ($self->match_globs(\%exists, $paths,
4127 $globs, $r)) {
4128 if ($gs->rev_map_max >= $r) {
4129 next;
4131 next unless $gs->match_paths($paths, $r);
4132 $gs->{logged_rev_props} = $logged;
4133 if (my $last_commit = $gs->last_commit) {
4134 $gs->assert_index_clean($last_commit);
4136 my $log_entry = $gs->do_fetch($paths, $r);
4137 if ($log_entry) {
4138 $gs->do_git_commit($log_entry);
4140 $INDEX_FILES{$gs->{index}} = 1;
4142 foreach my $g (@$globs) {
4143 my $k = "svn-remote.$g->{remote}." .
4144 "$g->{t}-maxRev";
4145 Git::SVN::tmp_config($k, $r);
4147 if ($ra_invalid) {
4148 $_[0] = undef;
4149 $self = undef;
4150 $RA = undef;
4151 $self = Git::SVN::Ra->new($ra_url);
4152 $ra_invalid = undef;
4155 # pre-fill the .rev_db since it'll eventually get filled in
4156 # with '0' x40 if something new gets committed
4157 foreach my $gs (@$gsv) {
4158 next if $gs->rev_map_max >= $max;
4159 next if defined $gs->rev_map_get($max);
4160 $gs->rev_map_set($max, 0 x40);
4162 foreach my $g (@$globs) {
4163 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4164 Git::SVN::tmp_config($k, $max);
4166 last if $max >= $head;
4167 $min = $max + 1;
4168 $max += $inc;
4169 $max = $head if ($max > $head);
4171 Git::SVN::gc();
4174 sub get_dir_globbed {
4175 my ($self, $left, $depth, $r) = @_;
4177 my @x = eval { $self->get_dir($left, $r) };
4178 return unless scalar @x == 3;
4179 my $dirents = $x[0];
4180 my @finalents;
4181 foreach my $de (keys %$dirents) {
4182 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4183 if ($depth > 1) {
4184 my @args = ("$left/$de", $depth - 1, $r);
4185 foreach my $dir ($self->get_dir_globbed(@args)) {
4186 push @finalents, "$de/$dir";
4188 } else {
4189 push @finalents, $de;
4192 @finalents;
4195 sub match_globs {
4196 my ($self, $exists, $paths, $globs, $r) = @_;
4198 sub get_dir_check {
4199 my ($self, $exists, $g, $r) = @_;
4201 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4202 $g->{path}->{depth},
4203 $r);
4205 foreach my $de (@dirs) {
4206 my $p = $g->{path}->full_path($de);
4207 next if $exists->{$p};
4208 next if (length $g->{path}->{right} &&
4209 ($self->check_path($p, $r) !=
4210 $SVN::Node::dir));
4211 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4212 $g->{ref}->full_path($de), 1);
4215 foreach my $g (@$globs) {
4216 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4217 if ($path->{action} =~ /^[AR]$/) {
4218 get_dir_check($self, $exists, $g, $r);
4221 foreach (keys %$paths) {
4222 if (/$g->{path}->{left_regex}/ &&
4223 !/$g->{path}->{regex}/) {
4224 next if $paths->{$_}->{action} !~ /^[AR]$/;
4225 get_dir_check($self, $exists, $g, $r);
4227 next unless /$g->{path}->{regex}/;
4228 my $p = $1;
4229 my $pathname = $g->{path}->full_path($p);
4230 next if $exists->{$pathname};
4231 next if ($self->check_path($pathname, $r) !=
4232 $SVN::Node::dir);
4233 $exists->{$pathname} = Git::SVN->init(
4234 $self->{url}, $pathname, undef,
4235 $g->{ref}->full_path($p), 1);
4237 my $c = '';
4238 foreach (split m#/#, $g->{path}->{left}) {
4239 $c .= "/$_";
4240 next unless ($paths->{$c} &&
4241 ($paths->{$c}->{action} =~ /^[AR]$/));
4242 get_dir_check($self, $exists, $g, $r);
4245 values %$exists;
4248 sub minimize_url {
4249 my ($self) = @_;
4250 return $self->{url} if ($self->{url} eq $self->{repos_root});
4251 my $url = $self->{repos_root};
4252 my @components = split(m!/!, $self->{svn_path});
4253 my $c = '';
4254 do {
4255 $url .= "/$c" if length $c;
4256 eval { (ref $self)->new($url)->get_latest_revnum };
4257 } while ($@ && ($c = shift @components));
4258 $url;
4261 sub can_do_switch {
4262 my $self = shift;
4263 unless (defined $can_do_switch) {
4264 my $pool = SVN::Pool->new;
4265 my $rep = eval {
4266 $self->do_switch(1, '', 0, $self->{url},
4267 SVN::Delta::Editor->new, $pool);
4269 if ($@) {
4270 $can_do_switch = 0;
4271 } else {
4272 $rep->abort_report($pool);
4273 $can_do_switch = 1;
4275 $pool->clear;
4277 $can_do_switch;
4280 sub skip_unknown_revs {
4281 my ($err) = @_;
4282 my $errno = $err->apr_err();
4283 # Maybe the branch we're tracking didn't
4284 # exist when the repo started, so it's
4285 # not an error if it doesn't, just continue
4287 # Wonderfully consistent library, eh?
4288 # 160013 - svn:// and file://
4289 # 175002 - http(s)://
4290 # 175007 - http(s):// (this repo required authorization, too...)
4291 # More codes may be discovered later...
4292 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4293 my $err_key = $err->expanded_message;
4294 # revision numbers change every time, filter them out
4295 $err_key =~ s/\d+/\0/g;
4296 $err_key = "$errno\0$err_key";
4297 unless ($ignored_err{$err_key}) {
4298 warn "W: Ignoring error from SVN, path probably ",
4299 "does not exist: ($errno): ",
4300 $err->expanded_message,"\n";
4301 warn "W: Do not be alarmed at the above message ",
4302 "git-svn is just searching aggressively for ",
4303 "old history.\n",
4304 "This may take a while on large repositories\n";
4305 $ignored_err{$err_key} = 1;
4307 return;
4309 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4312 # svn_log_changed_path_t objects passed to get_log are likely to be
4313 # overwritten even if only the refs are copied to an external variable,
4314 # so we should dup the structures in their entirety. Using an externally
4315 # passed pool (instead of our temporary and quickly cleared pool in
4316 # Git::SVN::Ra) does not help matters at all...
4317 sub dup_changed_paths {
4318 my ($paths) = @_;
4319 return undef unless $paths;
4320 my %ret;
4321 foreach my $p (keys %$paths) {
4322 my $i = $paths->{$p};
4323 my %s = map { $_ => $i->$_ }
4324 qw/copyfrom_path copyfrom_rev action/;
4325 $ret{$p} = \%s;
4327 \%ret;
4330 package Git::SVN::Log;
4331 use strict;
4332 use warnings;
4333 use POSIX qw/strftime/;
4334 use constant commit_log_separator => ('-' x 72) . "\n";
4335 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4336 %rusers $show_commit $incremental/;
4337 my $l_fmt;
4339 sub cmt_showable {
4340 my ($c) = @_;
4341 return 1 if defined $c->{r};
4343 # big commit message got truncated by the 16k pretty buffer in rev-list
4344 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4345 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4346 @{$c->{l}} = ();
4347 my @log = command(qw/cat-file commit/, $c->{c});
4349 # shift off the headers
4350 shift @log while ($log[0] ne '');
4351 shift @log;
4353 # TODO: make $c->{l} not have a trailing newline in the future
4354 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4356 (undef, $c->{r}, undef) = ::extract_metadata(
4357 (grep(/^git-svn-id: /, @log))[-1]);
4359 return defined $c->{r};
4362 sub log_use_color {
4363 return $color || Git->repository->get_colorbool('color.diff');
4366 sub git_svn_log_cmd {
4367 my ($r_min, $r_max, @args) = @_;
4368 my $head = 'HEAD';
4369 my (@files, @log_opts);
4370 foreach my $x (@args) {
4371 if ($x eq '--' || @files) {
4372 push @files, $x;
4373 } else {
4374 if (::verify_ref("$x^0")) {
4375 $head = $x;
4376 } else {
4377 push @log_opts, $x;
4382 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4383 $gs ||= Git::SVN->_new;
4384 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4385 $gs->refname);
4386 push @cmd, '-r' unless $non_recursive;
4387 push @cmd, qw/--raw --name-status/ if $verbose;
4388 push @cmd, '--color' if log_use_color();
4389 push @cmd, @log_opts;
4390 if (defined $r_max && $r_max == $r_min) {
4391 push @cmd, '--max-count=1';
4392 if (my $c = $gs->rev_map_get($r_max)) {
4393 push @cmd, $c;
4395 } elsif (defined $r_max) {
4396 if ($r_max < $r_min) {
4397 ($r_min, $r_max) = ($r_max, $r_min);
4399 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4400 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4401 # If there are no commits in the range, both $c_max and $c_min
4402 # will be undefined. If there is at least 1 commit in the
4403 # range, both will be defined.
4404 return () if !defined $c_min || !defined $c_max;
4405 if ($c_min eq $c_max) {
4406 push @cmd, '--max-count=1', $c_min;
4407 } else {
4408 push @cmd, '--boundary', "$c_min..$c_max";
4411 return (@cmd, @files);
4414 # adapted from pager.c
4415 sub config_pager {
4416 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4417 if (!defined $pager) {
4418 $pager = 'less';
4419 } elsif (length $pager == 0 || $pager eq 'cat') {
4420 $pager = undef;
4422 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4425 sub run_pager {
4426 return unless -t *STDOUT && defined $pager;
4427 pipe my ($rfd, $wfd) or return;
4428 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4429 if (!$pid) {
4430 open STDOUT, '>&', $wfd or
4431 ::fatal "Can't redirect to stdout: $!";
4432 return;
4434 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4435 $ENV{LESS} ||= 'FRSX';
4436 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4439 sub format_svn_date {
4440 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4443 sub parse_git_date {
4444 my ($t, $tz) = @_;
4445 # Date::Parse isn't in the standard Perl distro :(
4446 if ($tz =~ s/^\+//) {
4447 $t += tz_to_s_offset($tz);
4448 } elsif ($tz =~ s/^\-//) {
4449 $t -= tz_to_s_offset($tz);
4451 return $t;
4454 sub set_local_timezone {
4455 if (defined $TZ) {
4456 $ENV{TZ} = $TZ;
4457 } else {
4458 delete $ENV{TZ};
4462 sub tz_to_s_offset {
4463 my ($tz) = @_;
4464 $tz =~ s/(\d\d)$//;
4465 return ($1 * 60) + ($tz * 3600);
4468 sub get_author_info {
4469 my ($dest, $author, $t, $tz) = @_;
4470 $author =~ s/(?:^\s*|\s*$)//g;
4471 $dest->{a_raw} = $author;
4472 my $au;
4473 if ($::_authors) {
4474 $au = $rusers{$author} || undef;
4476 if (!$au) {
4477 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4479 $dest->{t} = $t;
4480 $dest->{tz} = $tz;
4481 $dest->{a} = $au;
4482 $dest->{t_utc} = parse_git_date($t, $tz);
4485 sub process_commit {
4486 my ($c, $r_min, $r_max, $defer) = @_;
4487 if (defined $r_min && defined $r_max) {
4488 if ($r_min == $c->{r} && $r_min == $r_max) {
4489 show_commit($c);
4490 return 0;
4492 return 1 if $r_min == $r_max;
4493 if ($r_min < $r_max) {
4494 # we need to reverse the print order
4495 return 0 if (defined $limit && --$limit < 0);
4496 push @$defer, $c;
4497 return 1;
4499 if ($r_min != $r_max) {
4500 return 1 if ($r_min < $c->{r});
4501 return 1 if ($r_max > $c->{r});
4504 return 0 if (defined $limit && --$limit < 0);
4505 show_commit($c);
4506 return 1;
4509 sub show_commit {
4510 my $c = shift;
4511 if ($oneline) {
4512 my $x = "\n";
4513 if (my $l = $c->{l}) {
4514 while ($l->[0] =~ /^\s*$/) { shift @$l }
4515 $x = $l->[0];
4517 $l_fmt ||= 'A' . length($c->{r});
4518 print 'r',pack($l_fmt, $c->{r}),' | ';
4519 print "$c->{c} | " if $show_commit;
4520 print $x;
4521 } else {
4522 show_commit_normal($c);
4526 sub show_commit_changed_paths {
4527 my ($c) = @_;
4528 return unless $c->{changed};
4529 print "Changed paths:\n", @{$c->{changed}};
4532 sub show_commit_normal {
4533 my ($c) = @_;
4534 print commit_log_separator, "r$c->{r} | ";
4535 print "$c->{c} | " if $show_commit;
4536 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4537 my $nr_line = 0;
4539 if (my $l = $c->{l}) {
4540 while ($l->[$#$l] eq "\n" && $#$l > 0
4541 && $l->[($#$l - 1)] eq "\n") {
4542 pop @$l;
4544 $nr_line = scalar @$l;
4545 if (!$nr_line) {
4546 print "1 line\n\n\n";
4547 } else {
4548 if ($nr_line == 1) {
4549 $nr_line = '1 line';
4550 } else {
4551 $nr_line .= ' lines';
4553 print $nr_line, "\n";
4554 show_commit_changed_paths($c);
4555 print "\n";
4556 print $_ foreach @$l;
4558 } else {
4559 print "1 line\n";
4560 show_commit_changed_paths($c);
4561 print "\n";
4564 foreach my $x (qw/raw stat diff/) {
4565 if ($c->{$x}) {
4566 print "\n";
4567 print $_ foreach @{$c->{$x}}
4572 sub cmd_show_log {
4573 my (@args) = @_;
4574 my ($r_min, $r_max);
4575 my $r_last = -1; # prevent dupes
4576 set_local_timezone();
4577 if (defined $::_revision) {
4578 if ($::_revision =~ /^(\d+):(\d+)$/) {
4579 ($r_min, $r_max) = ($1, $2);
4580 } elsif ($::_revision =~ /^\d+$/) {
4581 $r_min = $r_max = $::_revision;
4582 } else {
4583 ::fatal "-r$::_revision is not supported, use ",
4584 "standard 'git log' arguments instead";
4588 config_pager();
4589 @args = git_svn_log_cmd($r_min, $r_max, @args);
4590 if (!@args) {
4591 print commit_log_separator unless $incremental || $oneline;
4592 return;
4594 my $log = command_output_pipe(@args);
4595 run_pager();
4596 my (@k, $c, $d, $stat);
4597 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4598 while (<$log>) {
4599 if (/^${esc_color}commit -?($::sha1_short)/o) {
4600 my $cmt = $1;
4601 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4602 $r_last = $c->{r};
4603 process_commit($c, $r_min, $r_max, \@k) or
4604 goto out;
4606 $d = undef;
4607 $c = { c => $cmt };
4608 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4609 get_author_info($c, $1, $2, $3);
4610 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4611 # ignore
4612 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4613 push @{$c->{raw}}, $_;
4614 } elsif (/^${esc_color}[ACRMDT]\t/) {
4615 # we could add $SVN->{svn_path} here, but that requires
4616 # remote access at the moment (repo_path_split)...
4617 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4618 push @{$c->{changed}}, $_;
4619 } elsif (/^${esc_color}diff /o) {
4620 $d = 1;
4621 push @{$c->{diff}}, $_;
4622 } elsif ($d) {
4623 push @{$c->{diff}}, $_;
4624 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4625 $esc_color*[\+\-]*$esc_color$/x) {
4626 $stat = 1;
4627 push @{$c->{stat}}, $_;
4628 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4629 push @{$c->{stat}}, $_;
4630 $stat = undef;
4631 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4632 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4633 } elsif (s/^${esc_color} //o) {
4634 push @{$c->{l}}, $_;
4637 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4638 $r_last = $c->{r};
4639 process_commit($c, $r_min, $r_max, \@k);
4641 if (@k) {
4642 ($r_min, $r_max) = ($r_max, $r_min);
4643 process_commit($_, $r_min, $r_max) foreach reverse @k;
4645 out:
4646 close $log;
4647 print commit_log_separator unless $incremental || $oneline;
4650 sub cmd_blame {
4651 my $path = pop;
4653 config_pager();
4654 run_pager();
4656 my ($fh, $ctx, $rev);
4658 if ($_git_format) {
4659 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4660 while (my $line = <$fh>) {
4661 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4662 # Uncommitted edits show up as a rev ID of
4663 # all zeros, which we can't look up with
4664 # cmt_metadata
4665 if ($1 !~ /^0+$/) {
4666 (undef, $rev, undef) =
4667 ::cmt_metadata($1);
4668 $rev = '0' if (!$rev);
4669 } else {
4670 $rev = '0';
4672 $rev = sprintf('%-10s', $rev);
4673 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4675 print $line;
4677 } else {
4678 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4679 '--', $path);
4680 my ($sha1);
4681 my %authors;
4682 while (my $line = <$fh>) {
4683 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4684 $sha1 = $1;
4685 (undef, $rev, undef) = ::cmt_metadata($1);
4686 $rev = '0' if (!$rev);
4688 elsif ($line =~ /^author (.*)/) {
4689 $authors{$rev} = $1;
4690 $authors{$rev} =~ s/\s/_/g;
4692 elsif ($line =~ /^\t(.*)$/) {
4693 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4697 command_close_pipe($fh, $ctx);
4700 package Git::SVN::Migration;
4701 # these version numbers do NOT correspond to actual version numbers
4702 # of git nor git-svn. They are just relative.
4704 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4706 # v1 layout: .git/$id/info/url, refs/remotes/$id
4708 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4710 # v3 layout: .git/svn/$id, refs/remotes/$id
4711 # - info/url may remain for backwards compatibility
4712 # - this is what we migrate up to this layout automatically,
4713 # - this will be used by git svn init on single branches
4714 # v3.1 layout (auto migrated):
4715 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4716 # for backwards compatibility
4718 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4719 # - this is only created for newly multi-init-ed
4720 # repositories. Similar in spirit to the
4721 # --use-separate-remotes option in git-clone (now default)
4722 # - we do not automatically migrate to this (following
4723 # the example set by core git)
4725 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4726 # - newer, more-efficient format that uses 24-bytes per record
4727 # with no filler space.
4728 # - use xxd -c24 < .rev_map.$UUID to view and debug
4729 # - This is a one-way migration, repositories updated to the
4730 # new format will not be able to use old git-svn without
4731 # rebuilding the .rev_db. Rebuilding the rev_db is not
4732 # possible if noMetadata or useSvmProps are set; but should
4733 # be no problem for users that use the (sensible) defaults.
4734 use strict;
4735 use warnings;
4736 use Carp qw/croak/;
4737 use File::Path qw/mkpath/;
4738 use File::Basename qw/dirname basename/;
4739 use vars qw/$_minimize/;
4741 sub migrate_from_v0 {
4742 my $git_dir = $ENV{GIT_DIR};
4743 return undef unless -d $git_dir;
4744 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4745 my $migrated = 0;
4746 while (<$fh>) {
4747 chomp;
4748 my ($id, $orig_ref) = ($_, $_);
4749 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4750 next unless -f "$git_dir/$id/info/url";
4751 my $new_ref = "refs/remotes/$id";
4752 if (::verify_ref("$new_ref^0")) {
4753 print STDERR "W: $orig_ref is probably an old ",
4754 "branch used by an ancient version of ",
4755 "git-svn.\n",
4756 "However, $new_ref also exists.\n",
4757 "We will not be able ",
4758 "to use this branch until this ",
4759 "ambiguity is resolved.\n";
4760 next;
4762 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4763 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4764 command_noisy('update-ref', $new_ref, $orig_ref);
4765 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4766 $migrated++;
4768 command_close_pipe($fh, $ctx);
4769 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4770 $migrated;
4773 sub migrate_from_v1 {
4774 my $git_dir = $ENV{GIT_DIR};
4775 my $migrated = 0;
4776 return $migrated unless -d $git_dir;
4777 my $svn_dir = "$git_dir/svn";
4779 # just in case somebody used 'svn' as their $id at some point...
4780 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4782 print STDERR "Migrating from a git-svn v1 layout...\n";
4783 mkpath([$svn_dir]);
4784 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4785 "$svn_dir\n\t(required for this version ",
4786 "($::VERSION) of git-svn) does not exist.\n";
4787 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4788 while (<$fh>) {
4789 my $x = $_;
4790 next unless $x =~ s#^refs/remotes/##;
4791 chomp $x;
4792 next unless -f "$git_dir/$x/info/url";
4793 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4794 next unless $u;
4795 my $dn = dirname("$git_dir/svn/$x");
4796 mkpath([$dn]) unless -d $dn;
4797 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4798 mkpath(["$git_dir/svn/svn"]);
4799 print STDERR " - $git_dir/$x/info => ",
4800 "$git_dir/svn/$x/info\n";
4801 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4802 croak "$!: $x";
4803 # don't worry too much about these, they probably
4804 # don't exist with repos this old (save for index,
4805 # and we can easily regenerate that)
4806 foreach my $f (qw/unhandled.log index .rev_db/) {
4807 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4809 } else {
4810 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4811 rename "$git_dir/$x", "$git_dir/svn/$x" or
4812 croak "$!: $x";
4814 $migrated++;
4816 command_close_pipe($fh, $ctx);
4817 print STDERR "Done migrating from a git-svn v1 layout\n";
4818 $migrated;
4821 sub read_old_urls {
4822 my ($l_map, $pfx, $path) = @_;
4823 my @dir;
4824 foreach (<$path/*>) {
4825 if (-r "$_/info/url") {
4826 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4827 my $ref_id = $pfx . basename $_;
4828 my $url = ::file_to_s("$_/info/url");
4829 $l_map->{$ref_id} = $url;
4830 } elsif (-d $_) {
4831 push @dir, $_;
4834 foreach (@dir) {
4835 my $x = $_;
4836 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4837 read_old_urls($l_map, $x, $_);
4841 sub migrate_from_v2 {
4842 my @cfg = command(qw/config -l/);
4843 return if grep /^svn-remote\..+\.url=/, @cfg;
4844 my %l_map;
4845 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4846 my $migrated = 0;
4848 foreach my $ref_id (sort keys %l_map) {
4849 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4850 if ($@) {
4851 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4853 $migrated++;
4855 $migrated;
4858 sub minimize_connections {
4859 my $r = Git::SVN::read_all_remotes();
4860 my $new_urls = {};
4861 my $root_repos = {};
4862 foreach my $repo_id (keys %$r) {
4863 my $url = $r->{$repo_id}->{url} or next;
4864 my $fetch = $r->{$repo_id}->{fetch} or next;
4865 my $ra = Git::SVN::Ra->new($url);
4867 # skip existing cases where we already connect to the root
4868 if (($ra->{url} eq $ra->{repos_root}) ||
4869 ($ra->{repos_root} eq $repo_id)) {
4870 $root_repos->{$ra->{url}} = $repo_id;
4871 next;
4874 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4875 my $root_path = $ra->{url};
4876 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4877 foreach my $path (keys %$fetch) {
4878 my $ref_id = $fetch->{$path};
4879 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4881 # make sure we can read when connecting to
4882 # a higher level of a repository
4883 my ($last_rev, undef) = $gs->last_rev_commit;
4884 if (!defined $last_rev) {
4885 $last_rev = eval {
4886 $root_ra->get_latest_revnum;
4888 next if $@;
4890 my $new = $root_path;
4891 $new .= length $path ? "/$path" : '';
4892 eval {
4893 $root_ra->get_log([$new], $last_rev, $last_rev,
4894 0, 0, 1, sub { });
4896 next if $@;
4897 $new_urls->{$ra->{repos_root}}->{$new} =
4898 { ref_id => $ref_id,
4899 old_repo_id => $repo_id,
4900 old_path => $path };
4904 my @emptied;
4905 foreach my $url (keys %$new_urls) {
4906 # see if we can re-use an existing [svn-remote "repo_id"]
4907 # instead of creating a(n ugly) new section:
4908 my $repo_id = $root_repos->{$url} || $url;
4910 my $fetch = $new_urls->{$url};
4911 foreach my $path (keys %$fetch) {
4912 my $x = $fetch->{$path};
4913 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4914 my $pfx = "svn-remote.$x->{old_repo_id}";
4916 my $old_fetch = quotemeta("$x->{old_path}:".
4917 "refs/remotes/$x->{ref_id}");
4918 command_noisy(qw/config --unset/,
4919 "$pfx.fetch", '^'. $old_fetch . '$');
4920 delete $r->{$x->{old_repo_id}}->
4921 {fetch}->{$x->{old_path}};
4922 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4923 command_noisy(qw/config --unset/,
4924 "$pfx.url");
4925 push @emptied, $x->{old_repo_id}
4929 if (@emptied) {
4930 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4931 "$ENV{GIT_DIR}/config";
4932 print STDERR <<EOF;
4933 The following [svn-remote] sections in your config file ($file) are empty
4934 and can be safely removed:
4936 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4940 sub migration_check {
4941 migrate_from_v0();
4942 migrate_from_v1();
4943 migrate_from_v2();
4944 minimize_connections() if $_minimize;
4947 package Git::IndexInfo;
4948 use strict;
4949 use warnings;
4950 use Git qw/command_input_pipe command_close_pipe/;
4952 sub new {
4953 my ($class) = @_;
4954 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4955 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4958 sub remove {
4959 my ($self, $path) = @_;
4960 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4961 return ++$self->{nr};
4963 undef;
4966 sub update {
4967 my ($self, $mode, $hash, $path) = @_;
4968 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4969 return ++$self->{nr};
4971 undef;
4974 sub DESTROY {
4975 my ($self) = @_;
4976 command_close_pipe($self->{gui}, $self->{ctx});
4979 package Git::SVN::GlobSpec;
4980 use strict;
4981 use warnings;
4983 sub new {
4984 my ($class, $glob) = @_;
4985 my $re = $glob;
4986 $re =~ s!/+$!!g; # no need for trailing slashes
4987 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
4988 my $temp = $re;
4989 my ($left, $right) = ($1, $3);
4990 $re = $2;
4991 my $depth = $re =~ tr/*/*/;
4992 if ($depth != $temp =~ tr/*/*/) {
4993 die "Only one set of wildcard directories " .
4994 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
4996 if ($depth == 0) {
4997 die "One '*' is needed for glob: '$glob'\n";
4999 $re =~ s!\*!\[^/\]*!g;
5000 $re = quotemeta($left) . "($re)" . quotemeta($right);
5001 if (length $left && !($left =~ s!/+$!!g)) {
5002 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5004 if (length $right && !($right =~ s!^/+!!g)) {
5005 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5007 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5008 bless { left => $left, right => $right, left_regex => $left_re,
5009 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5012 sub full_path {
5013 my ($self, $path) = @_;
5014 return (length $self->{left} ? "$self->{left}/" : '') .
5015 $path . (length $self->{right} ? "/$self->{right}" : '');
5018 __END__
5020 Data structures:
5023 $remotes = { # returned by read_all_remotes()
5024 'svn' => {
5025 # svn-remote.svn.url=https://svn.musicpd.org
5026 url => 'https://svn.musicpd.org',
5027 # svn-remote.svn.fetch=mpd/trunk:trunk
5028 fetch => {
5029 'mpd/trunk' => 'trunk',
5031 # svn-remote.svn.tags=mpd/tags/*:tags/*
5032 tags => {
5033 path => {
5034 left => 'mpd/tags',
5035 right => '',
5036 regex => qr!mpd/tags/([^/]+)$!,
5037 glob => 'tags/*',
5039 ref => {
5040 left => 'tags',
5041 right => '',
5042 regex => qr!tags/([^/]+)$!,
5043 glob => 'tags/*',
5049 $log_entry hashref as returned by libsvn_log_entry()
5051 log => 'whitespace-formatted log entry
5052 ', # trailing newline is preserved
5053 revision => '8', # integer
5054 date => '2004-02-24T17:01:44.108345Z', # commit date
5055 author => 'committer name'
5059 # this is generated by generate_diff();
5060 @mods = array of diff-index line hashes, each element represents one line
5061 of diff-index output
5063 diff-index line ($m hash)
5065 mode_a => first column of diff-index output, no leading ':',
5066 mode_b => second column of diff-index output,
5067 sha1_b => sha1sum of the final blob,
5068 chg => change type [MCRADT],
5069 file_a => original file name of a file (iff chg is 'C' or 'R')
5070 file_b => new/current file name of a file (any chg)
5074 # retval of read_url_paths{,_all}();
5075 $l_map = {
5076 # repository root url
5077 'https://svn.musicpd.org' => {
5078 # repository path # GIT_SVN_ID
5079 'mpd/trunk' => 'trunk',
5080 'mpd/tags/0.11.5' => 'tags/0.11.5',
5084 Notes:
5085 I don't trust the each() function on unless I created %hash myself
5086 because the internal iterator may not have started at base.