git-svn: Send deltas during commits
[alt-git.git] / git-svn.perl
blobfdf4e4a455cb80e2c145aad356638640491d6c8a
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 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
425 my $last_rev = $_revision if defined $_revision;
426 if ($url) {
427 print "Committing to $url ...\n";
429 unless ($gs) {
430 die "Unable to determine upstream SVN information from ",
431 "$head history.\nPerhaps the repository is empty.";
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 cmd_info {
807 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
808 if (exists $_[1]) {
809 die "Too many arguments specified\n";
812 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
814 if (!$file_type && !$diff_status) {
815 print STDERR "$path: (Not a versioned resource)\n\n";
816 return;
819 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
820 unless ($gs) {
821 die "Unable to determine upstream SVN information from ",
822 "working tree history\n";
825 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
826 $path = "." if $path eq "";
828 my $full_url = $url . ($path eq "." ? "" : "/$path");
830 if ($_url) {
831 print $full_url, "\n";
832 return;
835 my $result = "Path: $path\n";
836 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
837 $result .= "URL: " . $full_url . "\n";
839 eval {
840 my $repos_root = $gs->repos_root;
841 Git::SVN::remove_username($repos_root);
842 $result .= "Repository Root: $repos_root\n";
844 if ($@) {
845 $result .= "Repository Root: (offline)\n";
847 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
848 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
850 $result .= "Node Kind: " .
851 ($file_type eq "dir" ? "directory" : "file") . "\n";
853 my $schedule = $diff_status eq "A"
854 ? "add"
855 : ($diff_status eq "D" ? "delete" : "normal");
856 $result .= "Schedule: $schedule\n";
858 if ($diff_status eq "A") {
859 print $result, "\n";
860 return;
863 my ($lc_author, $lc_rev, $lc_date_utc);
864 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
865 my $log = command_output_pipe(@args);
866 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
867 while (<$log>) {
868 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
869 $lc_author = $1;
870 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
871 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
872 (undef, $lc_rev, undef) = ::extract_metadata($1);
875 close $log;
877 Git::SVN::Log::set_local_timezone();
879 $result .= "Last Changed Author: $lc_author\n";
880 $result .= "Last Changed Rev: $lc_rev\n";
881 $result .= "Last Changed Date: " .
882 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
884 if ($file_type ne "dir") {
885 my $text_last_updated_date =
886 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
887 $result .=
888 "Text Last Updated: " .
889 Git::SVN::Log::format_svn_date($text_last_updated_date) .
890 "\n";
891 my $checksum;
892 if ($diff_status eq "D") {
893 my ($fh, $ctx) =
894 command_output_pipe(qw(cat-file blob), "HEAD:$path");
895 if ($file_type eq "link") {
896 my $file_name = <$fh>;
897 $checksum = md5sum("link $file_name");
898 } else {
899 $checksum = md5sum($fh);
901 command_close_pipe($fh, $ctx);
902 } elsif ($file_type eq "link") {
903 my $file_name =
904 command(qw(cat-file blob), "HEAD:$path");
905 $checksum =
906 md5sum("link " . $file_name);
907 } else {
908 open FILE, "<", $path or die $!;
909 $checksum = md5sum(\*FILE);
910 close FILE or die $!;
912 $result .= "Checksum: " . $checksum . "\n";
915 print $result, "\n";
918 ########################### utility functions #########################
920 sub rebase_cmd {
921 my @cmd = qw/rebase/;
922 push @cmd, '-v' if $_verbose;
923 push @cmd, qw/--merge/ if $_merge;
924 push @cmd, "--strategy=$_strategy" if $_strategy;
925 @cmd;
928 sub post_fetch_checkout {
929 return if $_no_checkout;
930 my $gs = $Git::SVN::_head or return;
931 return if verify_ref('refs/heads/master^0');
933 my $valid_head = verify_ref('HEAD^0');
934 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
935 return if ($valid_head || !verify_ref('HEAD^0'));
937 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
938 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
939 return if -f $index;
941 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
942 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
943 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
944 print STDERR "Checked out HEAD:\n ",
945 $gs->full_url, " r", $gs->last_rev, "\n";
948 sub complete_svn_url {
949 my ($url, $path) = @_;
950 $path =~ s#/+$##;
951 if ($path !~ m#^[a-z\+]+://#) {
952 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
953 fatal("E: '$path' is not a complete URL ",
954 "and a separate URL is not specified");
956 return ($url, $path);
958 return ($path, '');
961 sub complete_url_ls_init {
962 my ($ra, $repo_path, $switch, $pfx) = @_;
963 unless ($repo_path) {
964 print STDERR "W: $switch not specified\n";
965 return;
967 $repo_path =~ s#/+$##;
968 if ($repo_path =~ m#^[a-z\+]+://#) {
969 $ra = Git::SVN::Ra->new($repo_path);
970 $repo_path = '';
971 } else {
972 $repo_path =~ s#^/+##;
973 unless ($ra) {
974 fatal("E: '$repo_path' is not a complete URL ",
975 "and a separate URL is not specified");
978 my $url = $ra->{url};
979 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
980 my $k = "svn-remote.$gs->{repo_id}.url";
981 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
982 if ($orig_url && ($orig_url ne $gs->{url})) {
983 die "$k already set: $orig_url\n",
984 "wanted to set to: $gs->{url}\n";
986 command_oneline('config', $k, $gs->{url}) unless $orig_url;
987 my $remote_path = "$ra->{svn_path}/$repo_path";
988 $remote_path =~ s#/+#/#g;
989 $remote_path =~ s#^/##g;
990 $remote_path .= "/*" if $remote_path !~ /\*/;
991 my ($n) = ($switch =~ /^--(\w+)/);
992 if (length $pfx && $pfx !~ m#/$#) {
993 die "--prefix='$pfx' must have a trailing slash '/'\n";
995 command_noisy('config',
996 "svn-remote.$gs->{repo_id}.$n",
997 "$remote_path:refs/remotes/$pfx*" .
998 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1001 sub verify_ref {
1002 my ($ref) = @_;
1003 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1004 { STDERR => 0 }); };
1007 sub get_tree_from_treeish {
1008 my ($treeish) = @_;
1009 # $treeish can be a symbolic ref, too:
1010 my $type = command_oneline(qw/cat-file -t/, $treeish);
1011 my $expected;
1012 while ($type eq 'tag') {
1013 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1015 if ($type eq 'commit') {
1016 $expected = (grep /^tree /, command(qw/cat-file commit/,
1017 $treeish))[0];
1018 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1019 die "Unable to get tree from $treeish\n" unless $expected;
1020 } elsif ($type eq 'tree') {
1021 $expected = $treeish;
1022 } else {
1023 die "$treeish is a $type, expected tree, tag or commit\n";
1025 return $expected;
1028 sub get_commit_entry {
1029 my ($treeish) = shift;
1030 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1031 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1032 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1033 open my $log_fh, '>', $commit_editmsg or croak $!;
1035 my $type = command_oneline(qw/cat-file -t/, $treeish);
1036 if ($type eq 'commit' || $type eq 'tag') {
1037 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1038 $type, $treeish);
1039 my $in_msg = 0;
1040 my $author;
1041 my $saw_from = 0;
1042 my $msgbuf = "";
1043 while (<$msg_fh>) {
1044 if (!$in_msg) {
1045 $in_msg = 1 if (/^\s*$/);
1046 $author = $1 if (/^author (.*>)/);
1047 } elsif (/^git-svn-id: /) {
1048 # skip this for now, we regenerate the
1049 # correct one on re-fetch anyways
1050 # TODO: set *:merge properties or like...
1051 } else {
1052 if (/^From:/ || /^Signed-off-by:/) {
1053 $saw_from = 1;
1055 $msgbuf .= $_;
1058 $msgbuf =~ s/\s+$//s;
1059 if ($Git::SVN::_add_author_from && defined($author)
1060 && !$saw_from) {
1061 $msgbuf .= "\n\nFrom: $author";
1063 print $log_fh $msgbuf or croak $!;
1064 command_close_pipe($msg_fh, $ctx);
1066 close $log_fh or croak $!;
1068 if ($_edit || ($type eq 'tree')) {
1069 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1070 # TODO: strip out spaces, comments, like git-commit.sh
1071 system($editor, $commit_editmsg);
1073 rename $commit_editmsg, $commit_msg or croak $!;
1074 open $log_fh, '<', $commit_msg or croak $!;
1075 { local $/; chomp($log_entry{log} = <$log_fh>); }
1076 close $log_fh or croak $!;
1077 unlink $commit_msg;
1078 \%log_entry;
1081 sub s_to_file {
1082 my ($str, $file, $mode) = @_;
1083 open my $fd,'>',$file or croak $!;
1084 print $fd $str,"\n" or croak $!;
1085 close $fd or croak $!;
1086 chmod ($mode &~ umask, $file) if (defined $mode);
1089 sub file_to_s {
1090 my $file = shift;
1091 open my $fd,'<',$file or croak "$!: file: $file\n";
1092 local $/;
1093 my $ret = <$fd>;
1094 close $fd or croak $!;
1095 $ret =~ s/\s*$//s;
1096 return $ret;
1099 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1100 sub load_authors {
1101 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1102 my $log = $cmd eq 'log';
1103 while (<$authors>) {
1104 chomp;
1105 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1106 my ($user, $name, $email) = ($1, $2, $3);
1107 if ($log) {
1108 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1109 } else {
1110 $users{$user} = [$name, $email];
1113 close $authors or croak $!;
1116 # convert GetOpt::Long specs for use by git-config
1117 sub read_repo_config {
1118 return unless -d $ENV{GIT_DIR};
1119 my $opts = shift;
1120 my @config_only;
1121 foreach my $o (keys %$opts) {
1122 # if we have mixedCase and a long option-only, then
1123 # it's a config-only variable that we don't need for
1124 # the command-line.
1125 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1126 my $v = $opts->{$o};
1127 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1128 $key =~ s/-//g;
1129 my $arg = 'git-config';
1130 $arg .= ' --int' if ($o =~ /[:=]i$/);
1131 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1132 if (ref $v eq 'ARRAY') {
1133 chomp(my @tmp = `$arg --get-all svn.$key`);
1134 @$v = @tmp if @tmp;
1135 } else {
1136 chomp(my $tmp = `$arg --get svn.$key`);
1137 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1138 $$v = $tmp;
1142 delete @$opts{@config_only} if @config_only;
1145 sub extract_metadata {
1146 my $id = shift or return (undef, undef, undef);
1147 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1148 \s([a-f\d\-]+)$/x);
1149 if (!defined $rev || !$uuid || !$url) {
1150 # some of the original repositories I made had
1151 # identifiers like this:
1152 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1154 return ($url, $rev, $uuid);
1157 sub cmt_metadata {
1158 return extract_metadata((grep(/^git-svn-id: /,
1159 command(qw/cat-file commit/, shift)))[-1]);
1162 sub working_head_info {
1163 my ($head, $refs) = @_;
1164 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1165 my ($fh, $ctx) = command_output_pipe(@args, $head);
1166 my $hash;
1167 my %max;
1168 while (<$fh>) {
1169 if ( m{^commit ($::sha1)$} ) {
1170 unshift @$refs, $hash if $hash and $refs;
1171 $hash = $1;
1172 next;
1174 next unless s{^\s*(git-svn-id:)}{$1};
1175 my ($url, $rev, $uuid) = extract_metadata($_);
1176 if (defined $url && defined $rev) {
1177 next if $max{$url} and $max{$url} < $rev;
1178 if (my $gs = Git::SVN->find_by_url($url)) {
1179 my $c = $gs->rev_map_get($rev, $uuid);
1180 if ($c && $c eq $hash) {
1181 close $fh; # break the pipe
1182 return ($url, $rev, $uuid, $gs);
1183 } else {
1184 $max{$url} ||= $gs->rev_map_max;
1189 command_close_pipe($fh, $ctx);
1190 (undef, undef, undef, undef);
1193 sub read_commit_parents {
1194 my ($parents, $c) = @_;
1195 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1196 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1197 @{$parents->{$c}} = split(/ /, $p);
1200 sub linearize_history {
1201 my ($gs, $refs) = @_;
1202 my %parents;
1203 foreach my $c (@$refs) {
1204 read_commit_parents(\%parents, $c);
1207 my @linear_refs;
1208 my %skip = ();
1209 my $last_svn_commit = $gs->last_commit;
1210 foreach my $c (reverse @$refs) {
1211 next if $c eq $last_svn_commit;
1212 last if $skip{$c};
1214 unshift @linear_refs, $c;
1215 $skip{$c} = 1;
1217 # we only want the first parent to diff against for linear
1218 # history, we save the rest to inject when we finalize the
1219 # svn commit
1220 my $fp_a = verify_ref("$c~1");
1221 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1222 if (!$fp_a || !$fp_b) {
1223 die "Commit $c\n",
1224 "has no parent commit, and therefore ",
1225 "nothing to diff against.\n",
1226 "You should be working from a repository ",
1227 "originally created by git-svn\n";
1229 if ($fp_a ne $fp_b) {
1230 die "$c~1 = $fp_a, however parsing commit $c ",
1231 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1234 foreach my $p (@{$parents{$c}}) {
1235 $skip{$p} = 1;
1238 (\@linear_refs, \%parents);
1241 sub find_file_type_and_diff_status {
1242 my ($path) = @_;
1243 return ('dir', '') if $path eq '';
1245 my $diff_output =
1246 command_oneline(qw(diff --cached --name-status --), $path) || "";
1247 my $diff_status = (split(' ', $diff_output))[0] || "";
1249 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1251 return (undef, undef) if !$diff_status && !$ls_tree;
1253 if ($diff_status eq "A") {
1254 return ("link", $diff_status) if -l $path;
1255 return ("dir", $diff_status) if -d $path;
1256 return ("file", $diff_status);
1259 my $mode = (split(' ', $ls_tree))[0] || "";
1261 return ("link", $diff_status) if $mode eq "120000";
1262 return ("dir", $diff_status) if $mode eq "040000";
1263 return ("file", $diff_status);
1266 sub md5sum {
1267 my $arg = shift;
1268 my $ref = ref $arg;
1269 my $md5 = Digest::MD5->new();
1270 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1271 $md5->addfile($arg) or croak $!;
1272 } elsif ($ref eq 'SCALAR') {
1273 $md5->add($$arg) or croak $!;
1274 } elsif (!$ref) {
1275 $md5->add($arg) or croak $!;
1276 } else {
1277 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1279 return $md5->hexdigest();
1282 package Git::SVN;
1283 use strict;
1284 use warnings;
1285 use Fcntl qw/:DEFAULT :seek/;
1286 use constant rev_map_fmt => 'NH40';
1287 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1288 $_repack $_repack_flags $_use_svm_props $_head
1289 $_use_svnsync_props $no_reuse_existing $_minimize_url
1290 $_use_log_author $_add_author_from/;
1291 use Carp qw/croak/;
1292 use File::Path qw/mkpath/;
1293 use File::Copy qw/copy/;
1294 use IPC::Open3;
1296 my ($_gc_nr, $_gc_period);
1298 # properties that we do not log:
1299 my %SKIP_PROP;
1300 BEGIN {
1301 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1302 svn:special svn:executable
1303 svn:entry:committed-rev
1304 svn:entry:last-author
1305 svn:entry:uuid
1306 svn:entry:committed-date/;
1308 # some options are read globally, but can be overridden locally
1309 # per [svn-remote "..."] section. Command-line options will *NOT*
1310 # override options set in an [svn-remote "..."] section
1311 no strict 'refs';
1312 for my $option (qw/follow_parent no_metadata use_svm_props
1313 use_svnsync_props/) {
1314 my $key = $option;
1315 $key =~ tr/_//d;
1316 my $prop = "-$option";
1317 *$option = sub {
1318 my ($self) = @_;
1319 return $self->{$prop} if exists $self->{$prop};
1320 my $k = "svn-remote.$self->{repo_id}.$key";
1321 eval { command_oneline(qw/config --get/, $k) };
1322 if ($@) {
1323 $self->{$prop} = ${"Git::SVN::_$option"};
1324 } else {
1325 my $v = command_oneline(qw/config --bool/,$k);
1326 $self->{$prop} = $v eq 'false' ? 0 : 1;
1328 return $self->{$prop};
1334 my (%LOCKFILES, %INDEX_FILES);
1335 END {
1336 unlink keys %LOCKFILES if %LOCKFILES;
1337 unlink keys %INDEX_FILES if %INDEX_FILES;
1340 sub resolve_local_globs {
1341 my ($url, $fetch, $glob_spec) = @_;
1342 return unless defined $glob_spec;
1343 my $ref = $glob_spec->{ref};
1344 my $path = $glob_spec->{path};
1345 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1346 next unless m#^refs/remotes/$ref->{regex}$#;
1347 my $p = $1;
1348 my $pathname = desanitize_refname($path->full_path($p));
1349 my $refname = desanitize_refname($ref->full_path($p));
1350 if (my $existing = $fetch->{$pathname}) {
1351 if ($existing ne $refname) {
1352 die "Refspec conflict:\n",
1353 "existing: refs/remotes/$existing\n",
1354 " globbed: refs/remotes/$refname\n";
1356 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1357 $u =~ s!^\Q$url\E(/|$)!! or die
1358 "refs/remotes/$refname: '$url' not found in '$u'\n";
1359 if ($pathname ne $u) {
1360 warn "W: Refspec glob conflict ",
1361 "(ref: refs/remotes/$refname):\n",
1362 "expected path: $pathname\n",
1363 " real path: $u\n",
1364 "Continuing ahead with $u\n";
1365 next;
1367 } else {
1368 $fetch->{$pathname} = $refname;
1373 sub parse_revision_argument {
1374 my ($base, $head) = @_;
1375 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1376 return ($base, $head);
1378 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1379 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1380 return ($head, $head) if ($::_revision eq 'HEAD');
1381 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1382 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1383 die "revision argument: $::_revision not understood by git-svn\n";
1386 sub fetch_all {
1387 my ($repo_id, $remotes) = @_;
1388 if (ref $repo_id) {
1389 my $gs = $repo_id;
1390 $repo_id = undef;
1391 $repo_id = $gs->{repo_id};
1393 $remotes ||= read_all_remotes();
1394 my $remote = $remotes->{$repo_id} or
1395 die "[svn-remote \"$repo_id\"] unknown\n";
1396 my $fetch = $remote->{fetch};
1397 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1398 my (@gs, @globs);
1399 my $ra = Git::SVN::Ra->new($url);
1400 my $uuid = $ra->get_uuid;
1401 my $head = $ra->get_latest_revnum;
1402 my $base = defined $fetch ? $head : 0;
1404 # read the max revs for wildcard expansion (branches/*, tags/*)
1405 foreach my $t (qw/branches tags/) {
1406 defined $remote->{$t} or next;
1407 push @globs, $remote->{$t};
1408 my $max_rev = eval { tmp_config(qw/--int --get/,
1409 "svn-remote.$repo_id.${t}-maxRev") };
1410 if (defined $max_rev && ($max_rev < $base)) {
1411 $base = $max_rev;
1412 } elsif (!defined $max_rev) {
1413 $base = 0;
1417 if ($fetch) {
1418 foreach my $p (sort keys %$fetch) {
1419 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1420 my $lr = $gs->rev_map_max;
1421 if (defined $lr) {
1422 $base = $lr if ($lr < $base);
1424 push @gs, $gs;
1428 ($base, $head) = parse_revision_argument($base, $head);
1429 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1432 sub read_all_remotes {
1433 my $r = {};
1434 my $use_svm_props = eval { command_oneline(qw/config --bool
1435 svn.useSvmProps/) };
1436 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1437 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1438 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1439 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1440 die("svn-remote.$remote: remote ref '$_remote_ref' "
1441 . "must start with 'refs/remotes/'\n")
1442 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1443 my $remote_ref = $1;
1444 $local_ref =~ s{^/}{};
1445 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1446 $r->{$remote}->{svm} = {} if $use_svm_props;
1447 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1448 $r->{$1}->{svm} = {};
1449 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1450 $r->{$1}->{url} = $2;
1451 } elsif (m!^(.+)\.(branches|tags)=
1452 (.*):refs/remotes/(.+)\s*$/!x) {
1453 my ($p, $g) = ($3, $4);
1454 my $rs = $r->{$1}->{$2} = {
1455 t => $2,
1456 remote => $1,
1457 path => Git::SVN::GlobSpec->new($p),
1458 ref => Git::SVN::GlobSpec->new($g) };
1459 if (length($rs->{ref}->{right}) != 0) {
1460 die "The '*' glob character must be the last ",
1461 "character of '$g'\n";
1466 map {
1467 if (defined $r->{$_}->{svm}) {
1468 my $svm;
1469 eval {
1470 my $section = "svn-remote.$_";
1471 $svm = {
1472 source => tmp_config('--get',
1473 "$section.svm-source"),
1474 replace => tmp_config('--get',
1475 "$section.svm-replace"),
1478 $r->{$_}->{svm} = $svm;
1480 } keys %$r;
1485 sub init_vars {
1486 $_gc_nr = $_gc_period = 1000;
1487 if (defined $_repack || defined $_repack_flags) {
1488 warn "Repack options are obsolete; they have no effect.\n";
1492 sub verify_remotes_sanity {
1493 return unless -d $ENV{GIT_DIR};
1494 my %seen;
1495 foreach (command(qw/config -l/)) {
1496 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1497 if ($seen{$1}) {
1498 die "Remote ref refs/remote/$1 is tracked by",
1499 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1500 "Please resolve this ambiguity in ",
1501 "your git configuration file before ",
1502 "continuing\n";
1504 $seen{$1} = $_;
1509 sub find_existing_remote {
1510 my ($url, $remotes) = @_;
1511 return undef if $no_reuse_existing;
1512 my $existing;
1513 foreach my $repo_id (keys %$remotes) {
1514 my $u = $remotes->{$repo_id}->{url} or next;
1515 next if $u ne $url;
1516 $existing = $repo_id;
1517 last;
1519 $existing;
1522 sub init_remote_config {
1523 my ($self, $url, $no_write) = @_;
1524 $url =~ s!/+$!!; # strip trailing slash
1525 my $r = read_all_remotes();
1526 my $existing = find_existing_remote($url, $r);
1527 if ($existing) {
1528 unless ($no_write) {
1529 print STDERR "Using existing ",
1530 "[svn-remote \"$existing\"]\n";
1532 $self->{repo_id} = $existing;
1533 } elsif ($_minimize_url) {
1534 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1535 $existing = find_existing_remote($min_url, $r);
1536 if ($existing) {
1537 unless ($no_write) {
1538 print STDERR "Using existing ",
1539 "[svn-remote \"$existing\"]\n";
1541 $self->{repo_id} = $existing;
1543 if ($min_url ne $url) {
1544 unless ($no_write) {
1545 print STDERR "Using higher level of URL: ",
1546 "$url => $min_url\n";
1548 my $old_path = $self->{path};
1549 $self->{path} = $url;
1550 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1551 if (length $old_path) {
1552 $self->{path} .= "/$old_path";
1554 $url = $min_url;
1557 my $orig_url;
1558 if (!$existing) {
1559 # verify that we aren't overwriting anything:
1560 $orig_url = eval {
1561 command_oneline('config', '--get',
1562 "svn-remote.$self->{repo_id}.url")
1564 if ($orig_url && ($orig_url ne $url)) {
1565 die "svn-remote.$self->{repo_id}.url already set: ",
1566 "$orig_url\nwanted to set to: $url\n";
1569 my ($xrepo_id, $xpath) = find_ref($self->refname);
1570 if (defined $xpath) {
1571 die "svn-remote.$xrepo_id.fetch already set to track ",
1572 "$xpath:refs/remotes/", $self->refname, "\n";
1574 unless ($no_write) {
1575 command_noisy('config',
1576 "svn-remote.$self->{repo_id}.url", $url);
1577 $self->{path} =~ s{^/}{};
1578 command_noisy('config', '--add',
1579 "svn-remote.$self->{repo_id}.fetch",
1580 "$self->{path}:".$self->refname);
1582 $self->{url} = $url;
1585 sub find_by_url { # repos_root and, path are optional
1586 my ($class, $full_url, $repos_root, $path) = @_;
1588 return undef unless defined $full_url;
1589 remove_username($full_url);
1590 remove_username($repos_root) if defined $repos_root;
1591 my $remotes = read_all_remotes();
1592 if (defined $full_url && defined $repos_root && !defined $path) {
1593 $path = $full_url;
1594 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1596 foreach my $repo_id (keys %$remotes) {
1597 my $u = $remotes->{$repo_id}->{url} or next;
1598 remove_username($u);
1599 next if defined $repos_root && $repos_root ne $u;
1601 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1602 foreach (qw/branches tags/) {
1603 resolve_local_globs($u, $fetch,
1604 $remotes->{$repo_id}->{$_});
1606 my $p = $path;
1607 my $rwr = rewrite_root({repo_id => $repo_id});
1608 my $svm = $remotes->{$repo_id}->{svm}
1609 if defined $remotes->{$repo_id}->{svm};
1610 unless (defined $p) {
1611 $p = $full_url;
1612 my $z = $u;
1613 my $prefix = '';
1614 if ($rwr) {
1615 $z = $rwr;
1616 } elsif (defined $svm) {
1617 $z = $svm->{source};
1618 $prefix = $svm->{replace};
1619 $prefix =~ s#^\Q$u\E(?:/|$)##;
1620 $prefix =~ s#/$##;
1622 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1624 foreach my $f (keys %$fetch) {
1625 next if $f ne $p;
1626 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1629 undef;
1632 sub init {
1633 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1634 my $self = _new($class, $repo_id, $ref_id, $path);
1635 if (defined $url) {
1636 $self->init_remote_config($url, $no_write);
1638 $self;
1641 sub find_ref {
1642 my ($ref_id) = @_;
1643 foreach (command(qw/config -l/)) {
1644 next unless m!^svn-remote\.(.+)\.fetch=
1645 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1646 my ($repo_id, $path, $ref) = ($1, $2, $3);
1647 if ($ref eq $ref_id) {
1648 $path = '' if ($path =~ m#^\./?#);
1649 return ($repo_id, $path);
1652 (undef, undef, undef);
1655 sub new {
1656 my ($class, $ref_id, $repo_id, $path) = @_;
1657 if (defined $ref_id && !defined $repo_id && !defined $path) {
1658 ($repo_id, $path) = find_ref($ref_id);
1659 if (!defined $repo_id) {
1660 die "Could not find a \"svn-remote.*.fetch\" key ",
1661 "in the repository configuration matching: ",
1662 "refs/remotes/$ref_id\n";
1665 my $self = _new($class, $repo_id, $ref_id, $path);
1666 if (!defined $self->{path} || !length $self->{path}) {
1667 my $fetch = command_oneline('config', '--get',
1668 "svn-remote.$repo_id.fetch",
1669 ":refs/remotes/$ref_id\$") or
1670 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1671 "\":refs/remotes/$ref_id\$\" in config\n";
1672 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1674 $self->{url} = command_oneline('config', '--get',
1675 "svn-remote.$repo_id.url") or
1676 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1677 $self->rebuild;
1678 $self;
1681 sub refname {
1682 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1684 # It cannot end with a slash /, we'll throw up on this because
1685 # SVN can't have directories with a slash in their name, either:
1686 if ($refname =~ m{/$}) {
1687 die "ref: '$refname' ends with a trailing slash, this is ",
1688 "not permitted by git nor Subversion\n";
1691 # It cannot have ASCII control character space, tilde ~, caret ^,
1692 # colon :, question-mark ?, asterisk *, space, or open bracket [
1693 # anywhere.
1695 # Additionally, % must be escaped because it is used for escaping
1696 # and we want our escaped refname to be reversible
1697 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1699 # no slash-separated component can begin with a dot .
1700 # /.* becomes /%2E*
1701 $refname =~ s{/\.}{/%2E}g;
1703 # It cannot have two consecutive dots .. anywhere
1704 # .. becomes %2E%2E
1705 $refname =~ s{\.\.}{%2E%2E}g;
1707 return $refname;
1710 sub desanitize_refname {
1711 my ($refname) = @_;
1712 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1713 return $refname;
1716 sub svm_uuid {
1717 my ($self) = @_;
1718 return $self->{svm}->{uuid} if $self->svm;
1719 $self->ra;
1720 unless ($self->{svm}) {
1721 die "SVM UUID not cached, and reading remotely failed\n";
1723 $self->{svm}->{uuid};
1726 sub svm {
1727 my ($self) = @_;
1728 return $self->{svm} if $self->{svm};
1729 my $svm;
1730 # see if we have it in our config, first:
1731 eval {
1732 my $section = "svn-remote.$self->{repo_id}";
1733 $svm = {
1734 source => tmp_config('--get', "$section.svm-source"),
1735 uuid => tmp_config('--get', "$section.svm-uuid"),
1736 replace => tmp_config('--get', "$section.svm-replace"),
1739 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1740 $self->{svm} = $svm;
1742 $self->{svm};
1745 sub _set_svm_vars {
1746 my ($self, $ra) = @_;
1747 return $ra if $self->svm;
1749 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1750 "(svm:source, svm:uuid) ",
1751 "from the following URLs:\n" );
1752 sub read_svm_props {
1753 my ($self, $ra, $path, $r) = @_;
1754 my $props = ($ra->get_dir($path, $r))[2];
1755 my $src = $props->{'svm:source'};
1756 my $uuid = $props->{'svm:uuid'};
1757 return undef if (!$src || !$uuid);
1759 chomp($src, $uuid);
1761 $uuid =~ m{^[0-9a-f\-]{30,}$}
1762 or die "doesn't look right - svm:uuid is '$uuid'\n";
1764 # the '!' is used to mark the repos_root!/relative/path
1765 $src =~ s{/?!/?}{/};
1766 $src =~ s{/+$}{}; # no trailing slashes please
1767 # username is of no interest
1768 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1770 my $replace = $ra->{url};
1771 $replace .= "/$path" if length $path;
1773 my $section = "svn-remote.$self->{repo_id}";
1774 tmp_config("$section.svm-source", $src);
1775 tmp_config("$section.svm-replace", $replace);
1776 tmp_config("$section.svm-uuid", $uuid);
1777 $self->{svm} = {
1778 source => $src,
1779 uuid => $uuid,
1780 replace => $replace
1784 my $r = $ra->get_latest_revnum;
1785 my $path = $self->{path};
1786 my %tried;
1787 while (length $path) {
1788 unless ($tried{"$self->{url}/$path"}) {
1789 return $ra if $self->read_svm_props($ra, $path, $r);
1790 $tried{"$self->{url}/$path"} = 1;
1792 $path =~ s#/?[^/]+$##;
1794 die "Path: '$path' should be ''\n" if $path ne '';
1795 return $ra if $self->read_svm_props($ra, $path, $r);
1796 $tried{"$self->{url}/$path"} = 1;
1798 if ($ra->{repos_root} eq $self->{url}) {
1799 die @err, (map { " $_\n" } keys %tried), "\n";
1802 # nope, make sure we're connected to the repository root:
1803 my $ok;
1804 my @tried_b;
1805 $path = $ra->{svn_path};
1806 $ra = Git::SVN::Ra->new($ra->{repos_root});
1807 while (length $path) {
1808 unless ($tried{"$ra->{url}/$path"}) {
1809 $ok = $self->read_svm_props($ra, $path, $r);
1810 last if $ok;
1811 $tried{"$ra->{url}/$path"} = 1;
1813 $path =~ s#/?[^/]+$##;
1815 die "Path: '$path' should be ''\n" if $path ne '';
1816 $ok ||= $self->read_svm_props($ra, $path, $r);
1817 $tried{"$ra->{url}/$path"} = 1;
1818 if (!$ok) {
1819 die @err, (map { " $_\n" } keys %tried), "\n";
1821 Git::SVN::Ra->new($self->{url});
1824 sub svnsync {
1825 my ($self) = @_;
1826 return $self->{svnsync} if $self->{svnsync};
1828 if ($self->no_metadata) {
1829 die "Can't have both 'noMetadata' and ",
1830 "'useSvnsyncProps' options set!\n";
1832 if ($self->rewrite_root) {
1833 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1834 "options set!\n";
1837 my $svnsync;
1838 # see if we have it in our config, first:
1839 eval {
1840 my $section = "svn-remote.$self->{repo_id}";
1842 my $url = tmp_config('--get', "$section.svnsync-url");
1843 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1844 die "doesn't look right - svn:sync-from-url is '$url'\n";
1846 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1847 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1848 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1850 $svnsync = { url => $url, uuid => $uuid }
1852 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1853 return $self->{svnsync} = $svnsync;
1856 my $err = "useSvnsyncProps set, but failed to read " .
1857 "svnsync property: svn:sync-from-";
1858 my $rp = $self->ra->rev_proplist(0);
1860 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1861 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1862 die "doesn't look right - svn:sync-from-url is '$url'\n";
1864 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1865 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1866 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1868 my $section = "svn-remote.$self->{repo_id}";
1869 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1870 tmp_config('--add', "$section.svnsync-url", $url);
1871 return $self->{svnsync} = { url => $url, uuid => $uuid };
1874 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1875 # remote lookup (useful for 'git svn log').
1876 sub ra_uuid {
1877 my ($self) = @_;
1878 unless ($self->{ra_uuid}) {
1879 my $key = "svn-remote.$self->{repo_id}.uuid";
1880 my $uuid = eval { tmp_config('--get', $key) };
1881 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1882 $self->{ra_uuid} = $uuid;
1883 } else {
1884 die "ra_uuid called without URL\n" unless $self->{url};
1885 $self->{ra_uuid} = $self->ra->get_uuid;
1886 tmp_config('--add', $key, $self->{ra_uuid});
1889 $self->{ra_uuid};
1892 sub _set_repos_root {
1893 my ($self, $repos_root) = @_;
1894 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1895 $repos_root ||= $self->ra->{repos_root};
1896 tmp_config($k, $repos_root);
1897 $repos_root;
1900 sub repos_root {
1901 my ($self) = @_;
1902 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1903 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1906 sub ra {
1907 my ($self) = shift;
1908 my $ra = Git::SVN::Ra->new($self->{url});
1909 $self->_set_repos_root($ra->{repos_root});
1910 if ($self->use_svm_props && !$self->{svm}) {
1911 if ($self->no_metadata) {
1912 die "Can't have both 'noMetadata' and ",
1913 "'useSvmProps' options set!\n";
1914 } elsif ($self->use_svnsync_props) {
1915 die "Can't have both 'useSvnsyncProps' and ",
1916 "'useSvmProps' options set!\n";
1918 $ra = $self->_set_svm_vars($ra);
1919 $self->{-want_revprops} = 1;
1921 $ra;
1924 sub rel_path {
1925 my ($self) = @_;
1926 my $repos_root = $self->ra->{repos_root};
1927 return $self->{path} if ($self->{url} eq $repos_root);
1928 my $url = $self->{url} .
1929 (length $self->{path} ? "/$self->{path}" : $self->{path});
1930 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1931 $url;
1934 # prop_walk(PATH, REV, SUB)
1935 # -------------------------
1936 # Recursively traverse PATH at revision REV and invoke SUB for each
1937 # directory that contains a SVN property. SUB will be invoked as
1938 # follows: &SUB(gs, path, props); where `gs' is this instance of
1939 # Git::SVN, `path' the path to the directory where the properties
1940 # `props' were found. The `path' will be relative to point of checkout,
1941 # that is, if url://repo/trunk is the current Git branch, and that
1942 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1943 # as `path' (note the trailing `/').
1944 sub prop_walk {
1945 my ($self, $path, $rev, $sub) = @_;
1947 $path =~ s#^/##;
1948 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1949 $path =~ s#^/*#/#g;
1950 my $p = $path;
1951 # Strip the irrelevant part of the path.
1952 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1953 # Ensure the path is terminated by a `/'.
1954 $p =~ s#/*$#/#;
1956 # The properties contain all the internal SVN stuff nobody
1957 # (usually) cares about.
1958 my $interesting_props = 0;
1959 foreach (keys %{$props}) {
1960 # If it doesn't start with `svn:', it must be a
1961 # user-defined property.
1962 ++$interesting_props and next if $_ !~ /^svn:/;
1963 # FIXME: Fragile, if SVN adds new public properties,
1964 # this needs to be updated.
1965 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1966 |eol-style|mime-type
1967 |externals|needs-lock)$/x;
1969 &$sub($self, $p, $props) if $interesting_props;
1971 foreach (sort keys %$dirent) {
1972 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1973 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1977 sub last_rev { ($_[0]->last_rev_commit)[0] }
1978 sub last_commit { ($_[0]->last_rev_commit)[1] }
1980 # returns the newest SVN revision number and newest commit SHA1
1981 sub last_rev_commit {
1982 my ($self) = @_;
1983 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1984 return ($self->{last_rev}, $self->{last_commit});
1986 my $c = ::verify_ref($self->refname.'^0');
1987 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1988 my $rev = (::cmt_metadata($c))[1];
1989 if (defined $rev) {
1990 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1991 return ($rev, $c);
1994 my $map_path = $self->map_path;
1995 unless (-e $map_path) {
1996 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1997 return (undef, undef);
1999 my ($rev, $commit) = $self->rev_map_max(1);
2000 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2001 return ($rev, $commit);
2004 sub get_fetch_range {
2005 my ($self, $min, $max) = @_;
2006 $max ||= $self->ra->get_latest_revnum;
2007 $min ||= $self->rev_map_max;
2008 (++$min, $max);
2011 sub tmp_config {
2012 my (@args) = @_;
2013 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2014 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2015 if (! -f $config && -f $old_def_config) {
2016 rename $old_def_config, $config or
2017 die "Failed rename $old_def_config => $config: $!\n";
2019 my $old_config = $ENV{GIT_CONFIG};
2020 $ENV{GIT_CONFIG} = $config;
2021 $@ = undef;
2022 my @ret = eval {
2023 unless (-f $config) {
2024 mkfile($config);
2025 open my $fh, '>', $config or
2026 die "Can't open $config: $!\n";
2027 print $fh "; This file is used internally by ",
2028 "git-svn\n" or die
2029 "Couldn't write to $config: $!\n";
2030 print $fh "; You should not have to edit it\n" or
2031 die "Couldn't write to $config: $!\n";
2032 close $fh or die "Couldn't close $config: $!\n";
2034 command('config', @args);
2036 my $err = $@;
2037 if (defined $old_config) {
2038 $ENV{GIT_CONFIG} = $old_config;
2039 } else {
2040 delete $ENV{GIT_CONFIG};
2042 die $err if $err;
2043 wantarray ? @ret : $ret[0];
2046 sub tmp_index_do {
2047 my ($self, $sub) = @_;
2048 my $old_index = $ENV{GIT_INDEX_FILE};
2049 $ENV{GIT_INDEX_FILE} = $self->{index};
2050 $@ = undef;
2051 my @ret = eval {
2052 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2053 mkpath([$dir]) unless -d $dir;
2054 &$sub;
2056 my $err = $@;
2057 if (defined $old_index) {
2058 $ENV{GIT_INDEX_FILE} = $old_index;
2059 } else {
2060 delete $ENV{GIT_INDEX_FILE};
2062 die $err if $err;
2063 wantarray ? @ret : $ret[0];
2066 sub assert_index_clean {
2067 my ($self, $treeish) = @_;
2069 $self->tmp_index_do(sub {
2070 command_noisy('read-tree', $treeish) unless -e $self->{index};
2071 my $x = command_oneline('write-tree');
2072 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2073 /^tree ($::sha1)/mo);
2074 return if $y eq $x;
2076 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2077 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2078 command_noisy('read-tree', $treeish);
2079 $x = command_oneline('write-tree');
2080 if ($y ne $x) {
2081 ::fatal "trees ($treeish) $y != $x\n",
2082 "Something is seriously wrong...";
2087 sub get_commit_parents {
2088 my ($self, $log_entry) = @_;
2089 my (%seen, @ret, @tmp);
2090 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2091 if (my $ip = $self->{inject_parents}) {
2092 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2093 push @tmp, $commit;
2096 if (my $cur = ::verify_ref($self->refname.'^0')) {
2097 push @tmp, $cur;
2099 if (my $ipd = $self->{inject_parents_dcommit}) {
2100 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2101 push @tmp, @$commit;
2104 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2105 while (my $p = shift @tmp) {
2106 next if $seen{$p};
2107 $seen{$p} = 1;
2108 push @ret, $p;
2109 # MAXPARENT is defined to 16 in commit-tree.c:
2110 last if @ret >= 16;
2112 if (@tmp) {
2113 die "r$log_entry->{revision}: No room for parents:\n\t",
2114 join("\n\t", @tmp), "\n";
2116 @ret;
2119 sub rewrite_root {
2120 my ($self) = @_;
2121 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2122 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2123 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2124 if ($rwr) {
2125 $rwr =~ s#/+$##;
2126 if ($rwr !~ m#^[a-z\+]+://#) {
2127 die "$rwr is not a valid URL (key: $k)\n";
2130 $self->{-rewrite_root} = $rwr;
2133 sub metadata_url {
2134 my ($self) = @_;
2135 ($self->rewrite_root || $self->{url}) .
2136 (length $self->{path} ? '/' . $self->{path} : '');
2139 sub full_url {
2140 my ($self) = @_;
2141 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2145 sub set_commit_header_env {
2146 my ($log_entry) = @_;
2147 my %env;
2148 foreach my $ned (qw/NAME EMAIL DATE/) {
2149 foreach my $ac (qw/AUTHOR COMMITTER/) {
2150 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2154 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2155 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2156 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2158 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2159 ? $log_entry->{commit_name}
2160 : $log_entry->{name};
2161 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2162 ? $log_entry->{commit_email}
2163 : $log_entry->{email};
2164 \%env;
2167 sub restore_commit_header_env {
2168 my ($env) = @_;
2169 foreach my $ned (qw/NAME EMAIL DATE/) {
2170 foreach my $ac (qw/AUTHOR COMMITTER/) {
2171 my $k = "GIT_${ac}_${ned}";
2172 if (defined $env->{$k}) {
2173 $ENV{$k} = $env->{$k};
2174 } else {
2175 delete $ENV{$k};
2181 sub gc {
2182 command_noisy('gc', '--auto');
2185 sub do_git_commit {
2186 my ($self, $log_entry) = @_;
2187 my $lr = $self->last_rev;
2188 if (defined $lr && $lr >= $log_entry->{revision}) {
2189 die "Last fetched revision of ", $self->refname,
2190 " was r$lr, but we are about to fetch: ",
2191 "r$log_entry->{revision}!\n";
2193 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2194 croak "$log_entry->{revision} = $c already exists! ",
2195 "Why are we refetching it?\n";
2197 my $old_env = set_commit_header_env($log_entry);
2198 my $tree = $log_entry->{tree};
2199 if (!defined $tree) {
2200 $tree = $self->tmp_index_do(sub {
2201 command_oneline('write-tree') });
2203 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2205 my @exec = ('git-commit-tree', $tree);
2206 foreach ($self->get_commit_parents($log_entry)) {
2207 push @exec, '-p', $_;
2209 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2210 or croak $!;
2211 print $msg_fh $log_entry->{log} or croak $!;
2212 restore_commit_header_env($old_env);
2213 unless ($self->no_metadata) {
2214 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2215 or croak $!;
2217 $msg_fh->flush == 0 or croak $!;
2218 close $msg_fh or croak $!;
2219 chomp(my $commit = do { local $/; <$out_fh> });
2220 close $out_fh or croak $!;
2221 waitpid $pid, 0;
2222 croak $? if $?;
2223 if ($commit !~ /^$::sha1$/o) {
2224 die "Failed to commit, invalid sha1: $commit\n";
2227 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2229 $self->{last_rev} = $log_entry->{revision};
2230 $self->{last_commit} = $commit;
2231 print "r$log_entry->{revision}";
2232 if (defined $log_entry->{svm_revision}) {
2233 print " (\@$log_entry->{svm_revision})";
2234 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2235 0, $self->svm_uuid);
2237 print " = $commit ($self->{ref_id})\n";
2238 if (--$_gc_nr == 0) {
2239 $_gc_nr = $_gc_period;
2240 gc();
2242 return $commit;
2245 sub match_paths {
2246 my ($self, $paths, $r) = @_;
2247 return 1 if $self->{path} eq '';
2248 if (my $path = $paths->{"/$self->{path}"}) {
2249 return ($path->{action} eq 'D') ? 0 : 1;
2251 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2252 if (grep /$self->{path_regex}/, keys %$paths) {
2253 return 1;
2255 my $c = '';
2256 foreach (split m#/#, $self->{path}) {
2257 $c .= "/$_";
2258 next unless ($paths->{$c} &&
2259 ($paths->{$c}->{action} =~ /^[AR]$/));
2260 if ($self->ra->check_path($self->{path}, $r) ==
2261 $SVN::Node::dir) {
2262 return 1;
2265 return 0;
2268 sub find_parent_branch {
2269 my ($self, $paths, $rev) = @_;
2270 return undef unless $self->follow_parent;
2271 unless (defined $paths) {
2272 my $err_handler = $SVN::Error::handler;
2273 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2274 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2275 $paths =
2276 Git::SVN::Ra::dup_changed_paths($_[0]) });
2277 $SVN::Error::handler = $err_handler;
2279 return undef unless defined $paths;
2281 # look for a parent from another branch:
2282 my @b_path_components = split m#/#, $self->rel_path;
2283 my @a_path_components;
2284 my $i;
2285 while (@b_path_components) {
2286 $i = $paths->{'/'.join('/', @b_path_components)};
2287 last if $i && defined $i->{copyfrom_path};
2288 unshift(@a_path_components, pop(@b_path_components));
2290 return undef unless defined $i && defined $i->{copyfrom_path};
2291 my $branch_from = $i->{copyfrom_path};
2292 if (@a_path_components) {
2293 print STDERR "branch_from: $branch_from => ";
2294 $branch_from .= '/'.join('/', @a_path_components);
2295 print STDERR $branch_from, "\n";
2297 my $r = $i->{copyfrom_rev};
2298 my $repos_root = $self->ra->{repos_root};
2299 my $url = $self->ra->{url};
2300 my $new_url = $repos_root . $branch_from;
2301 print STDERR "Found possible branch point: ",
2302 "$new_url => ", $self->full_url, ", $r\n";
2303 $branch_from =~ s#^/##;
2304 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2305 unless ($gs) {
2306 my $ref_id = $self->{ref_id};
2307 $ref_id =~ s/\@\d+$//;
2308 $ref_id .= "\@$r";
2309 # just grow a tail if we're not unique enough :x
2310 $ref_id .= '-' while find_ref($ref_id);
2311 print STDERR "Initializing parent: $ref_id\n";
2312 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2313 if ($u =~ s#^\Q$url\E(/|$)##) {
2314 $p = $u;
2315 $u = $url;
2316 $repo_id = $self->{repo_id};
2318 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2320 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2321 if (!defined $r0 || !defined $parent) {
2322 my ($base, $head) = parse_revision_argument(0, $r);
2323 if ($base <= $r) {
2324 $gs->fetch($base, $r);
2326 ($r0, $parent) = $gs->last_rev_commit;
2328 if (defined $r0 && defined $parent) {
2329 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2330 my $ed;
2331 if ($self->ra->can_do_switch) {
2332 $self->assert_index_clean($parent);
2333 print STDERR "Following parent with do_switch\n";
2334 # do_switch works with svn/trunk >= r22312, but that
2335 # is not included with SVN 1.4.3 (the latest version
2336 # at the moment), so we can't rely on it
2337 $self->{last_commit} = $parent;
2338 $ed = SVN::Git::Fetcher->new($self);
2339 $gs->ra->gs_do_switch($r0, $rev, $gs,
2340 $self->full_url, $ed)
2341 or die "SVN connection failed somewhere...\n";
2342 } elsif ($self->ra->trees_match($new_url, $r0,
2343 $self->full_url, $rev)) {
2344 print STDERR "Trees match:\n",
2345 " $new_url\@$r0\n",
2346 " ${\$self->full_url}\@$rev\n",
2347 "Following parent with no changes\n";
2348 $self->tmp_index_do(sub {
2349 command_noisy('read-tree', $parent);
2351 $self->{last_commit} = $parent;
2352 } else {
2353 print STDERR "Following parent with do_update\n";
2354 $ed = SVN::Git::Fetcher->new($self);
2355 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2356 or die "SVN connection failed somewhere...\n";
2358 print STDERR "Successfully followed parent\n";
2359 return $self->make_log_entry($rev, [$parent], $ed);
2361 return undef;
2364 sub do_fetch {
2365 my ($self, $paths, $rev) = @_;
2366 my $ed;
2367 my ($last_rev, @parents);
2368 if (my $lc = $self->last_commit) {
2369 # we can have a branch that was deleted, then re-added
2370 # under the same name but copied from another path, in
2371 # which case we'll have multiple parents (we don't
2372 # want to break the original ref, nor lose copypath info):
2373 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2374 push @{$log_entry->{parents}}, $lc;
2375 return $log_entry;
2377 $ed = SVN::Git::Fetcher->new($self);
2378 $last_rev = $self->{last_rev};
2379 $ed->{c} = $lc;
2380 @parents = ($lc);
2381 } else {
2382 $last_rev = $rev;
2383 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2384 return $log_entry;
2386 $ed = SVN::Git::Fetcher->new($self);
2388 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2389 die "SVN connection failed somewhere...\n";
2391 $self->make_log_entry($rev, \@parents, $ed);
2394 sub get_untracked {
2395 my ($self, $ed) = @_;
2396 my @out;
2397 my $h = $ed->{empty};
2398 foreach (sort keys %$h) {
2399 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2400 push @out, " $act: " . uri_encode($_);
2401 warn "W: $act: $_\n";
2403 foreach my $t (qw/dir_prop file_prop/) {
2404 $h = $ed->{$t} or next;
2405 foreach my $path (sort keys %$h) {
2406 my $ppath = $path eq '' ? '.' : $path;
2407 foreach my $prop (sort keys %{$h->{$path}}) {
2408 next if $SKIP_PROP{$prop};
2409 my $v = $h->{$path}->{$prop};
2410 my $t_ppath_prop = "$t: " .
2411 uri_encode($ppath) . ' ' .
2412 uri_encode($prop);
2413 if (defined $v) {
2414 push @out, " +$t_ppath_prop " .
2415 uri_encode($v);
2416 } else {
2417 push @out, " -$t_ppath_prop";
2422 foreach my $t (qw/absent_file absent_directory/) {
2423 $h = $ed->{$t} or next;
2424 foreach my $parent (sort keys %$h) {
2425 foreach my $path (sort @{$h->{$parent}}) {
2426 push @out, " $t: " .
2427 uri_encode("$parent/$path");
2428 warn "W: $t: $parent/$path ",
2429 "Insufficient permissions?\n";
2433 \@out;
2436 sub parse_svn_date {
2437 my $date = shift || return '+0000 1970-01-01 00:00:00';
2438 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2439 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2440 croak "Unable to parse date: $date\n";
2441 "+0000 $Y-$m-$d $H:$M:$S";
2444 sub check_author {
2445 my ($author) = @_;
2446 if (!defined $author || length $author == 0) {
2447 $author = '(no author)';
2448 } elsif (defined $::_authors && ! defined $::users{$author}) {
2449 die "Author: $author not defined in $::_authors file\n";
2451 $author;
2454 sub make_log_entry {
2455 my ($self, $rev, $parents, $ed) = @_;
2456 my $untracked = $self->get_untracked($ed);
2458 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2459 print $un "r$rev\n" or croak $!;
2460 print $un $_, "\n" foreach @$untracked;
2461 my %log_entry = ( parents => $parents || [], revision => $rev,
2462 log => '');
2464 my $headrev;
2465 my $logged = delete $self->{logged_rev_props};
2466 if (!$logged || $self->{-want_revprops}) {
2467 my $rp = $self->ra->rev_proplist($rev);
2468 foreach (sort keys %$rp) {
2469 my $v = $rp->{$_};
2470 if (/^svn:(author|date|log)$/) {
2471 $log_entry{$1} = $v;
2472 } elsif ($_ eq 'svm:headrev') {
2473 $headrev = $v;
2474 } else {
2475 print $un " rev_prop: ", uri_encode($_), ' ',
2476 uri_encode($v), "\n";
2479 } else {
2480 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2482 close $un or croak $!;
2484 $log_entry{date} = parse_svn_date($log_entry{date});
2485 $log_entry{log} .= "\n";
2486 my $author = $log_entry{author} = check_author($log_entry{author});
2487 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2488 : ($author, undef);
2490 my ($commit_name, $commit_email) = ($name, $email);
2491 if ($_use_log_author) {
2492 my $name_field;
2493 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2494 $name_field = $1;
2495 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2496 $name_field = $1;
2498 if (!defined $name_field) {
2499 if (!defined $email) {
2500 $email = $name;
2502 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2503 ($name, $email) = ($1, $2);
2504 } elsif ($name_field =~ /(.*)@/) {
2505 ($name, $email) = ($1, $name_field);
2506 } else {
2507 ($name, $email) = ($name_field, $name_field);
2510 if (defined $headrev && $self->use_svm_props) {
2511 if ($self->rewrite_root) {
2512 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2513 "options set!\n";
2515 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2516 # we don't want "SVM: initializing mirror for junk" ...
2517 return undef if $r == 0;
2518 my $svm = $self->svm;
2519 if ($uuid ne $svm->{uuid}) {
2520 die "UUID mismatch on SVM path:\n",
2521 "expected: $svm->{uuid}\n",
2522 " got: $uuid\n";
2524 my $full_url = $self->full_url;
2525 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2526 die "Failed to replace '$svm->{replace}' with ",
2527 "'$svm->{source}' in $full_url\n";
2528 # throw away username for storing in records
2529 remove_username($full_url);
2530 $log_entry{metadata} = "$full_url\@$r $uuid";
2531 $log_entry{svm_revision} = $r;
2532 $email ||= "$author\@$uuid";
2533 $commit_email ||= "$author\@$uuid";
2534 } elsif ($self->use_svnsync_props) {
2535 my $full_url = $self->svnsync->{url};
2536 $full_url .= "/$self->{path}" if length $self->{path};
2537 remove_username($full_url);
2538 my $uuid = $self->svnsync->{uuid};
2539 $log_entry{metadata} = "$full_url\@$rev $uuid";
2540 $email ||= "$author\@$uuid";
2541 $commit_email ||= "$author\@$uuid";
2542 } else {
2543 my $url = $self->metadata_url;
2544 remove_username($url);
2545 $log_entry{metadata} = "$url\@$rev " .
2546 $self->ra->get_uuid;
2547 $email ||= "$author\@" . $self->ra->get_uuid;
2548 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2550 $log_entry{name} = $name;
2551 $log_entry{email} = $email;
2552 $log_entry{commit_name} = $commit_name;
2553 $log_entry{commit_email} = $commit_email;
2554 \%log_entry;
2557 sub fetch {
2558 my ($self, $min_rev, $max_rev, @parents) = @_;
2559 my ($last_rev, $last_commit) = $self->last_rev_commit;
2560 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2561 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2564 sub set_tree_cb {
2565 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2566 $self->{inject_parents} = { $rev => $tree };
2567 $self->fetch(undef, undef);
2570 sub set_tree {
2571 my ($self, $tree) = (shift, shift);
2572 my $log_entry = ::get_commit_entry($tree);
2573 unless ($self->{last_rev}) {
2574 fatal("Must have an existing revision to commit");
2576 my %ed_opts = ( r => $self->{last_rev},
2577 log => $log_entry->{log},
2578 ra => $self->ra,
2579 tree_a => $self->{last_commit},
2580 tree_b => $tree,
2581 editor_cb => sub {
2582 $self->set_tree_cb($log_entry, $tree, @_) },
2583 svn_path => $self->{path} );
2584 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2585 print "No changes\nr$self->{last_rev} = $tree\n";
2589 sub rebuild_from_rev_db {
2590 my ($self, $path) = @_;
2591 my $r = -1;
2592 open my $fh, '<', $path or croak "open: $!";
2593 binmode $fh or croak "binmode: $!";
2594 while (<$fh>) {
2595 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2596 chomp($_);
2597 ++$r;
2598 next if $_ eq ('0' x 40);
2599 $self->rev_map_set($r, $_);
2600 print "r$r = $_\n";
2602 close $fh or croak "close: $!";
2603 unlink $path or croak "unlink: $!";
2606 sub rebuild {
2607 my ($self) = @_;
2608 my $map_path = $self->map_path;
2609 return if (-e $map_path && ! -z $map_path);
2610 return unless ::verify_ref($self->refname.'^0');
2611 if ($self->use_svm_props || $self->no_metadata) {
2612 my $rev_db = $self->rev_db_path;
2613 $self->rebuild_from_rev_db($rev_db);
2614 if ($self->use_svm_props) {
2615 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2616 $self->rebuild_from_rev_db($svm_rev_db);
2618 $self->unlink_rev_db_symlink;
2619 return;
2621 print "Rebuilding $map_path ...\n";
2622 my ($log, $ctx) =
2623 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2624 $self->refname, '--');
2625 my $metadata_url = $self->metadata_url;
2626 remove_username($metadata_url);
2627 my $svn_uuid = $self->ra_uuid;
2628 my $c;
2629 while (<$log>) {
2630 if ( m{^commit ($::sha1)$} ) {
2631 $c = $1;
2632 next;
2634 next unless s{^\s*(git-svn-id:)}{$1};
2635 my ($url, $rev, $uuid) = ::extract_metadata($_);
2636 remove_username($url);
2638 # ignore merges (from set-tree)
2639 next if (!defined $rev || !$uuid);
2641 # if we merged or otherwise started elsewhere, this is
2642 # how we break out of it
2643 if (($uuid ne $svn_uuid) ||
2644 ($metadata_url && $url && ($url ne $metadata_url))) {
2645 next;
2648 $self->rev_map_set($rev, $c);
2649 print "r$rev = $c\n";
2651 command_close_pipe($log, $ctx);
2652 print "Done rebuilding $map_path\n";
2653 my $rev_db_path = $self->rev_db_path;
2654 if (-f $self->rev_db_path) {
2655 unlink $self->rev_db_path or croak "unlink: $!";
2657 $self->unlink_rev_db_symlink;
2660 # rev_map:
2661 # Tie::File seems to be prone to offset errors if revisions get sparse,
2662 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2663 # one of my favorite modules is out :< Next up would be one of the DBM
2664 # modules, but I'm not sure which is most portable...
2666 # This is the replacement for the rev_db format, which was too big
2667 # and inefficient for large repositories with a lot of sparse history
2668 # (mainly tags)
2670 # The format is this:
2671 # - 24 bytes for every record,
2672 # * 4 bytes for the integer representing an SVN revision number
2673 # * 20 bytes representing the sha1 of a git commit
2674 # - No empty padding records like the old format
2675 # (except the last record, which can be overwritten)
2676 # - new records are written append-only since SVN revision numbers
2677 # increase monotonically
2678 # - lookups on SVN revision number are done via a binary search
2679 # - Piping the file to xxd -c24 is a good way of dumping it for
2680 # viewing or editing (piped back through xxd -r), should the need
2681 # ever arise.
2682 # - The last record can be padding revision with an all-zero sha1
2683 # This is used to optimize fetch performance when using multiple
2684 # "fetch" directives in .git/config
2686 # These files are disposable unless noMetadata or useSvmProps is set
2688 sub _rev_map_set {
2689 my ($fh, $rev, $commit) = @_;
2691 binmode $fh or croak "binmode: $!";
2692 my $size = (stat($fh))[7];
2693 ($size % 24) == 0 or croak "inconsistent size: $size";
2695 my $wr_offset = 0;
2696 if ($size > 0) {
2697 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2698 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2699 $read == 24 or croak "read only $read bytes (!= 24)";
2700 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2701 if ($last_commit eq ('0' x40)) {
2702 if ($size >= 48) {
2703 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2704 $read = sysread($fh, $buf, 24) or
2705 croak "read: $!";
2706 $read == 24 or
2707 croak "read only $read bytes (!= 24)";
2708 ($last_rev, $last_commit) =
2709 unpack(rev_map_fmt, $buf);
2710 if ($last_commit eq ('0' x40)) {
2711 croak "inconsistent .rev_map\n";
2714 if ($last_rev >= $rev) {
2715 croak "last_rev is higher!: $last_rev >= $rev";
2717 $wr_offset = -24;
2720 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2721 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2722 croak "write: $!";
2725 sub mkfile {
2726 my ($path) = @_;
2727 unless (-e $path) {
2728 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2729 mkpath([$dir]) unless -d $dir;
2730 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2731 close $fh or die "Couldn't close (create) $path: $!\n";
2735 sub rev_map_set {
2736 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2737 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2738 my $db = $self->map_path($uuid);
2739 my $db_lock = "$db.lock";
2740 my $sig;
2741 if ($update_ref) {
2742 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2743 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2745 mkfile($db);
2747 $LOCKFILES{$db_lock} = 1;
2748 my $sync;
2749 # both of these options make our .rev_db file very, very important
2750 # and we can't afford to lose it because rebuild() won't work
2751 if ($self->use_svm_props || $self->no_metadata) {
2752 $sync = 1;
2753 copy($db, $db_lock) or die "rev_map_set(@_): ",
2754 "Failed to copy: ",
2755 "$db => $db_lock ($!)\n";
2756 } else {
2757 rename $db, $db_lock or die "rev_map_set(@_): ",
2758 "Failed to rename: ",
2759 "$db => $db_lock ($!)\n";
2762 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2763 or croak "Couldn't open $db_lock: $!\n";
2764 _rev_map_set($fh, $rev, $commit);
2765 if ($sync) {
2766 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2767 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2769 close $fh or croak $!;
2770 if ($update_ref) {
2771 $_head = $self;
2772 command_noisy('update-ref', '-m', "r$rev",
2773 $self->refname, $commit);
2775 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2776 "$db_lock => $db ($!)\n";
2777 delete $LOCKFILES{$db_lock};
2778 if ($update_ref) {
2779 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2780 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2781 kill $sig, $$ if defined $sig;
2785 # If want_commit, this will return an array of (rev, commit) where
2786 # commit _must_ be a valid commit in the archive.
2787 # Otherwise, it'll return the max revision (whether or not the
2788 # commit is valid or just a 0x40 placeholder).
2789 sub rev_map_max {
2790 my ($self, $want_commit) = @_;
2791 $self->rebuild;
2792 my $map_path = $self->map_path;
2793 stat $map_path or return $want_commit ? (0, undef) : 0;
2794 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2795 binmode $fh or croak "binmode: $!";
2796 my $size = (stat($fh))[7];
2797 ($size % 24) == 0 or croak "inconsistent size: $size";
2799 if ($size == 0) {
2800 close $fh or croak "close: $!";
2801 return $want_commit ? (0, undef) : 0;
2804 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2805 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2806 my ($r, $c) = unpack(rev_map_fmt, $buf);
2807 if ($want_commit && $c eq ('0' x40)) {
2808 if ($size < 48) {
2809 return $want_commit ? (0, undef) : 0;
2811 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2812 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2813 ($r, $c) = unpack(rev_map_fmt, $buf);
2814 if ($c eq ('0'x40)) {
2815 croak "Penultimate record is all-zeroes in $map_path";
2818 close $fh or croak "close: $!";
2819 $want_commit ? ($r, $c) : $r;
2822 sub rev_map_get {
2823 my ($self, $rev, $uuid) = @_;
2824 my $map_path = $self->map_path($uuid);
2825 return undef unless -e $map_path;
2827 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2828 binmode $fh or croak "binmode: $!";
2829 my $size = (stat($fh))[7];
2830 ($size % 24) == 0 or croak "inconsistent size: $size";
2832 if ($size == 0) {
2833 close $fh or croak "close: $fh";
2834 return undef;
2837 my ($l, $u) = (0, $size - 24);
2838 my ($r, $c, $buf);
2840 while ($l <= $u) {
2841 my $i = int(($l/24 + $u/24) / 2) * 24;
2842 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2843 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2844 my ($r, $c) = unpack('NH40', $buf);
2846 if ($r < $rev) {
2847 $l = $i + 24;
2848 } elsif ($r > $rev) {
2849 $u = $i - 24;
2850 } else { # $r == $rev
2851 close($fh) or croak "close: $!";
2852 return $c eq ('0' x 40) ? undef : $c;
2855 close($fh) or croak "close: $!";
2856 undef;
2859 # Finds the first svn revision that exists on (if $eq_ok is true) or
2860 # before $rev for the current branch. It will not search any lower
2861 # than $min_rev. Returns the git commit hash and svn revision number
2862 # if found, else (undef, undef).
2863 sub find_rev_before {
2864 my ($self, $rev, $eq_ok, $min_rev) = @_;
2865 --$rev unless $eq_ok;
2866 $min_rev ||= 1;
2867 while ($rev >= $min_rev) {
2868 if (my $c = $self->rev_map_get($rev)) {
2869 return ($rev, $c);
2871 --$rev;
2873 return (undef, undef);
2876 # Finds the first svn revision that exists on (if $eq_ok is true) or
2877 # after $rev for the current branch. It will not search any higher
2878 # than $max_rev. Returns the git commit hash and svn revision number
2879 # if found, else (undef, undef).
2880 sub find_rev_after {
2881 my ($self, $rev, $eq_ok, $max_rev) = @_;
2882 ++$rev unless $eq_ok;
2883 $max_rev ||= $self->rev_map_max;
2884 while ($rev <= $max_rev) {
2885 if (my $c = $self->rev_map_get($rev)) {
2886 return ($rev, $c);
2888 ++$rev;
2890 return (undef, undef);
2893 sub _new {
2894 my ($class, $repo_id, $ref_id, $path) = @_;
2895 unless (defined $repo_id && length $repo_id) {
2896 $repo_id = $Git::SVN::default_repo_id;
2898 unless (defined $ref_id && length $ref_id) {
2899 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2901 $_[1] = $repo_id;
2902 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2903 $_[3] = $path = '' unless (defined $path);
2904 mkpath(["$ENV{GIT_DIR}/svn"]);
2905 bless {
2906 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2907 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2908 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2911 # for read-only access of old .rev_db formats
2912 sub unlink_rev_db_symlink {
2913 my ($self) = @_;
2914 my $link = $self->rev_db_path;
2915 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2916 if (-l $link) {
2917 unlink $link or croak "unlink: $link failed!";
2921 sub rev_db_path {
2922 my ($self, $uuid) = @_;
2923 my $db_path = $self->map_path($uuid);
2924 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2925 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2926 $db_path;
2929 # the new replacement for .rev_db
2930 sub map_path {
2931 my ($self, $uuid) = @_;
2932 $uuid ||= $self->ra_uuid;
2933 "$self->{map_root}.$uuid";
2936 sub uri_encode {
2937 my ($f) = @_;
2938 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2942 sub remove_username {
2943 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2946 package Git::SVN::Prompt;
2947 use strict;
2948 use warnings;
2949 require SVN::Core;
2950 use vars qw/$_no_auth_cache $_username/;
2952 sub simple {
2953 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2954 $may_save = undef if $_no_auth_cache;
2955 $default_username = $_username if defined $_username;
2956 if (defined $default_username && length $default_username) {
2957 if (defined $realm && length $realm) {
2958 print STDERR "Authentication realm: $realm\n";
2959 STDERR->flush;
2961 $cred->username($default_username);
2962 } else {
2963 username($cred, $realm, $may_save, $pool);
2965 $cred->password(_read_password("Password for '" .
2966 $cred->username . "': ", $realm));
2967 $cred->may_save($may_save);
2968 $SVN::_Core::SVN_NO_ERROR;
2971 sub ssl_server_trust {
2972 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2973 $may_save = undef if $_no_auth_cache;
2974 print STDERR "Error validating server certificate for '$realm':\n";
2976 no warnings 'once';
2977 # All variables SVN::Auth::SSL::* are used only once,
2978 # so we're shutting up Perl warnings about this.
2979 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2980 print STDERR " - The certificate is not issued ",
2981 "by a trusted authority. Use the\n",
2982 " fingerprint to validate ",
2983 "the certificate manually!\n";
2985 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2986 print STDERR " - The certificate hostname ",
2987 "does not match.\n";
2989 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2990 print STDERR " - The certificate is not yet valid.\n";
2992 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2993 print STDERR " - The certificate has expired.\n";
2995 if ($failures & $SVN::Auth::SSL::OTHER) {
2996 print STDERR " - The certificate has ",
2997 "an unknown error.\n";
2999 } # no warnings 'once'
3000 printf STDERR
3001 "Certificate information:\n".
3002 " - Hostname: %s\n".
3003 " - Valid: from %s until %s\n".
3004 " - Issuer: %s\n".
3005 " - Fingerprint: %s\n",
3006 map $cert_info->$_, qw(hostname valid_from valid_until
3007 issuer_dname fingerprint);
3008 my $choice;
3009 prompt:
3010 print STDERR $may_save ?
3011 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3012 "(R)eject or accept (t)emporarily? ";
3013 STDERR->flush;
3014 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3015 if ($choice =~ /^t$/i) {
3016 $cred->may_save(undef);
3017 } elsif ($choice =~ /^r$/i) {
3018 return -1;
3019 } elsif ($may_save && $choice =~ /^p$/i) {
3020 $cred->may_save($may_save);
3021 } else {
3022 goto prompt;
3024 $cred->accepted_failures($failures);
3025 $SVN::_Core::SVN_NO_ERROR;
3028 sub ssl_client_cert {
3029 my ($cred, $realm, $may_save, $pool) = @_;
3030 $may_save = undef if $_no_auth_cache;
3031 print STDERR "Client certificate filename: ";
3032 STDERR->flush;
3033 chomp(my $filename = <STDIN>);
3034 $cred->cert_file($filename);
3035 $cred->may_save($may_save);
3036 $SVN::_Core::SVN_NO_ERROR;
3039 sub ssl_client_cert_pw {
3040 my ($cred, $realm, $may_save, $pool) = @_;
3041 $may_save = undef if $_no_auth_cache;
3042 $cred->password(_read_password("Password: ", $realm));
3043 $cred->may_save($may_save);
3044 $SVN::_Core::SVN_NO_ERROR;
3047 sub username {
3048 my ($cred, $realm, $may_save, $pool) = @_;
3049 $may_save = undef if $_no_auth_cache;
3050 if (defined $realm && length $realm) {
3051 print STDERR "Authentication realm: $realm\n";
3053 my $username;
3054 if (defined $_username) {
3055 $username = $_username;
3056 } else {
3057 print STDERR "Username: ";
3058 STDERR->flush;
3059 chomp($username = <STDIN>);
3061 $cred->username($username);
3062 $cred->may_save($may_save);
3063 $SVN::_Core::SVN_NO_ERROR;
3066 sub _read_password {
3067 my ($prompt, $realm) = @_;
3068 print STDERR $prompt;
3069 STDERR->flush;
3070 require Term::ReadKey;
3071 Term::ReadKey::ReadMode('noecho');
3072 my $password = '';
3073 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3074 last if $key =~ /[\012\015]/; # \n\r
3075 $password .= $key;
3077 Term::ReadKey::ReadMode('restore');
3078 print STDERR "\n";
3079 STDERR->flush;
3080 $password;
3083 package SVN::Git::Fetcher;
3084 use vars qw/@ISA/;
3085 use strict;
3086 use warnings;
3087 use Carp qw/croak/;
3088 use File::Temp qw/tempfile/;
3089 use IO::File qw//;
3091 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3092 sub new {
3093 my ($class, $git_svn) = @_;
3094 my $self = SVN::Delta::Editor->new;
3095 bless $self, $class;
3096 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3097 $self->{empty} = {};
3098 $self->{dir_prop} = {};
3099 $self->{file_prop} = {};
3100 $self->{absent_dir} = {};
3101 $self->{absent_file} = {};
3102 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3103 $self;
3106 sub set_path_strip {
3107 my ($self, $path) = @_;
3108 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3111 sub open_root {
3112 { path => '' };
3115 sub open_directory {
3116 my ($self, $path, $pb, $rev) = @_;
3117 { path => $path };
3120 sub git_path {
3121 my ($self, $path) = @_;
3122 if ($self->{path_strip}) {
3123 $path =~ s!$self->{path_strip}!! or
3124 die "Failed to strip path '$path' ($self->{path_strip})\n";
3126 $path;
3129 sub delete_entry {
3130 my ($self, $path, $rev, $pb) = @_;
3132 my $gpath = $self->git_path($path);
3133 return undef if ($gpath eq '');
3135 # remove entire directories.
3136 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3137 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3138 -r --name-only -z/,
3139 $self->{c}, '--', $gpath);
3140 local $/ = "\0";
3141 while (<$ls>) {
3142 chomp;
3143 $self->{gii}->remove($_);
3144 print "\tD\t$_\n" unless $::_q;
3146 print "\tD\t$gpath/\n" unless $::_q;
3147 command_close_pipe($ls, $ctx);
3148 $self->{empty}->{$path} = 0
3149 } else {
3150 $self->{gii}->remove($gpath);
3151 print "\tD\t$gpath\n" unless $::_q;
3153 undef;
3156 sub open_file {
3157 my ($self, $path, $pb, $rev) = @_;
3158 my $gpath = $self->git_path($path);
3159 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3160 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3161 unless (defined $mode && defined $blob) {
3162 die "$path was not found in commit $self->{c} (r$rev)\n";
3164 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3165 pool => SVN::Pool->new, action => 'M' };
3168 sub add_file {
3169 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3170 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3171 delete $self->{empty}->{$dir};
3172 { path => $path, mode_a => 100644, mode_b => 100644,
3173 pool => SVN::Pool->new, action => 'A' };
3176 sub add_directory {
3177 my ($self, $path, $cp_path, $cp_rev) = @_;
3178 my $gpath = $self->git_path($path);
3179 if ($gpath eq '') {
3180 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3181 -r --name-only -z/,
3182 $self->{c});
3183 local $/ = "\0";
3184 while (<$ls>) {
3185 chomp;
3186 $self->{gii}->remove($_);
3187 print "\tD\t$_\n" unless $::_q;
3189 command_close_pipe($ls, $ctx);
3190 $self->{empty}->{$path} = 0;
3192 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3193 delete $self->{empty}->{$dir};
3194 $self->{empty}->{$path} = 1;
3195 { path => $path };
3198 sub change_dir_prop {
3199 my ($self, $db, $prop, $value) = @_;
3200 $self->{dir_prop}->{$db->{path}} ||= {};
3201 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3202 undef;
3205 sub absent_directory {
3206 my ($self, $path, $pb) = @_;
3207 $self->{absent_dir}->{$pb->{path}} ||= [];
3208 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3209 undef;
3212 sub absent_file {
3213 my ($self, $path, $pb) = @_;
3214 $self->{absent_file}->{$pb->{path}} ||= [];
3215 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3216 undef;
3219 sub change_file_prop {
3220 my ($self, $fb, $prop, $value) = @_;
3221 if ($prop eq 'svn:executable') {
3222 if ($fb->{mode_b} != 120000) {
3223 $fb->{mode_b} = defined $value ? 100755 : 100644;
3225 } elsif ($prop eq 'svn:special') {
3226 $fb->{mode_b} = defined $value ? 120000 : 100644;
3227 } else {
3228 $self->{file_prop}->{$fb->{path}} ||= {};
3229 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3231 undef;
3234 sub apply_textdelta {
3235 my ($self, $fb, $exp) = @_;
3236 my $fh = Git::temp_acquire('svn_delta');
3237 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3238 # (but $base does not,) so dup() it for reading in close_file
3239 open my $dup, '<&', $fh or croak $!;
3240 my $base = Git::temp_acquire('git_blob');
3241 if ($fb->{blob}) {
3242 print $base 'link ' if ($fb->{mode_a} == 120000);
3243 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3244 die "Failed to read object $fb->{blob}" if ($size < 0);
3246 if (defined $exp) {
3247 seek $base, 0, 0 or croak $!;
3248 my $got = ::md5sum($base);
3249 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3250 "expected: $exp\n",
3251 " got: $got\n" if ($got ne $exp);
3254 seek $base, 0, 0 or croak $!;
3255 $fb->{fh} = $fh;
3256 $fb->{base} = $base;
3257 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3260 sub close_file {
3261 my ($self, $fb, $exp) = @_;
3262 my $hash;
3263 my $path = $self->git_path($fb->{path});
3264 if (my $fh = $fb->{fh}) {
3265 if (defined $exp) {
3266 seek($fh, 0, 0) or croak $!;
3267 my $got = ::md5sum($fh);
3268 if ($got ne $exp) {
3269 die "Checksum mismatch: $path\n",
3270 "expected: $exp\n got: $got\n";
3273 if ($fb->{mode_b} == 120000) {
3274 sysseek($fh, 0, 0) or croak $!;
3275 sysread($fh, my $buf, 5) == 5 or croak $!;
3277 unless ($buf eq 'link ') {
3278 warn "$path has mode 120000",
3279 " but is not a link\n";
3280 } else {
3281 my $tmp_fh = Git::temp_acquire('svn_hash');
3282 my $res;
3283 while ($res = sysread($fh, my $str, 1024)) {
3284 my $out = syswrite($tmp_fh, $str, $res);
3285 defined($out) && $out == $res
3286 or croak("write ",
3287 $tmp_fh->filename,
3288 ": $!\n");
3290 defined $res or croak $!;
3292 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3293 Git::temp_release($tmp_fh, 1);
3297 $hash = $::_repository->hash_and_insert_object(
3298 $fh->filename);
3299 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3301 Git::temp_release($fb->{base}, 1);
3302 Git::temp_release($fh, 1);
3303 } else {
3304 $hash = $fb->{blob} or die "no blob information\n";
3306 $fb->{pool}->clear;
3307 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3308 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3309 undef;
3312 sub abort_edit {
3313 my $self = shift;
3314 $self->{nr} = $self->{gii}->{nr};
3315 delete $self->{gii};
3316 $self->SUPER::abort_edit(@_);
3319 sub close_edit {
3320 my $self = shift;
3321 $self->{git_commit_ok} = 1;
3322 $self->{nr} = $self->{gii}->{nr};
3323 delete $self->{gii};
3324 $self->SUPER::close_edit(@_);
3327 package SVN::Git::Editor;
3328 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3329 use strict;
3330 use warnings;
3331 use Carp qw/croak/;
3332 use IO::File;
3334 sub new {
3335 my ($class, $opts) = @_;
3336 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3337 die "$_ required!\n" unless (defined $opts->{$_});
3340 my $pool = SVN::Pool->new;
3341 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3342 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3343 $opts->{r}, $mods);
3345 # $opts->{ra} functions should not be used after this:
3346 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3347 $opts->{editor_cb}, $pool);
3348 my $self = SVN::Delta::Editor->new(@ce, $pool);
3349 bless $self, $class;
3350 foreach (qw/svn_path r tree_a tree_b/) {
3351 $self->{$_} = $opts->{$_};
3353 $self->{url} = $opts->{ra}->{url};
3354 $self->{mods} = $mods;
3355 $self->{types} = $types;
3356 $self->{pool} = $pool;
3357 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3358 $self->{rm} = { };
3359 $self->{path_prefix} = length $self->{svn_path} ?
3360 "$self->{svn_path}/" : '';
3361 $self->{config} = $opts->{config};
3362 return $self;
3365 sub generate_diff {
3366 my ($tree_a, $tree_b) = @_;
3367 my @diff_tree = qw(diff-tree -z -r);
3368 if ($_cp_similarity) {
3369 push @diff_tree, "-C$_cp_similarity";
3370 } else {
3371 push @diff_tree, '-C';
3373 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3374 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3375 push @diff_tree, $tree_a, $tree_b;
3376 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3377 local $/ = "\0";
3378 my $state = 'meta';
3379 my @mods;
3380 while (<$diff_fh>) {
3381 chomp $_; # this gets rid of the trailing "\0"
3382 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3383 ($::sha1)\s($::sha1)\s
3384 ([MTCRAD])\d*$/xo) {
3385 push @mods, { mode_a => $1, mode_b => $2,
3386 sha1_a => $3, sha1_b => $4,
3387 chg => $5 };
3388 if ($5 =~ /^(?:C|R)$/) {
3389 $state = 'file_a';
3390 } else {
3391 $state = 'file_b';
3393 } elsif ($state eq 'file_a') {
3394 my $x = $mods[$#mods] or croak "Empty array\n";
3395 if ($x->{chg} !~ /^(?:C|R)$/) {
3396 croak "Error parsing $_, $x->{chg}\n";
3398 $x->{file_a} = $_;
3399 $state = 'file_b';
3400 } elsif ($state eq 'file_b') {
3401 my $x = $mods[$#mods] or croak "Empty array\n";
3402 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3403 croak "Error parsing $_, $x->{chg}\n";
3405 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3406 croak "Error parsing $_, $x->{chg}\n";
3408 $x->{file_b} = $_;
3409 $state = 'meta';
3410 } else {
3411 croak "Error parsing $_\n";
3414 command_close_pipe($diff_fh, $ctx);
3415 \@mods;
3418 sub check_diff_paths {
3419 my ($ra, $pfx, $rev, $mods) = @_;
3420 my %types;
3421 $pfx .= '/' if length $pfx;
3423 sub type_diff_paths {
3424 my ($ra, $types, $path, $rev) = @_;
3425 my @p = split m#/+#, $path;
3426 my $c = shift @p;
3427 unless (defined $types->{$c}) {
3428 $types->{$c} = $ra->check_path($c, $rev);
3430 while (@p) {
3431 $c .= '/' . shift @p;
3432 next if defined $types->{$c};
3433 $types->{$c} = $ra->check_path($c, $rev);
3437 foreach my $m (@$mods) {
3438 foreach my $f (qw/file_a file_b/) {
3439 next unless defined $m->{$f};
3440 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3441 if (length $pfx.$dir && ! defined $types{$dir}) {
3442 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3446 \%types;
3449 sub split_path {
3450 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3453 sub repo_path {
3454 my ($self, $path) = @_;
3455 $self->{path_prefix}.(defined $path ? $path : '');
3458 sub url_path {
3459 my ($self, $path) = @_;
3460 if ($self->{url} =~ m#^https?://#) {
3461 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3463 $self->{url} . '/' . $self->repo_path($path);
3466 sub rmdirs {
3467 my ($self) = @_;
3468 my $rm = $self->{rm};
3469 delete $rm->{''}; # we never delete the url we're tracking
3470 return unless %$rm;
3472 foreach (keys %$rm) {
3473 my @d = split m#/#, $_;
3474 my $c = shift @d;
3475 $rm->{$c} = 1;
3476 while (@d) {
3477 $c .= '/' . shift @d;
3478 $rm->{$c} = 1;
3481 delete $rm->{$self->{svn_path}};
3482 delete $rm->{''}; # we never delete the url we're tracking
3483 return unless %$rm;
3485 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3486 $self->{tree_b});
3487 local $/ = "\0";
3488 while (<$fh>) {
3489 chomp;
3490 my @dn = split m#/#, $_;
3491 while (pop @dn) {
3492 delete $rm->{join '/', @dn};
3494 unless (%$rm) {
3495 close $fh;
3496 return;
3499 command_close_pipe($fh, $ctx);
3501 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3502 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3503 $self->close_directory($bat->{$d}, $p);
3504 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3505 print "\tD+\t$d/\n" unless $::_q;
3506 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3507 delete $bat->{$d};
3511 sub open_or_add_dir {
3512 my ($self, $full_path, $baton) = @_;
3513 my $t = $self->{types}->{$full_path};
3514 if (!defined $t) {
3515 die "$full_path not known in r$self->{r} or we have a bug!\n";
3518 no warnings 'once';
3519 # SVN::Node::none and SVN::Node::file are used only once,
3520 # so we're shutting up Perl's warnings about them.
3521 if ($t == $SVN::Node::none) {
3522 return $self->add_directory($full_path, $baton,
3523 undef, -1, $self->{pool});
3524 } elsif ($t == $SVN::Node::dir) {
3525 return $self->open_directory($full_path, $baton,
3526 $self->{r}, $self->{pool});
3527 } # no warnings 'once'
3528 print STDERR "$full_path already exists in repository at ",
3529 "r$self->{r} and it is not a directory (",
3530 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3531 } # no warnings 'once'
3532 exit 1;
3535 sub ensure_path {
3536 my ($self, $path) = @_;
3537 my $bat = $self->{bat};
3538 my $repo_path = $self->repo_path($path);
3539 return $bat->{''} unless (length $repo_path);
3540 my @p = split m#/+#, $repo_path;
3541 my $c = shift @p;
3542 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3543 while (@p) {
3544 my $c0 = $c;
3545 $c .= '/' . shift @p;
3546 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3548 return $bat->{$c};
3551 # Subroutine to convert a globbing pattern to a regular expression.
3552 # From perl cookbook.
3553 sub glob2pat {
3554 my $globstr = shift;
3555 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3556 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3557 return '^' . $globstr . '$';
3560 sub check_autoprop {
3561 my ($self, $pattern, $properties, $file, $fbat) = @_;
3562 # Convert the globbing pattern to a regular expression.
3563 my $regex = glob2pat($pattern);
3564 # Check if the pattern matches the file name.
3565 if($file =~ m/($regex)/) {
3566 # Parse the list of properties to set.
3567 my @props = split(/;/, $properties);
3568 foreach my $prop (@props) {
3569 # Parse 'name=value' syntax and set the property.
3570 if ($prop =~ /([^=]+)=(.*)/) {
3571 my ($n,$v) = ($1,$2);
3572 for ($n, $v) {
3573 s/^\s+//; s/\s+$//;
3575 $self->change_file_prop($fbat, $n, $v);
3581 sub apply_autoprops {
3582 my ($self, $file, $fbat) = @_;
3583 my $conf_t = ${$self->{config}}{'config'};
3584 no warnings 'once';
3585 # Check [miscellany]/enable-auto-props in svn configuration.
3586 if (SVN::_Core::svn_config_get_bool(
3587 $conf_t,
3588 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3589 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3590 0)) {
3591 # Auto-props are enabled. Enumerate them to look for matches.
3592 my $callback = sub {
3593 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3595 SVN::_Core::svn_config_enumerate(
3596 $conf_t,
3597 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3598 $callback);
3602 sub A {
3603 my ($self, $m) = @_;
3604 my ($dir, $file) = split_path($m->{file_b});
3605 my $pbat = $self->ensure_path($dir);
3606 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3607 undef, -1);
3608 print "\tA\t$m->{file_b}\n" unless $::_q;
3609 $self->apply_autoprops($file, $fbat);
3610 $self->chg_file($fbat, $m);
3611 $self->close_file($fbat,undef,$self->{pool});
3614 sub C {
3615 my ($self, $m) = @_;
3616 my ($dir, $file) = split_path($m->{file_b});
3617 my $pbat = $self->ensure_path($dir);
3618 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3619 $self->url_path($m->{file_a}), $self->{r});
3620 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3621 $self->chg_file($fbat, $m);
3622 $self->close_file($fbat,undef,$self->{pool});
3625 sub delete_entry {
3626 my ($self, $path, $pbat) = @_;
3627 my $rpath = $self->repo_path($path);
3628 my ($dir, $file) = split_path($rpath);
3629 $self->{rm}->{$dir} = 1;
3630 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3633 sub R {
3634 my ($self, $m) = @_;
3635 my ($dir, $file) = split_path($m->{file_b});
3636 my $pbat = $self->ensure_path($dir);
3637 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3638 $self->url_path($m->{file_a}), $self->{r});
3639 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3640 $self->chg_file($fbat, $m);
3641 $self->close_file($fbat,undef,$self->{pool});
3643 ($dir, $file) = split_path($m->{file_a});
3644 $pbat = $self->ensure_path($dir);
3645 $self->delete_entry($m->{file_a}, $pbat);
3648 sub M {
3649 my ($self, $m) = @_;
3650 my ($dir, $file) = split_path($m->{file_b});
3651 my $pbat = $self->ensure_path($dir);
3652 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3653 $pbat,$self->{r},$self->{pool});
3654 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3655 $self->chg_file($fbat, $m);
3656 $self->close_file($fbat,undef,$self->{pool});
3659 sub T { shift->M(@_) }
3661 sub change_file_prop {
3662 my ($self, $fbat, $pname, $pval) = @_;
3663 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3666 sub _chg_file_get_blob ($$$$) {
3667 my ($self, $fbat, $m, $which) = @_;
3668 my $fh = Git::temp_acquire("git_blob_$which");
3669 if ($m->{"mode_$which"} =~ /^120/) {
3670 print $fh 'link ' or croak $!;
3671 $self->change_file_prop($fbat,'svn:special','*');
3672 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3673 $self->change_file_prop($fbat,'svn:special',undef);
3675 my $blob = $m->{"sha1_$which"};
3676 return ($fh,) if ($blob =~ /^0{40}$/);
3677 my $size = $::_repository->cat_blob($blob, $fh);
3678 croak "Failed to read object $blob" if ($size < 0);
3679 $fh->flush == 0 or croak $!;
3680 seek $fh, 0, 0 or croak $!;
3682 my $exp = ::md5sum($fh);
3683 seek $fh, 0, 0 or croak $!;
3684 return ($fh, $exp);
3687 sub chg_file {
3688 my ($self, $fbat, $m) = @_;
3689 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3690 $self->change_file_prop($fbat,'svn:executable','*');
3691 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3692 $self->change_file_prop($fbat,'svn:executable',undef);
3694 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3695 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3696 my $pool = SVN::Pool->new;
3697 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3698 if (-s $fh_a) {
3699 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3700 SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3701 } else {
3702 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3703 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3704 if ($got ne $exp_b);
3706 Git::temp_release($fh_b, 1);
3707 Git::temp_release($fh_a, 1);
3708 $pool->clear;
3711 sub D {
3712 my ($self, $m) = @_;
3713 my ($dir, $file) = split_path($m->{file_b});
3714 my $pbat = $self->ensure_path($dir);
3715 print "\tD\t$m->{file_b}\n" unless $::_q;
3716 $self->delete_entry($m->{file_b}, $pbat);
3719 sub close_edit {
3720 my ($self) = @_;
3721 my ($p,$bat) = ($self->{pool}, $self->{bat});
3722 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3723 next if $_ eq '';
3724 $self->close_directory($bat->{$_}, $p);
3726 $self->close_directory($bat->{''}, $p);
3727 $self->SUPER::close_edit($p);
3728 $p->clear;
3731 sub abort_edit {
3732 my ($self) = @_;
3733 $self->SUPER::abort_edit($self->{pool});
3736 sub DESTROY {
3737 my $self = shift;
3738 $self->SUPER::DESTROY(@_);
3739 $self->{pool}->clear;
3742 # this drives the editor
3743 sub apply_diff {
3744 my ($self) = @_;
3745 my $mods = $self->{mods};
3746 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3747 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3748 my $f = $m->{chg};
3749 if (defined $o{$f}) {
3750 $self->$f($m);
3751 } else {
3752 fatal("Invalid change type: $f");
3755 $self->rmdirs if $_rmdir;
3756 if (@$mods == 0) {
3757 $self->abort_edit;
3758 } else {
3759 $self->close_edit;
3761 return scalar @$mods;
3764 package Git::SVN::Ra;
3765 use vars qw/@ISA $config_dir $_log_window_size/;
3766 use strict;
3767 use warnings;
3768 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3770 BEGIN {
3771 # enforce temporary pool usage for some simple functions
3772 no strict 'refs';
3773 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3774 my $SUPER = "SUPER::$f";
3775 *$f = sub {
3776 my $self = shift;
3777 my $pool = SVN::Pool->new;
3778 my @ret = $self->$SUPER(@_,$pool);
3779 $pool->clear;
3780 wantarray ? @ret : $ret[0];
3785 sub _auth_providers () {
3787 SVN::Client::get_simple_provider(),
3788 SVN::Client::get_ssl_server_trust_file_provider(),
3789 SVN::Client::get_simple_prompt_provider(
3790 \&Git::SVN::Prompt::simple, 2),
3791 SVN::Client::get_ssl_client_cert_file_provider(),
3792 SVN::Client::get_ssl_client_cert_prompt_provider(
3793 \&Git::SVN::Prompt::ssl_client_cert, 2),
3794 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3795 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3796 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3797 SVN::Client::get_username_provider(),
3798 SVN::Client::get_ssl_server_trust_prompt_provider(
3799 \&Git::SVN::Prompt::ssl_server_trust),
3800 SVN::Client::get_username_prompt_provider(
3801 \&Git::SVN::Prompt::username, 2)
3805 sub escape_uri_only {
3806 my ($uri) = @_;
3807 my @tmp;
3808 foreach (split m{/}, $uri) {
3809 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3810 push @tmp, $_;
3812 join('/', @tmp);
3815 sub escape_url {
3816 my ($url) = @_;
3817 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3818 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3819 $url = "$scheme://$domain$uri";
3821 $url;
3824 sub new {
3825 my ($class, $url) = @_;
3826 $url =~ s!/+$!!;
3827 return $RA if ($RA && $RA->{url} eq $url);
3829 SVN::_Core::svn_config_ensure($config_dir, undef);
3830 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3831 my $config = SVN::Core::config_get_config($config_dir);
3832 $RA = undef;
3833 my $dont_store_passwords = 1;
3834 my $conf_t = ${$config}{'config'};
3836 no warnings 'once';
3837 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3838 # produces warnings that variables are used only once.
3839 # I had not found the better way to shut them up, so
3840 # the warnings of type 'once' are disabled in this block.
3841 if (SVN::_Core::svn_config_get_bool($conf_t,
3842 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3843 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3844 1) == 0) {
3845 SVN::_Core::svn_auth_set_parameter($baton,
3846 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3847 bless (\$dont_store_passwords, "_p_void"));
3849 if (SVN::_Core::svn_config_get_bool($conf_t,
3850 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3851 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3852 1) == 0) {
3853 $Git::SVN::Prompt::_no_auth_cache = 1;
3855 } # no warnings 'once'
3856 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3857 config => $config,
3858 pool => SVN::Pool->new,
3859 auth_provider_callbacks => $callbacks);
3860 $self->{url} = $url;
3861 $self->{svn_path} = $url;
3862 $self->{repos_root} = $self->get_repos_root;
3863 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3864 $self->{cache} = { check_path => { r => 0, data => {} },
3865 get_dir => { r => 0, data => {} } };
3866 $RA = bless $self, $class;
3869 sub check_path {
3870 my ($self, $path, $r) = @_;
3871 my $cache = $self->{cache}->{check_path};
3872 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3873 return $cache->{data}->{$path};
3875 my $pool = SVN::Pool->new;
3876 my $t = $self->SUPER::check_path($path, $r, $pool);
3877 $pool->clear;
3878 if ($r != $cache->{r}) {
3879 %{$cache->{data}} = ();
3880 $cache->{r} = $r;
3882 $cache->{data}->{$path} = $t;
3885 sub get_dir {
3886 my ($self, $dir, $r) = @_;
3887 my $cache = $self->{cache}->{get_dir};
3888 if ($r == $cache->{r}) {
3889 if (my $x = $cache->{data}->{$dir}) {
3890 return wantarray ? @$x : $x->[0];
3893 my $pool = SVN::Pool->new;
3894 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3895 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3896 $pool->clear;
3897 if ($r != $cache->{r}) {
3898 %{$cache->{data}} = ();
3899 $cache->{r} = $r;
3901 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3902 wantarray ? (\%dirents, $r, $props) : \%dirents;
3905 sub DESTROY {
3906 # do not call the real DESTROY since we store ourselves in $RA
3909 sub get_log {
3910 my ($self, @args) = @_;
3911 my $pool = SVN::Pool->new;
3912 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3913 my $ret = $self->SUPER::get_log(@args, $pool);
3914 $pool->clear;
3915 $ret;
3918 sub trees_match {
3919 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3920 my $ctx = SVN::Client->new(auth => _auth_providers);
3921 my $out = IO::File->new_tmpfile;
3923 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3924 # $ctx->diff(), so we'll create a default one
3925 my $pool = SVN::Pool->new_default_sub;
3927 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3928 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3929 $out->flush;
3930 my $ret = (($out->stat)[7] == 0);
3931 close $out or croak $!;
3933 $ret;
3936 sub get_commit_editor {
3937 my ($self, $log, $cb, $pool) = @_;
3938 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3939 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3942 sub gs_do_update {
3943 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3944 my $new = ($rev_a == $rev_b);
3945 my $path = $gs->{path};
3947 if ($new && -e $gs->{index}) {
3948 unlink $gs->{index} or die
3949 "Couldn't unlink index: $gs->{index}: $!\n";
3951 my $pool = SVN::Pool->new;
3952 $editor->set_path_strip($path);
3953 my (@pc) = split m#/#, $path;
3954 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3955 1, $editor, $pool);
3956 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3958 # Since we can't rely on svn_ra_reparent being available, we'll
3959 # just have to do some magic with set_path to make it so
3960 # we only want a partial path.
3961 my $sp = '';
3962 my $final = join('/', @pc);
3963 while (@pc) {
3964 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3965 $sp .= '/' if length $sp;
3966 $sp .= shift @pc;
3968 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3970 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3972 $reporter->finish_report($pool);
3973 $pool->clear;
3974 $editor->{git_commit_ok};
3977 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3978 # svn_ra_reparent didn't work before 1.4)
3979 sub gs_do_switch {
3980 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3981 my $path = $gs->{path};
3982 my $pool = SVN::Pool->new;
3984 my $full_url = $self->{url};
3985 my $old_url = $full_url;
3986 $full_url .= '/' . escape_uri_only($path) if length $path;
3987 my ($ra, $reparented);
3988 if ($old_url ne $full_url) {
3989 if ($old_url !~ m#^svn(\+ssh)?://#) {
3990 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3991 $pool);
3992 $self->{url} = $full_url;
3993 $reparented = 1;
3994 } else {
3995 $_[0] = undef;
3996 $self = undef;
3997 $RA = undef;
3998 $ra = Git::SVN::Ra->new($full_url);
3999 $ra_invalid = 1;
4002 $ra ||= $self;
4003 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4004 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4005 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4006 $reporter->finish_report($pool);
4008 if ($reparented) {
4009 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4010 $self->{url} = $old_url;
4013 $pool->clear;
4014 $editor->{git_commit_ok};
4017 sub longest_common_path {
4018 my ($gsv, $globs) = @_;
4019 my %common;
4020 my $common_max = scalar @$gsv;
4022 foreach my $gs (@$gsv) {
4023 my @tmp = split m#/#, $gs->{path};
4024 my $p = '';
4025 foreach (@tmp) {
4026 $p .= length($p) ? "/$_" : $_;
4027 $common{$p} ||= 0;
4028 $common{$p}++;
4031 $globs ||= [];
4032 $common_max += scalar @$globs;
4033 foreach my $glob (@$globs) {
4034 my @tmp = split m#/#, $glob->{path}->{left};
4035 my $p = '';
4036 foreach (@tmp) {
4037 $p .= length($p) ? "/$_" : $_;
4038 $common{$p} ||= 0;
4039 $common{$p}++;
4043 my $longest_path = '';
4044 foreach (sort {length $b <=> length $a} keys %common) {
4045 if ($common{$_} == $common_max) {
4046 $longest_path = $_;
4047 last;
4050 $longest_path;
4053 sub gs_fetch_loop_common {
4054 my ($self, $base, $head, $gsv, $globs) = @_;
4055 return if ($base > $head);
4056 my $inc = $_log_window_size;
4057 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4058 my $longest_path = longest_common_path($gsv, $globs);
4059 my $ra_url = $self->{url};
4060 while (1) {
4061 my %revs;
4062 my $err;
4063 my $err_handler = $SVN::Error::handler;
4064 $SVN::Error::handler = sub {
4065 ($err) = @_;
4066 skip_unknown_revs($err);
4068 sub _cb {
4069 my ($paths, $r, $author, $date, $log) = @_;
4070 [ dup_changed_paths($paths),
4071 { author => $author, date => $date, log => $log } ];
4073 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4074 sub { $revs{$_[1]} = _cb(@_) });
4075 if ($err && $max >= $head) {
4076 print STDERR "Path '$longest_path' ",
4077 "was probably deleted:\n",
4078 $err->expanded_message,
4079 "\nWill attempt to follow ",
4080 "revisions r$min .. r$max ",
4081 "committed before the deletion\n";
4082 my $hi = $max;
4083 while (--$hi >= $min) {
4084 my $ok;
4085 $self->get_log([$longest_path], $min, $hi,
4086 0, 1, 1, sub {
4087 $ok ||= $_[1];
4088 $revs{$_[1]} = _cb(@_) });
4089 if ($ok) {
4090 print STDERR "r$min .. r$ok OK\n";
4091 last;
4095 $SVN::Error::handler = $err_handler;
4097 my %exists = map { $_->{path} => $_ } @$gsv;
4098 foreach my $r (sort {$a <=> $b} keys %revs) {
4099 my ($paths, $logged) = @{$revs{$r}};
4101 foreach my $gs ($self->match_globs(\%exists, $paths,
4102 $globs, $r)) {
4103 if ($gs->rev_map_max >= $r) {
4104 next;
4106 next unless $gs->match_paths($paths, $r);
4107 $gs->{logged_rev_props} = $logged;
4108 if (my $last_commit = $gs->last_commit) {
4109 $gs->assert_index_clean($last_commit);
4111 my $log_entry = $gs->do_fetch($paths, $r);
4112 if ($log_entry) {
4113 $gs->do_git_commit($log_entry);
4115 $INDEX_FILES{$gs->{index}} = 1;
4117 foreach my $g (@$globs) {
4118 my $k = "svn-remote.$g->{remote}." .
4119 "$g->{t}-maxRev";
4120 Git::SVN::tmp_config($k, $r);
4122 if ($ra_invalid) {
4123 $_[0] = undef;
4124 $self = undef;
4125 $RA = undef;
4126 $self = Git::SVN::Ra->new($ra_url);
4127 $ra_invalid = undef;
4130 # pre-fill the .rev_db since it'll eventually get filled in
4131 # with '0' x40 if something new gets committed
4132 foreach my $gs (@$gsv) {
4133 next if $gs->rev_map_max >= $max;
4134 next if defined $gs->rev_map_get($max);
4135 $gs->rev_map_set($max, 0 x40);
4137 foreach my $g (@$globs) {
4138 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4139 Git::SVN::tmp_config($k, $max);
4141 last if $max >= $head;
4142 $min = $max + 1;
4143 $max += $inc;
4144 $max = $head if ($max > $head);
4146 Git::SVN::gc();
4149 sub get_dir_globbed {
4150 my ($self, $left, $depth, $r) = @_;
4152 my @x = eval { $self->get_dir($left, $r) };
4153 return unless scalar @x == 3;
4154 my $dirents = $x[0];
4155 my @finalents;
4156 foreach my $de (keys %$dirents) {
4157 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4158 if ($depth > 1) {
4159 my @args = ("$left/$de", $depth - 1, $r);
4160 foreach my $dir ($self->get_dir_globbed(@args)) {
4161 push @finalents, "$de/$dir";
4163 } else {
4164 push @finalents, $de;
4167 @finalents;
4170 sub match_globs {
4171 my ($self, $exists, $paths, $globs, $r) = @_;
4173 sub get_dir_check {
4174 my ($self, $exists, $g, $r) = @_;
4176 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4177 $g->{path}->{depth},
4178 $r);
4180 foreach my $de (@dirs) {
4181 my $p = $g->{path}->full_path($de);
4182 next if $exists->{$p};
4183 next if (length $g->{path}->{right} &&
4184 ($self->check_path($p, $r) !=
4185 $SVN::Node::dir));
4186 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4187 $g->{ref}->full_path($de), 1);
4190 foreach my $g (@$globs) {
4191 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4192 if ($path->{action} =~ /^[AR]$/) {
4193 get_dir_check($self, $exists, $g, $r);
4196 foreach (keys %$paths) {
4197 if (/$g->{path}->{left_regex}/ &&
4198 !/$g->{path}->{regex}/) {
4199 next if $paths->{$_}->{action} !~ /^[AR]$/;
4200 get_dir_check($self, $exists, $g, $r);
4202 next unless /$g->{path}->{regex}/;
4203 my $p = $1;
4204 my $pathname = $g->{path}->full_path($p);
4205 next if $exists->{$pathname};
4206 next if ($self->check_path($pathname, $r) !=
4207 $SVN::Node::dir);
4208 $exists->{$pathname} = Git::SVN->init(
4209 $self->{url}, $pathname, undef,
4210 $g->{ref}->full_path($p), 1);
4212 my $c = '';
4213 foreach (split m#/#, $g->{path}->{left}) {
4214 $c .= "/$_";
4215 next unless ($paths->{$c} &&
4216 ($paths->{$c}->{action} =~ /^[AR]$/));
4217 get_dir_check($self, $exists, $g, $r);
4220 values %$exists;
4223 sub minimize_url {
4224 my ($self) = @_;
4225 return $self->{url} if ($self->{url} eq $self->{repos_root});
4226 my $url = $self->{repos_root};
4227 my @components = split(m!/!, $self->{svn_path});
4228 my $c = '';
4229 do {
4230 $url .= "/$c" if length $c;
4231 eval { (ref $self)->new($url)->get_latest_revnum };
4232 } while ($@ && ($c = shift @components));
4233 $url;
4236 sub can_do_switch {
4237 my $self = shift;
4238 unless (defined $can_do_switch) {
4239 my $pool = SVN::Pool->new;
4240 my $rep = eval {
4241 $self->do_switch(1, '', 0, $self->{url},
4242 SVN::Delta::Editor->new, $pool);
4244 if ($@) {
4245 $can_do_switch = 0;
4246 } else {
4247 $rep->abort_report($pool);
4248 $can_do_switch = 1;
4250 $pool->clear;
4252 $can_do_switch;
4255 sub skip_unknown_revs {
4256 my ($err) = @_;
4257 my $errno = $err->apr_err();
4258 # Maybe the branch we're tracking didn't
4259 # exist when the repo started, so it's
4260 # not an error if it doesn't, just continue
4262 # Wonderfully consistent library, eh?
4263 # 160013 - svn:// and file://
4264 # 175002 - http(s)://
4265 # 175007 - http(s):// (this repo required authorization, too...)
4266 # More codes may be discovered later...
4267 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4268 my $err_key = $err->expanded_message;
4269 # revision numbers change every time, filter them out
4270 $err_key =~ s/\d+/\0/g;
4271 $err_key = "$errno\0$err_key";
4272 unless ($ignored_err{$err_key}) {
4273 warn "W: Ignoring error from SVN, path probably ",
4274 "does not exist: ($errno): ",
4275 $err->expanded_message,"\n";
4276 warn "W: Do not be alarmed at the above message ",
4277 "git-svn is just searching aggressively for ",
4278 "old history.\n",
4279 "This may take a while on large repositories\n";
4280 $ignored_err{$err_key} = 1;
4282 return;
4284 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4287 # svn_log_changed_path_t objects passed to get_log are likely to be
4288 # overwritten even if only the refs are copied to an external variable,
4289 # so we should dup the structures in their entirety. Using an externally
4290 # passed pool (instead of our temporary and quickly cleared pool in
4291 # Git::SVN::Ra) does not help matters at all...
4292 sub dup_changed_paths {
4293 my ($paths) = @_;
4294 return undef unless $paths;
4295 my %ret;
4296 foreach my $p (keys %$paths) {
4297 my $i = $paths->{$p};
4298 my %s = map { $_ => $i->$_ }
4299 qw/copyfrom_path copyfrom_rev action/;
4300 $ret{$p} = \%s;
4302 \%ret;
4305 package Git::SVN::Log;
4306 use strict;
4307 use warnings;
4308 use POSIX qw/strftime/;
4309 use constant commit_log_separator => ('-' x 72) . "\n";
4310 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4311 %rusers $show_commit $incremental/;
4312 my $l_fmt;
4314 sub cmt_showable {
4315 my ($c) = @_;
4316 return 1 if defined $c->{r};
4318 # big commit message got truncated by the 16k pretty buffer in rev-list
4319 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4320 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4321 @{$c->{l}} = ();
4322 my @log = command(qw/cat-file commit/, $c->{c});
4324 # shift off the headers
4325 shift @log while ($log[0] ne '');
4326 shift @log;
4328 # TODO: make $c->{l} not have a trailing newline in the future
4329 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4331 (undef, $c->{r}, undef) = ::extract_metadata(
4332 (grep(/^git-svn-id: /, @log))[-1]);
4334 return defined $c->{r};
4337 sub log_use_color {
4338 return $color || Git->repository->get_colorbool('color.diff');
4341 sub git_svn_log_cmd {
4342 my ($r_min, $r_max, @args) = @_;
4343 my $head = 'HEAD';
4344 my (@files, @log_opts);
4345 foreach my $x (@args) {
4346 if ($x eq '--' || @files) {
4347 push @files, $x;
4348 } else {
4349 if (::verify_ref("$x^0")) {
4350 $head = $x;
4351 } else {
4352 push @log_opts, $x;
4357 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4358 $gs ||= Git::SVN->_new;
4359 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4360 $gs->refname);
4361 push @cmd, '-r' unless $non_recursive;
4362 push @cmd, qw/--raw --name-status/ if $verbose;
4363 push @cmd, '--color' if log_use_color();
4364 push @cmd, @log_opts;
4365 if (defined $r_max && $r_max == $r_min) {
4366 push @cmd, '--max-count=1';
4367 if (my $c = $gs->rev_map_get($r_max)) {
4368 push @cmd, $c;
4370 } elsif (defined $r_max) {
4371 if ($r_max < $r_min) {
4372 ($r_min, $r_max) = ($r_max, $r_min);
4374 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4375 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4376 # If there are no commits in the range, both $c_max and $c_min
4377 # will be undefined. If there is at least 1 commit in the
4378 # range, both will be defined.
4379 return () if !defined $c_min || !defined $c_max;
4380 if ($c_min eq $c_max) {
4381 push @cmd, '--max-count=1', $c_min;
4382 } else {
4383 push @cmd, '--boundary', "$c_min..$c_max";
4386 return (@cmd, @files);
4389 # adapted from pager.c
4390 sub config_pager {
4391 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4392 if (!defined $pager) {
4393 $pager = 'less';
4394 } elsif (length $pager == 0 || $pager eq 'cat') {
4395 $pager = undef;
4397 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4400 sub run_pager {
4401 return unless -t *STDOUT && defined $pager;
4402 pipe my $rfd, my $wfd or return;
4403 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4404 if (!$pid) {
4405 open STDOUT, '>&', $wfd or
4406 ::fatal "Can't redirect to stdout: $!";
4407 return;
4409 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4410 $ENV{LESS} ||= 'FRSX';
4411 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4414 sub format_svn_date {
4415 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4418 sub parse_git_date {
4419 my ($t, $tz) = @_;
4420 # Date::Parse isn't in the standard Perl distro :(
4421 if ($tz =~ s/^\+//) {
4422 $t += tz_to_s_offset($tz);
4423 } elsif ($tz =~ s/^\-//) {
4424 $t -= tz_to_s_offset($tz);
4426 return $t;
4429 sub set_local_timezone {
4430 if (defined $TZ) {
4431 $ENV{TZ} = $TZ;
4432 } else {
4433 delete $ENV{TZ};
4437 sub tz_to_s_offset {
4438 my ($tz) = @_;
4439 $tz =~ s/(\d\d)$//;
4440 return ($1 * 60) + ($tz * 3600);
4443 sub get_author_info {
4444 my ($dest, $author, $t, $tz) = @_;
4445 $author =~ s/(?:^\s*|\s*$)//g;
4446 $dest->{a_raw} = $author;
4447 my $au;
4448 if ($::_authors) {
4449 $au = $rusers{$author} || undef;
4451 if (!$au) {
4452 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4454 $dest->{t} = $t;
4455 $dest->{tz} = $tz;
4456 $dest->{a} = $au;
4457 $dest->{t_utc} = parse_git_date($t, $tz);
4460 sub process_commit {
4461 my ($c, $r_min, $r_max, $defer) = @_;
4462 if (defined $r_min && defined $r_max) {
4463 if ($r_min == $c->{r} && $r_min == $r_max) {
4464 show_commit($c);
4465 return 0;
4467 return 1 if $r_min == $r_max;
4468 if ($r_min < $r_max) {
4469 # we need to reverse the print order
4470 return 0 if (defined $limit && --$limit < 0);
4471 push @$defer, $c;
4472 return 1;
4474 if ($r_min != $r_max) {
4475 return 1 if ($r_min < $c->{r});
4476 return 1 if ($r_max > $c->{r});
4479 return 0 if (defined $limit && --$limit < 0);
4480 show_commit($c);
4481 return 1;
4484 sub show_commit {
4485 my $c = shift;
4486 if ($oneline) {
4487 my $x = "\n";
4488 if (my $l = $c->{l}) {
4489 while ($l->[0] =~ /^\s*$/) { shift @$l }
4490 $x = $l->[0];
4492 $l_fmt ||= 'A' . length($c->{r});
4493 print 'r',pack($l_fmt, $c->{r}),' | ';
4494 print "$c->{c} | " if $show_commit;
4495 print $x;
4496 } else {
4497 show_commit_normal($c);
4501 sub show_commit_changed_paths {
4502 my ($c) = @_;
4503 return unless $c->{changed};
4504 print "Changed paths:\n", @{$c->{changed}};
4507 sub show_commit_normal {
4508 my ($c) = @_;
4509 print commit_log_separator, "r$c->{r} | ";
4510 print "$c->{c} | " if $show_commit;
4511 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4512 my $nr_line = 0;
4514 if (my $l = $c->{l}) {
4515 while ($l->[$#$l] eq "\n" && $#$l > 0
4516 && $l->[($#$l - 1)] eq "\n") {
4517 pop @$l;
4519 $nr_line = scalar @$l;
4520 if (!$nr_line) {
4521 print "1 line\n\n\n";
4522 } else {
4523 if ($nr_line == 1) {
4524 $nr_line = '1 line';
4525 } else {
4526 $nr_line .= ' lines';
4528 print $nr_line, "\n";
4529 show_commit_changed_paths($c);
4530 print "\n";
4531 print $_ foreach @$l;
4533 } else {
4534 print "1 line\n";
4535 show_commit_changed_paths($c);
4536 print "\n";
4539 foreach my $x (qw/raw stat diff/) {
4540 if ($c->{$x}) {
4541 print "\n";
4542 print $_ foreach @{$c->{$x}}
4547 sub cmd_show_log {
4548 my (@args) = @_;
4549 my ($r_min, $r_max);
4550 my $r_last = -1; # prevent dupes
4551 set_local_timezone();
4552 if (defined $::_revision) {
4553 if ($::_revision =~ /^(\d+):(\d+)$/) {
4554 ($r_min, $r_max) = ($1, $2);
4555 } elsif ($::_revision =~ /^\d+$/) {
4556 $r_min = $r_max = $::_revision;
4557 } else {
4558 ::fatal "-r$::_revision is not supported, use ",
4559 "standard 'git log' arguments instead";
4563 config_pager();
4564 @args = git_svn_log_cmd($r_min, $r_max, @args);
4565 if (!@args) {
4566 print commit_log_separator unless $incremental || $oneline;
4567 return;
4569 my $log = command_output_pipe(@args);
4570 run_pager();
4571 my (@k, $c, $d, $stat);
4572 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4573 while (<$log>) {
4574 if (/^${esc_color}commit -?($::sha1_short)/o) {
4575 my $cmt = $1;
4576 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4577 $r_last = $c->{r};
4578 process_commit($c, $r_min, $r_max, \@k) or
4579 goto out;
4581 $d = undef;
4582 $c = { c => $cmt };
4583 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4584 get_author_info($c, $1, $2, $3);
4585 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4586 # ignore
4587 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4588 push @{$c->{raw}}, $_;
4589 } elsif (/^${esc_color}[ACRMDT]\t/) {
4590 # we could add $SVN->{svn_path} here, but that requires
4591 # remote access at the moment (repo_path_split)...
4592 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4593 push @{$c->{changed}}, $_;
4594 } elsif (/^${esc_color}diff /o) {
4595 $d = 1;
4596 push @{$c->{diff}}, $_;
4597 } elsif ($d) {
4598 push @{$c->{diff}}, $_;
4599 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4600 $esc_color*[\+\-]*$esc_color$/x) {
4601 $stat = 1;
4602 push @{$c->{stat}}, $_;
4603 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4604 push @{$c->{stat}}, $_;
4605 $stat = undef;
4606 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4607 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4608 } elsif (s/^${esc_color} //o) {
4609 push @{$c->{l}}, $_;
4612 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4613 $r_last = $c->{r};
4614 process_commit($c, $r_min, $r_max, \@k);
4616 if (@k) {
4617 ($r_min, $r_max) = ($r_max, $r_min);
4618 process_commit($_, $r_min, $r_max) foreach reverse @k;
4620 out:
4621 close $log;
4622 print commit_log_separator unless $incremental || $oneline;
4625 sub cmd_blame {
4626 my $path = pop;
4628 config_pager();
4629 run_pager();
4631 my ($fh, $ctx, $rev);
4633 if ($_git_format) {
4634 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4635 while (my $line = <$fh>) {
4636 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4637 # Uncommitted edits show up as a rev ID of
4638 # all zeros, which we can't look up with
4639 # cmt_metadata
4640 if ($1 !~ /^0+$/) {
4641 (undef, $rev, undef) =
4642 ::cmt_metadata($1);
4643 $rev = '0' if (!$rev);
4644 } else {
4645 $rev = '0';
4647 $rev = sprintf('%-10s', $rev);
4648 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4650 print $line;
4652 } else {
4653 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4654 '--', $path);
4655 my ($sha1);
4656 my %authors;
4657 while (my $line = <$fh>) {
4658 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4659 $sha1 = $1;
4660 (undef, $rev, undef) = ::cmt_metadata($1);
4661 $rev = '0' if (!$rev);
4663 elsif ($line =~ /^author (.*)/) {
4664 $authors{$rev} = $1;
4665 $authors{$rev} =~ s/\s/_/g;
4667 elsif ($line =~ /^\t(.*)$/) {
4668 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4672 command_close_pipe($fh, $ctx);
4675 package Git::SVN::Migration;
4676 # these version numbers do NOT correspond to actual version numbers
4677 # of git nor git-svn. They are just relative.
4679 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4681 # v1 layout: .git/$id/info/url, refs/remotes/$id
4683 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4685 # v3 layout: .git/svn/$id, refs/remotes/$id
4686 # - info/url may remain for backwards compatibility
4687 # - this is what we migrate up to this layout automatically,
4688 # - this will be used by git svn init on single branches
4689 # v3.1 layout (auto migrated):
4690 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4691 # for backwards compatibility
4693 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4694 # - this is only created for newly multi-init-ed
4695 # repositories. Similar in spirit to the
4696 # --use-separate-remotes option in git-clone (now default)
4697 # - we do not automatically migrate to this (following
4698 # the example set by core git)
4700 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4701 # - newer, more-efficient format that uses 24-bytes per record
4702 # with no filler space.
4703 # - use xxd -c24 < .rev_map.$UUID to view and debug
4704 # - This is a one-way migration, repositories updated to the
4705 # new format will not be able to use old git-svn without
4706 # rebuilding the .rev_db. Rebuilding the rev_db is not
4707 # possible if noMetadata or useSvmProps are set; but should
4708 # be no problem for users that use the (sensible) defaults.
4709 use strict;
4710 use warnings;
4711 use Carp qw/croak/;
4712 use File::Path qw/mkpath/;
4713 use File::Basename qw/dirname basename/;
4714 use vars qw/$_minimize/;
4716 sub migrate_from_v0 {
4717 my $git_dir = $ENV{GIT_DIR};
4718 return undef unless -d $git_dir;
4719 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4720 my $migrated = 0;
4721 while (<$fh>) {
4722 chomp;
4723 my ($id, $orig_ref) = ($_, $_);
4724 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4725 next unless -f "$git_dir/$id/info/url";
4726 my $new_ref = "refs/remotes/$id";
4727 if (::verify_ref("$new_ref^0")) {
4728 print STDERR "W: $orig_ref is probably an old ",
4729 "branch used by an ancient version of ",
4730 "git-svn.\n",
4731 "However, $new_ref also exists.\n",
4732 "We will not be able ",
4733 "to use this branch until this ",
4734 "ambiguity is resolved.\n";
4735 next;
4737 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4738 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4739 command_noisy('update-ref', $new_ref, $orig_ref);
4740 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4741 $migrated++;
4743 command_close_pipe($fh, $ctx);
4744 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4745 $migrated;
4748 sub migrate_from_v1 {
4749 my $git_dir = $ENV{GIT_DIR};
4750 my $migrated = 0;
4751 return $migrated unless -d $git_dir;
4752 my $svn_dir = "$git_dir/svn";
4754 # just in case somebody used 'svn' as their $id at some point...
4755 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4757 print STDERR "Migrating from a git-svn v1 layout...\n";
4758 mkpath([$svn_dir]);
4759 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4760 "$svn_dir\n\t(required for this version ",
4761 "($::VERSION) of git-svn) does not exist.\n";
4762 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4763 while (<$fh>) {
4764 my $x = $_;
4765 next unless $x =~ s#^refs/remotes/##;
4766 chomp $x;
4767 next unless -f "$git_dir/$x/info/url";
4768 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4769 next unless $u;
4770 my $dn = dirname("$git_dir/svn/$x");
4771 mkpath([$dn]) unless -d $dn;
4772 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4773 mkpath(["$git_dir/svn/svn"]);
4774 print STDERR " - $git_dir/$x/info => ",
4775 "$git_dir/svn/$x/info\n";
4776 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4777 croak "$!: $x";
4778 # don't worry too much about these, they probably
4779 # don't exist with repos this old (save for index,
4780 # and we can easily regenerate that)
4781 foreach my $f (qw/unhandled.log index .rev_db/) {
4782 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4784 } else {
4785 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4786 rename "$git_dir/$x", "$git_dir/svn/$x" or
4787 croak "$!: $x";
4789 $migrated++;
4791 command_close_pipe($fh, $ctx);
4792 print STDERR "Done migrating from a git-svn v1 layout\n";
4793 $migrated;
4796 sub read_old_urls {
4797 my ($l_map, $pfx, $path) = @_;
4798 my @dir;
4799 foreach (<$path/*>) {
4800 if (-r "$_/info/url") {
4801 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4802 my $ref_id = $pfx . basename $_;
4803 my $url = ::file_to_s("$_/info/url");
4804 $l_map->{$ref_id} = $url;
4805 } elsif (-d $_) {
4806 push @dir, $_;
4809 foreach (@dir) {
4810 my $x = $_;
4811 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4812 read_old_urls($l_map, $x, $_);
4816 sub migrate_from_v2 {
4817 my @cfg = command(qw/config -l/);
4818 return if grep /^svn-remote\..+\.url=/, @cfg;
4819 my %l_map;
4820 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4821 my $migrated = 0;
4823 foreach my $ref_id (sort keys %l_map) {
4824 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4825 if ($@) {
4826 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4828 $migrated++;
4830 $migrated;
4833 sub minimize_connections {
4834 my $r = Git::SVN::read_all_remotes();
4835 my $new_urls = {};
4836 my $root_repos = {};
4837 foreach my $repo_id (keys %$r) {
4838 my $url = $r->{$repo_id}->{url} or next;
4839 my $fetch = $r->{$repo_id}->{fetch} or next;
4840 my $ra = Git::SVN::Ra->new($url);
4842 # skip existing cases where we already connect to the root
4843 if (($ra->{url} eq $ra->{repos_root}) ||
4844 ($ra->{repos_root} eq $repo_id)) {
4845 $root_repos->{$ra->{url}} = $repo_id;
4846 next;
4849 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4850 my $root_path = $ra->{url};
4851 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4852 foreach my $path (keys %$fetch) {
4853 my $ref_id = $fetch->{$path};
4854 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4856 # make sure we can read when connecting to
4857 # a higher level of a repository
4858 my ($last_rev, undef) = $gs->last_rev_commit;
4859 if (!defined $last_rev) {
4860 $last_rev = eval {
4861 $root_ra->get_latest_revnum;
4863 next if $@;
4865 my $new = $root_path;
4866 $new .= length $path ? "/$path" : '';
4867 eval {
4868 $root_ra->get_log([$new], $last_rev, $last_rev,
4869 0, 0, 1, sub { });
4871 next if $@;
4872 $new_urls->{$ra->{repos_root}}->{$new} =
4873 { ref_id => $ref_id,
4874 old_repo_id => $repo_id,
4875 old_path => $path };
4879 my @emptied;
4880 foreach my $url (keys %$new_urls) {
4881 # see if we can re-use an existing [svn-remote "repo_id"]
4882 # instead of creating a(n ugly) new section:
4883 my $repo_id = $root_repos->{$url} || $url;
4885 my $fetch = $new_urls->{$url};
4886 foreach my $path (keys %$fetch) {
4887 my $x = $fetch->{$path};
4888 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4889 my $pfx = "svn-remote.$x->{old_repo_id}";
4891 my $old_fetch = quotemeta("$x->{old_path}:".
4892 "refs/remotes/$x->{ref_id}");
4893 command_noisy(qw/config --unset/,
4894 "$pfx.fetch", '^'. $old_fetch . '$');
4895 delete $r->{$x->{old_repo_id}}->
4896 {fetch}->{$x->{old_path}};
4897 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4898 command_noisy(qw/config --unset/,
4899 "$pfx.url");
4900 push @emptied, $x->{old_repo_id}
4904 if (@emptied) {
4905 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4906 "$ENV{GIT_DIR}/config";
4907 print STDERR <<EOF;
4908 The following [svn-remote] sections in your config file ($file) are empty
4909 and can be safely removed:
4911 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4915 sub migration_check {
4916 migrate_from_v0();
4917 migrate_from_v1();
4918 migrate_from_v2();
4919 minimize_connections() if $_minimize;
4922 package Git::IndexInfo;
4923 use strict;
4924 use warnings;
4925 use Git qw/command_input_pipe command_close_pipe/;
4927 sub new {
4928 my ($class) = @_;
4929 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4930 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4933 sub remove {
4934 my ($self, $path) = @_;
4935 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4936 return ++$self->{nr};
4938 undef;
4941 sub update {
4942 my ($self, $mode, $hash, $path) = @_;
4943 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4944 return ++$self->{nr};
4946 undef;
4949 sub DESTROY {
4950 my ($self) = @_;
4951 command_close_pipe($self->{gui}, $self->{ctx});
4954 package Git::SVN::GlobSpec;
4955 use strict;
4956 use warnings;
4958 sub new {
4959 my ($class, $glob) = @_;
4960 my $re = $glob;
4961 $re =~ s!/+$!!g; # no need for trailing slashes
4962 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
4963 my $temp = $re;
4964 my ($left, $right) = ($1, $3);
4965 $re = $2;
4966 my $depth = $re =~ tr/*/*/;
4967 if ($depth != $temp =~ tr/*/*/) {
4968 die "Only one set of wildcard directories " .
4969 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
4971 if ($depth == 0) {
4972 die "One '*' is needed for glob: '$glob'\n";
4974 $re =~ s!\*!\[^/\]*!g;
4975 $re = quotemeta($left) . "($re)" . quotemeta($right);
4976 if (length $left && !($left =~ s!/+$!!g)) {
4977 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4979 if (length $right && !($right =~ s!^/+!!g)) {
4980 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4982 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4983 bless { left => $left, right => $right, left_regex => $left_re,
4984 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4987 sub full_path {
4988 my ($self, $path) = @_;
4989 return (length $self->{left} ? "$self->{left}/" : '') .
4990 $path . (length $self->{right} ? "/$self->{right}" : '');
4993 __END__
4995 Data structures:
4998 $remotes = { # returned by read_all_remotes()
4999 'svn' => {
5000 # svn-remote.svn.url=https://svn.musicpd.org
5001 url => 'https://svn.musicpd.org',
5002 # svn-remote.svn.fetch=mpd/trunk:trunk
5003 fetch => {
5004 'mpd/trunk' => 'trunk',
5006 # svn-remote.svn.tags=mpd/tags/*:tags/*
5007 tags => {
5008 path => {
5009 left => 'mpd/tags',
5010 right => '',
5011 regex => qr!mpd/tags/([^/]+)$!,
5012 glob => 'tags/*',
5014 ref => {
5015 left => 'tags',
5016 right => '',
5017 regex => qr!tags/([^/]+)$!,
5018 glob => 'tags/*',
5024 $log_entry hashref as returned by libsvn_log_entry()
5026 log => 'whitespace-formatted log entry
5027 ', # trailing newline is preserved
5028 revision => '8', # integer
5029 date => '2004-02-24T17:01:44.108345Z', # commit date
5030 author => 'committer name'
5034 # this is generated by generate_diff();
5035 @mods = array of diff-index line hashes, each element represents one line
5036 of diff-index output
5038 diff-index line ($m hash)
5040 mode_a => first column of diff-index output, no leading ':',
5041 mode_b => second column of diff-index output,
5042 sha1_b => sha1sum of the final blob,
5043 chg => change type [MCRADT],
5044 file_a => original file name of a file (iff chg is 'C' or 'R')
5045 file_b => new/current file name of a file (any chg)
5049 # retval of read_url_paths{,_all}();
5050 $l_map = {
5051 # repository root url
5052 'https://svn.musicpd.org' => {
5053 # repository path # GIT_SVN_ID
5054 'mpd/trunk' => 'trunk',
5055 'mpd/tags/0.11.5' => 'tags/0.11.5',
5059 Notes:
5060 I don't trust the each() function on unless I created %hash myself
5061 because the internal iterator may not have started at base.