git-svn: add ability to specify --commit-url for dcommit
[git/mingw.git] / git-svn.perl
blob06a82c80cec51ce53fd0c978f016861afc8de9fd
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, "Translate between SVN revision numbers and tree-ish",
175 {} ],
176 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
177 { 'merge|m|M' => \$_merge,
178 'verbose|v' => \$_verbose,
179 'strategy|s=s' => \$_strategy,
180 'local|l' => \$_local,
181 'fetch-all|all' => \$_fetch_all,
182 'dry-run|n' => \$_dry_run,
183 %fc_opts } ],
184 'commit-diff' => [ \&cmd_commit_diff,
185 'Commit a diff between two trees',
186 { 'message|m=s' => \$_message,
187 'file|F=s' => \$_file,
188 'revision|r=s' => \$_revision,
189 %cmt_opts } ],
190 'info' => [ \&cmd_info,
191 "Show info about the latest SVN revision
192 on the current branch",
193 { 'url' => \$_url, } ],
194 'blame' => [ \&Git::SVN::Log::cmd_blame,
195 "Show what revision and author last modified each line of a file",
196 { 'git-format' => \$_git_format } ],
199 my $cmd;
200 for (my $i = 0; $i < @ARGV; $i++) {
201 if (defined $cmd{$ARGV[$i]}) {
202 $cmd = $ARGV[$i];
203 splice @ARGV, $i, 1;
204 last;
208 # make sure we're always running at the top-level working directory
209 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
210 unless (-d $ENV{GIT_DIR}) {
211 if ($git_dir_user_set) {
212 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
213 "but it is not a directory\n";
215 my $git_dir = delete $ENV{GIT_DIR};
216 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
217 unless (length $cdup) {
218 die "Already at toplevel, but $git_dir ",
219 "not found '$cdup'\n";
221 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
222 unless (-d $git_dir) {
223 die "$git_dir still not found after going to ",
224 "'$cdup'\n";
226 $ENV{GIT_DIR} = $git_dir;
228 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
231 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
233 read_repo_config(\%opts);
234 Getopt::Long::Configure('pass_through') if ($cmd && ($cmd eq 'log' || $cmd eq 'blame'));
235 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
236 'minimize-connections' => \$Git::SVN::Migration::_minimize,
237 'id|i=s' => \$Git::SVN::default_ref_id,
238 'svn-remote|remote|R=s' => sub {
239 $Git::SVN::no_reuse_existing = 1;
240 $Git::SVN::default_repo_id = $_[1] });
241 exit 1 if (!$rv && $cmd && $cmd ne 'log');
243 usage(0) if $_help;
244 version() if $_version;
245 usage(1) unless defined $cmd;
246 load_authors() if $_authors;
248 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
249 Git::SVN::Migration::migration_check();
251 Git::SVN::init_vars();
252 eval {
253 Git::SVN::verify_remotes_sanity();
254 $cmd{$cmd}->[0]->(@ARGV);
256 fatal $@ if $@;
257 post_fetch_checkout();
258 exit 0;
260 ####################### primary functions ######################
261 sub usage {
262 my $exit = shift || 0;
263 my $fd = $exit ? \*STDERR : \*STDOUT;
264 print $fd <<"";
265 git-svn - bidirectional operations between a single Subversion tree and git
266 Usage: git svn <command> [options] [arguments]\n
268 print $fd "Available commands:\n" unless $cmd;
270 foreach (sort keys %cmd) {
271 next if $cmd && $cmd ne $_;
272 next if /^multi-/; # don't show deprecated commands
273 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
274 foreach (sort keys %{$cmd{$_}->[2]}) {
275 # mixed-case options are for .git/config only
276 next if /[A-Z]/ && /^[a-z]+$/i;
277 # prints out arguments as they should be passed:
278 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
279 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
280 "--$_" : "-$_" }
281 split /\|/,$_)," $x\n";
284 print $fd <<"";
285 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
286 arbitrary identifier if you're tracking multiple SVN branches/repositories in
287 one git repository and want to keep them separate. See git-svn(1) for more
288 information.
290 exit $exit;
293 sub version {
294 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
295 exit 0;
298 sub do_git_init_db {
299 unless (-d $ENV{GIT_DIR}) {
300 my @init_db = ('init');
301 push @init_db, "--template=$_template" if defined $_template;
302 if (defined $_shared) {
303 if ($_shared =~ /[a-z]/) {
304 push @init_db, "--shared=$_shared";
305 } else {
306 push @init_db, "--shared";
309 command_noisy(@init_db);
310 $_repository = Git->repository(Repository => ".git");
312 my $set;
313 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
314 foreach my $i (keys %icv) {
315 die "'$set' and '$i' cannot both be set\n" if $set;
316 next unless defined $icv{$i};
317 command_noisy('config', "$pfx.$i", $icv{$i});
318 $set = $i;
322 sub init_subdir {
323 my $repo_path = shift or return;
324 mkpath([$repo_path]) unless -d $repo_path;
325 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
326 $ENV{GIT_DIR} = '.git';
327 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
330 sub cmd_clone {
331 my ($url, $path) = @_;
332 if (!defined $path &&
333 (defined $_trunk || defined $_branches || defined $_tags ||
334 defined $_stdlayout) &&
335 $url !~ m#^[a-z\+]+://#) {
336 $path = $url;
338 $path = basename($url) if !defined $path || !length $path;
339 cmd_init($url, $path);
340 Git::SVN::fetch_all($Git::SVN::default_repo_id);
343 sub cmd_init {
344 if (defined $_stdlayout) {
345 $_trunk = 'trunk' if (!defined $_trunk);
346 $_tags = 'tags' if (!defined $_tags);
347 $_branches = 'branches' if (!defined $_branches);
349 if (defined $_trunk || defined $_branches || defined $_tags) {
350 return cmd_multi_init(@_);
352 my $url = shift or die "SVN repository location required ",
353 "as a command-line argument\n";
354 init_subdir(@_);
355 do_git_init_db();
357 Git::SVN->init($url);
360 sub cmd_fetch {
361 if (grep /^\d+=./, @_) {
362 die "'<rev>=<commit>' fetch arguments are ",
363 "no longer supported.\n";
365 my ($remote) = @_;
366 if (@_ > 1) {
367 die "Usage: $0 fetch [--all] [svn-remote]\n";
369 $remote ||= $Git::SVN::default_repo_id;
370 if ($_fetch_all) {
371 cmd_multi_fetch();
372 } else {
373 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
377 sub cmd_set_tree {
378 my (@commits) = @_;
379 if ($_stdin || !@commits) {
380 print "Reading from stdin...\n";
381 @commits = ();
382 while (<STDIN>) {
383 if (/\b($sha1_short)\b/o) {
384 unshift @commits, $1;
388 my @revs;
389 foreach my $c (@commits) {
390 my @tmp = command('rev-parse',$c);
391 if (scalar @tmp == 1) {
392 push @revs, $tmp[0];
393 } elsif (scalar @tmp > 1) {
394 push @revs, reverse(command('rev-list',@tmp));
395 } else {
396 fatal "Failed to rev-parse $c";
399 my $gs = Git::SVN->new;
400 my ($r_last, $cmt_last) = $gs->last_rev_commit;
401 $gs->fetch;
402 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
403 fatal "There are new revisions that were fetched ",
404 "and need to be merged (or acknowledged) ",
405 "before committing.\nlast rev: $r_last\n",
406 " current: $gs->{last_rev}";
408 $gs->set_tree($_) foreach @revs;
409 print "Done committing ",scalar @revs," revisions to SVN\n";
410 unlink $gs->{index};
413 sub cmd_dcommit {
414 my $head = shift;
415 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
416 'Cannot dcommit with a dirty index. Commit your changes first, '
417 . "or stash them with `git stash'.\n";
418 $head ||= 'HEAD';
419 my @refs;
420 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
421 $url = $_commit_url if defined $_commit_url;
422 my $last_rev = $_revision if defined $_revision;
423 if ($url) {
424 print "Committing to $url ...\n";
426 unless ($gs) {
427 die "Unable to determine upstream SVN information from ",
428 "$head history.\nPerhaps the repository is empty.";
430 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
431 if ($_no_rebase && scalar(@$linear_refs) > 1) {
432 warn "Attempting to commit more than one change while ",
433 "--no-rebase is enabled.\n",
434 "If these changes depend on each other, re-running ",
435 "without --no-rebase may be required."
437 while (1) {
438 my $d = shift @$linear_refs or last;
439 unless (defined $last_rev) {
440 (undef, $last_rev, undef) = cmt_metadata("$d~1");
441 unless (defined $last_rev) {
442 fatal "Unable to extract revision information ",
443 "from commit $d~1";
446 if ($_dry_run) {
447 print "diff-tree $d~1 $d\n";
448 } else {
449 my $cmt_rev;
450 my %ed_opts = ( r => $last_rev,
451 log => get_commit_entry($d)->{log},
452 ra => Git::SVN::Ra->new($url),
453 config => SVN::Core::config_get_config(
454 $Git::SVN::Ra::config_dir
456 tree_a => "$d~1",
457 tree_b => $d,
458 editor_cb => sub {
459 print "Committed r$_[0]\n";
460 $cmt_rev = $_[0];
462 svn_path => '');
463 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
464 print "No changes\n$d~1 == $d\n";
465 } elsif ($parents->{$d} && @{$parents->{$d}}) {
466 $gs->{inject_parents_dcommit}->{$cmt_rev} =
467 $parents->{$d};
469 $_fetch_all ? $gs->fetch_all : $gs->fetch;
470 $last_rev = $cmt_rev;
471 next if $_no_rebase;
473 # we always want to rebase against the current HEAD,
474 # not any head that was passed to us
475 my @diff = command('diff-tree', $d,
476 $gs->refname, '--');
477 my @finish;
478 if (@diff) {
479 @finish = rebase_cmd();
480 print STDERR "W: $d and ", $gs->refname,
481 " differ, using @finish:\n",
482 join("\n", @diff), "\n";
483 } else {
484 print "No changes between current HEAD and ",
485 $gs->refname,
486 "\nResetting to the latest ",
487 $gs->refname, "\n";
488 @finish = qw/reset --mixed/;
490 command_noisy(@finish, $gs->refname);
491 if (@diff) {
492 @refs = ();
493 my ($url_, $rev_, $uuid_, $gs_) =
494 working_head_info($head, \@refs);
495 my ($linear_refs_, $parents_) =
496 linearize_history($gs_, \@refs);
497 if (scalar(@$linear_refs) !=
498 scalar(@$linear_refs_)) {
499 fatal "# of revisions changed ",
500 "\nbefore:\n",
501 join("\n", @$linear_refs),
502 "\n\nafter:\n",
503 join("\n", @$linear_refs_), "\n",
504 'If you are attempting to commit ',
505 "merges, try running:\n\t",
506 'git rebase --interactive',
507 '--preserve-merges ',
508 $gs->refname,
509 "\nBefore dcommitting";
511 if ($url_ ne $url) {
512 fatal "URL mismatch after rebase: ",
513 "$url_ != $url";
515 if ($uuid_ ne $uuid) {
516 fatal "uuid mismatch after rebase: ",
517 "$uuid_ != $uuid";
519 # remap parents
520 my (%p, @l, $i);
521 for ($i = 0; $i < scalar @$linear_refs; $i++) {
522 my $new = $linear_refs_->[$i] or next;
523 $p{$new} =
524 $parents->{$linear_refs->[$i]};
525 push @l, $new;
527 $parents = \%p;
528 $linear_refs = \@l;
532 unlink $gs->{index};
535 sub cmd_find_rev {
536 my $revision_or_hash = shift or die "SVN or git revision required ",
537 "as a command-line argument\n";
538 my $result;
539 if ($revision_or_hash =~ /^r\d+$/) {
540 my $head = shift;
541 $head ||= 'HEAD';
542 my @refs;
543 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
544 unless ($gs) {
545 die "Unable to determine upstream SVN information from ",
546 "$head history\n";
548 my $desired_revision = substr($revision_or_hash, 1);
549 $result = $gs->rev_map_get($desired_revision, $uuid);
550 } else {
551 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
552 $result = $rev;
554 print "$result\n" if $result;
557 sub cmd_rebase {
558 command_noisy(qw/update-index --refresh/);
559 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
560 unless ($gs) {
561 die "Unable to determine upstream SVN information from ",
562 "working tree history\n";
564 if ($_dry_run) {
565 print "Remote Branch: " . $gs->refname . "\n";
566 print "SVN URL: " . $url . "\n";
567 return;
569 if (command(qw/diff-index HEAD --/)) {
570 print STDERR "Cannot rebase with uncommited changes:\n";
571 command_noisy('status');
572 exit 1;
574 unless ($_local) {
575 # rebase will checkout for us, so no need to do it explicitly
576 $_no_checkout = 'true';
577 $_fetch_all ? $gs->fetch_all : $gs->fetch;
579 command_noisy(rebase_cmd(), $gs->refname);
582 sub cmd_show_ignore {
583 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
584 $gs ||= Git::SVN->new;
585 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
586 $gs->prop_walk($gs->{path}, $r, sub {
587 my ($gs, $path, $props) = @_;
588 print STDOUT "\n# $path\n";
589 my $s = $props->{'svn:ignore'} or return;
590 $s =~ s/[\r\n]+/\n/g;
591 chomp $s;
592 $s =~ s#^#$path#gm;
593 print STDOUT "$s\n";
597 sub cmd_show_externals {
598 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
599 $gs ||= Git::SVN->new;
600 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
601 $gs->prop_walk($gs->{path}, $r, sub {
602 my ($gs, $path, $props) = @_;
603 print STDOUT "\n# $path\n";
604 my $s = $props->{'svn:externals'} or return;
605 $s =~ s/[\r\n]+/\n/g;
606 chomp $s;
607 $s =~ s#^#$path#gm;
608 print STDOUT "$s\n";
612 sub cmd_create_ignore {
613 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
614 $gs ||= Git::SVN->new;
615 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
616 $gs->prop_walk($gs->{path}, $r, sub {
617 my ($gs, $path, $props) = @_;
618 # $path is of the form /path/to/dir/
619 my $ignore = '.' . $path . '.gitignore';
620 my $s = $props->{'svn:ignore'} or return;
621 open(GITIGNORE, '>', $ignore)
622 or fatal("Failed to open `$ignore' for writing: $!");
623 $s =~ s/[\r\n]+/\n/g;
624 chomp $s;
625 # Prefix all patterns so that the ignore doesn't apply
626 # to sub-directories.
627 $s =~ s#^#/#gm;
628 print GITIGNORE "$s\n";
629 close(GITIGNORE)
630 or fatal("Failed to close `$ignore': $!");
631 command_noisy('add', '-f', $ignore);
635 sub canonicalize_path {
636 my ($path) = @_;
637 my $dot_slash_added = 0;
638 if (substr($path, 0, 1) ne "/") {
639 $path = "./" . $path;
640 $dot_slash_added = 1;
642 # File::Spec->canonpath doesn't collapse x/../y into y (for a
643 # good reason), so let's do this manually.
644 $path =~ s#/+#/#g;
645 $path =~ s#/\.(?:/|$)#/#g;
646 $path =~ s#/[^/]+/\.\.##g;
647 $path =~ s#/$##g;
648 $path =~ s#^\./## if $dot_slash_added;
649 $path =~ s#^/##;
650 $path =~ s#^\.$##;
651 return $path;
654 # get_svnprops(PATH)
655 # ------------------
656 # Helper for cmd_propget and cmd_proplist below.
657 sub get_svnprops {
658 my $path = shift;
659 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
660 $gs ||= Git::SVN->new;
662 # prefix THE PATH by the sub-directory from which the user
663 # invoked us.
664 $path = $cmd_dir_prefix . $path;
665 fatal("No such file or directory: $path") unless -e $path;
666 my $is_dir = -d $path ? 1 : 0;
667 $path = $gs->{path} . '/' . $path;
669 # canonicalize the path (otherwise libsvn will abort or fail to
670 # find the file)
671 $path = canonicalize_path($path);
673 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
674 my $props;
675 if ($is_dir) {
676 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
678 else {
679 (undef, $props) = $gs->ra->get_file($path, $r, undef);
681 return $props;
684 # cmd_propget (PROP, PATH)
685 # ------------------------
686 # Print the SVN property PROP for PATH.
687 sub cmd_propget {
688 my ($prop, $path) = @_;
689 $path = '.' if not defined $path;
690 usage(1) if not defined $prop;
691 my $props = get_svnprops($path);
692 if (not defined $props->{$prop}) {
693 fatal("`$path' does not have a `$prop' SVN property.");
695 print $props->{$prop} . "\n";
698 # cmd_proplist (PATH)
699 # -------------------
700 # Print the list of SVN properties for PATH.
701 sub cmd_proplist {
702 my $path = shift;
703 $path = '.' if not defined $path;
704 my $props = get_svnprops($path);
705 print "Properties on '$path':\n";
706 foreach (sort keys %{$props}) {
707 print " $_\n";
711 sub cmd_multi_init {
712 my $url = shift;
713 unless (defined $_trunk || defined $_branches || defined $_tags) {
714 usage(1);
717 # there are currently some bugs that prevent multi-init/multi-fetch
718 # setups from working well without this.
719 $Git::SVN::_minimize_url = 1;
721 $_prefix = '' unless defined $_prefix;
722 if (defined $url) {
723 $url =~ s#/+$##;
724 init_subdir(@_);
726 do_git_init_db();
727 if (defined $_trunk) {
728 my $trunk_ref = $_prefix . 'trunk';
729 # try both old-style and new-style lookups:
730 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
731 unless ($gs_trunk) {
732 my ($trunk_url, $trunk_path) =
733 complete_svn_url($url, $_trunk);
734 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
735 undef, $trunk_ref);
738 return unless defined $_branches || defined $_tags;
739 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
740 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
741 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
744 sub cmd_multi_fetch {
745 my $remotes = Git::SVN::read_all_remotes();
746 foreach my $repo_id (sort keys %$remotes) {
747 if ($remotes->{$repo_id}->{url}) {
748 Git::SVN::fetch_all($repo_id, $remotes);
753 # this command is special because it requires no metadata
754 sub cmd_commit_diff {
755 my ($ta, $tb, $url) = @_;
756 my $usage = "Usage: $0 commit-diff -r<revision> ".
757 "<tree-ish> <tree-ish> [<URL>]";
758 fatal($usage) if (!defined $ta || !defined $tb);
759 my $svn_path = '';
760 if (!defined $url) {
761 my $gs = eval { Git::SVN->new };
762 if (!$gs) {
763 fatal("Needed URL or usable git-svn --id in ",
764 "the command-line\n", $usage);
766 $url = $gs->{url};
767 $svn_path = $gs->{path};
769 unless (defined $_revision) {
770 fatal("-r|--revision is a required argument\n", $usage);
772 if (defined $_message && defined $_file) {
773 fatal("Both --message/-m and --file/-F specified ",
774 "for the commit message.\n",
775 "I have no idea what you mean");
777 if (defined $_file) {
778 $_message = file_to_s($_file);
779 } else {
780 $_message ||= get_commit_entry($tb)->{log};
782 my $ra ||= Git::SVN::Ra->new($url);
783 my $r = $_revision;
784 if ($r eq 'HEAD') {
785 $r = $ra->get_latest_revnum;
786 } elsif ($r !~ /^\d+$/) {
787 die "revision argument: $r not understood by git-svn\n";
789 my %ed_opts = ( r => $r,
790 log => $_message,
791 ra => $ra,
792 tree_a => $ta,
793 tree_b => $tb,
794 editor_cb => sub { print "Committed r$_[0]\n" },
795 svn_path => $svn_path );
796 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
797 print "No changes\n$ta == $tb\n";
801 sub cmd_info {
802 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
803 if (exists $_[1]) {
804 die "Too many arguments specified\n";
807 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
809 if (!$file_type && !$diff_status) {
810 print STDERR "$path: (Not a versioned resource)\n\n";
811 return;
814 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
815 unless ($gs) {
816 die "Unable to determine upstream SVN information from ",
817 "working tree history\n";
820 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
821 $path = "." if $path eq "";
823 my $full_url = $url . ($path eq "." ? "" : "/$path");
825 if ($_url) {
826 print $full_url, "\n";
827 return;
830 my $result = "Path: $path\n";
831 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
832 $result .= "URL: " . $full_url . "\n";
834 eval {
835 my $repos_root = $gs->repos_root;
836 Git::SVN::remove_username($repos_root);
837 $result .= "Repository Root: $repos_root\n";
839 if ($@) {
840 $result .= "Repository Root: (offline)\n";
842 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
843 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
845 $result .= "Node Kind: " .
846 ($file_type eq "dir" ? "directory" : "file") . "\n";
848 my $schedule = $diff_status eq "A"
849 ? "add"
850 : ($diff_status eq "D" ? "delete" : "normal");
851 $result .= "Schedule: $schedule\n";
853 if ($diff_status eq "A") {
854 print $result, "\n";
855 return;
858 my ($lc_author, $lc_rev, $lc_date_utc);
859 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
860 my $log = command_output_pipe(@args);
861 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
862 while (<$log>) {
863 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
864 $lc_author = $1;
865 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
866 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
867 (undef, $lc_rev, undef) = ::extract_metadata($1);
870 close $log;
872 Git::SVN::Log::set_local_timezone();
874 $result .= "Last Changed Author: $lc_author\n";
875 $result .= "Last Changed Rev: $lc_rev\n";
876 $result .= "Last Changed Date: " .
877 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
879 if ($file_type ne "dir") {
880 my $text_last_updated_date =
881 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
882 $result .=
883 "Text Last Updated: " .
884 Git::SVN::Log::format_svn_date($text_last_updated_date) .
885 "\n";
886 my $checksum;
887 if ($diff_status eq "D") {
888 my ($fh, $ctx) =
889 command_output_pipe(qw(cat-file blob), "HEAD:$path");
890 if ($file_type eq "link") {
891 my $file_name = <$fh>;
892 $checksum = md5sum("link $file_name");
893 } else {
894 $checksum = md5sum($fh);
896 command_close_pipe($fh, $ctx);
897 } elsif ($file_type eq "link") {
898 my $file_name =
899 command(qw(cat-file blob), "HEAD:$path");
900 $checksum =
901 md5sum("link " . $file_name);
902 } else {
903 open FILE, "<", $path or die $!;
904 $checksum = md5sum(\*FILE);
905 close FILE or die $!;
907 $result .= "Checksum: " . $checksum . "\n";
910 print $result, "\n";
913 ########################### utility functions #########################
915 sub rebase_cmd {
916 my @cmd = qw/rebase/;
917 push @cmd, '-v' if $_verbose;
918 push @cmd, qw/--merge/ if $_merge;
919 push @cmd, "--strategy=$_strategy" if $_strategy;
920 @cmd;
923 sub post_fetch_checkout {
924 return if $_no_checkout;
925 my $gs = $Git::SVN::_head or return;
926 return if verify_ref('refs/heads/master^0');
928 my $valid_head = verify_ref('HEAD^0');
929 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
930 return if ($valid_head || !verify_ref('HEAD^0'));
932 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
933 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
934 return if -f $index;
936 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
937 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
938 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
939 print STDERR "Checked out HEAD:\n ",
940 $gs->full_url, " r", $gs->last_rev, "\n";
943 sub complete_svn_url {
944 my ($url, $path) = @_;
945 $path =~ s#/+$##;
946 if ($path !~ m#^[a-z\+]+://#) {
947 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
948 fatal("E: '$path' is not a complete URL ",
949 "and a separate URL is not specified");
951 return ($url, $path);
953 return ($path, '');
956 sub complete_url_ls_init {
957 my ($ra, $repo_path, $switch, $pfx) = @_;
958 unless ($repo_path) {
959 print STDERR "W: $switch not specified\n";
960 return;
962 $repo_path =~ s#/+$##;
963 if ($repo_path =~ m#^[a-z\+]+://#) {
964 $ra = Git::SVN::Ra->new($repo_path);
965 $repo_path = '';
966 } else {
967 $repo_path =~ s#^/+##;
968 unless ($ra) {
969 fatal("E: '$repo_path' is not a complete URL ",
970 "and a separate URL is not specified");
973 my $url = $ra->{url};
974 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
975 my $k = "svn-remote.$gs->{repo_id}.url";
976 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
977 if ($orig_url && ($orig_url ne $gs->{url})) {
978 die "$k already set: $orig_url\n",
979 "wanted to set to: $gs->{url}\n";
981 command_oneline('config', $k, $gs->{url}) unless $orig_url;
982 my $remote_path = "$ra->{svn_path}/$repo_path";
983 $remote_path =~ s#/+#/#g;
984 $remote_path =~ s#^/##g;
985 $remote_path .= "/*" if $remote_path !~ /\*/;
986 my ($n) = ($switch =~ /^--(\w+)/);
987 if (length $pfx && $pfx !~ m#/$#) {
988 die "--prefix='$pfx' must have a trailing slash '/'\n";
990 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
991 "$remote_path:refs/remotes/$pfx*");
994 sub verify_ref {
995 my ($ref) = @_;
996 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
997 { STDERR => 0 }); };
1000 sub get_tree_from_treeish {
1001 my ($treeish) = @_;
1002 # $treeish can be a symbolic ref, too:
1003 my $type = command_oneline(qw/cat-file -t/, $treeish);
1004 my $expected;
1005 while ($type eq 'tag') {
1006 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1008 if ($type eq 'commit') {
1009 $expected = (grep /^tree /, command(qw/cat-file commit/,
1010 $treeish))[0];
1011 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1012 die "Unable to get tree from $treeish\n" unless $expected;
1013 } elsif ($type eq 'tree') {
1014 $expected = $treeish;
1015 } else {
1016 die "$treeish is a $type, expected tree, tag or commit\n";
1018 return $expected;
1021 sub get_commit_entry {
1022 my ($treeish) = shift;
1023 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1024 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1025 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1026 open my $log_fh, '>', $commit_editmsg or croak $!;
1028 my $type = command_oneline(qw/cat-file -t/, $treeish);
1029 if ($type eq 'commit' || $type eq 'tag') {
1030 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1031 $type, $treeish);
1032 my $in_msg = 0;
1033 my $author;
1034 my $saw_from = 0;
1035 my $msgbuf = "";
1036 while (<$msg_fh>) {
1037 if (!$in_msg) {
1038 $in_msg = 1 if (/^\s*$/);
1039 $author = $1 if (/^author (.*>)/);
1040 } elsif (/^git-svn-id: /) {
1041 # skip this for now, we regenerate the
1042 # correct one on re-fetch anyways
1043 # TODO: set *:merge properties or like...
1044 } else {
1045 if (/^From:/ || /^Signed-off-by:/) {
1046 $saw_from = 1;
1048 $msgbuf .= $_;
1051 $msgbuf =~ s/\s+$//s;
1052 if ($Git::SVN::_add_author_from && defined($author)
1053 && !$saw_from) {
1054 $msgbuf .= "\n\nFrom: $author";
1056 print $log_fh $msgbuf or croak $!;
1057 command_close_pipe($msg_fh, $ctx);
1059 close $log_fh or croak $!;
1061 if ($_edit || ($type eq 'tree')) {
1062 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1063 # TODO: strip out spaces, comments, like git-commit.sh
1064 system($editor, $commit_editmsg);
1066 rename $commit_editmsg, $commit_msg or croak $!;
1067 open $log_fh, '<', $commit_msg or croak $!;
1068 { local $/; chomp($log_entry{log} = <$log_fh>); }
1069 close $log_fh or croak $!;
1070 unlink $commit_msg;
1071 \%log_entry;
1074 sub s_to_file {
1075 my ($str, $file, $mode) = @_;
1076 open my $fd,'>',$file or croak $!;
1077 print $fd $str,"\n" or croak $!;
1078 close $fd or croak $!;
1079 chmod ($mode &~ umask, $file) if (defined $mode);
1082 sub file_to_s {
1083 my $file = shift;
1084 open my $fd,'<',$file or croak "$!: file: $file\n";
1085 local $/;
1086 my $ret = <$fd>;
1087 close $fd or croak $!;
1088 $ret =~ s/\s*$//s;
1089 return $ret;
1092 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1093 sub load_authors {
1094 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1095 my $log = $cmd eq 'log';
1096 while (<$authors>) {
1097 chomp;
1098 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1099 my ($user, $name, $email) = ($1, $2, $3);
1100 if ($log) {
1101 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1102 } else {
1103 $users{$user} = [$name, $email];
1106 close $authors or croak $!;
1109 # convert GetOpt::Long specs for use by git-config
1110 sub read_repo_config {
1111 return unless -d $ENV{GIT_DIR};
1112 my $opts = shift;
1113 my @config_only;
1114 foreach my $o (keys %$opts) {
1115 # if we have mixedCase and a long option-only, then
1116 # it's a config-only variable that we don't need for
1117 # the command-line.
1118 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1119 my $v = $opts->{$o};
1120 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1121 $key =~ s/-//g;
1122 my $arg = 'git-config';
1123 $arg .= ' --int' if ($o =~ /[:=]i$/);
1124 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1125 if (ref $v eq 'ARRAY') {
1126 chomp(my @tmp = `$arg --get-all svn.$key`);
1127 @$v = @tmp if @tmp;
1128 } else {
1129 chomp(my $tmp = `$arg --get svn.$key`);
1130 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1131 $$v = $tmp;
1135 delete @$opts{@config_only} if @config_only;
1138 sub extract_metadata {
1139 my $id = shift or return (undef, undef, undef);
1140 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1141 \s([a-f\d\-]+)$/x);
1142 if (!defined $rev || !$uuid || !$url) {
1143 # some of the original repositories I made had
1144 # identifiers like this:
1145 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1147 return ($url, $rev, $uuid);
1150 sub cmt_metadata {
1151 return extract_metadata((grep(/^git-svn-id: /,
1152 command(qw/cat-file commit/, shift)))[-1]);
1155 sub working_head_info {
1156 my ($head, $refs) = @_;
1157 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1158 my ($fh, $ctx) = command_output_pipe(@args, $head);
1159 my $hash;
1160 my %max;
1161 while (<$fh>) {
1162 if ( m{^commit ($::sha1)$} ) {
1163 unshift @$refs, $hash if $hash and $refs;
1164 $hash = $1;
1165 next;
1167 next unless s{^\s*(git-svn-id:)}{$1};
1168 my ($url, $rev, $uuid) = extract_metadata($_);
1169 if (defined $url && defined $rev) {
1170 next if $max{$url} and $max{$url} < $rev;
1171 if (my $gs = Git::SVN->find_by_url($url)) {
1172 my $c = $gs->rev_map_get($rev, $uuid);
1173 if ($c && $c eq $hash) {
1174 close $fh; # break the pipe
1175 return ($url, $rev, $uuid, $gs);
1176 } else {
1177 $max{$url} ||= $gs->rev_map_max;
1182 command_close_pipe($fh, $ctx);
1183 (undef, undef, undef, undef);
1186 sub read_commit_parents {
1187 my ($parents, $c) = @_;
1188 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1189 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1190 @{$parents->{$c}} = split(/ /, $p);
1193 sub linearize_history {
1194 my ($gs, $refs) = @_;
1195 my %parents;
1196 foreach my $c (@$refs) {
1197 read_commit_parents(\%parents, $c);
1200 my @linear_refs;
1201 my %skip = ();
1202 my $last_svn_commit = $gs->last_commit;
1203 foreach my $c (reverse @$refs) {
1204 next if $c eq $last_svn_commit;
1205 last if $skip{$c};
1207 unshift @linear_refs, $c;
1208 $skip{$c} = 1;
1210 # we only want the first parent to diff against for linear
1211 # history, we save the rest to inject when we finalize the
1212 # svn commit
1213 my $fp_a = verify_ref("$c~1");
1214 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1215 if (!$fp_a || !$fp_b) {
1216 die "Commit $c\n",
1217 "has no parent commit, and therefore ",
1218 "nothing to diff against.\n",
1219 "You should be working from a repository ",
1220 "originally created by git-svn\n";
1222 if ($fp_a ne $fp_b) {
1223 die "$c~1 = $fp_a, however parsing commit $c ",
1224 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1227 foreach my $p (@{$parents{$c}}) {
1228 $skip{$p} = 1;
1231 (\@linear_refs, \%parents);
1234 sub find_file_type_and_diff_status {
1235 my ($path) = @_;
1236 return ('dir', '') if $path eq '';
1238 my $diff_output =
1239 command_oneline(qw(diff --cached --name-status --), $path) || "";
1240 my $diff_status = (split(' ', $diff_output))[0] || "";
1242 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1244 return (undef, undef) if !$diff_status && !$ls_tree;
1246 if ($diff_status eq "A") {
1247 return ("link", $diff_status) if -l $path;
1248 return ("dir", $diff_status) if -d $path;
1249 return ("file", $diff_status);
1252 my $mode = (split(' ', $ls_tree))[0] || "";
1254 return ("link", $diff_status) if $mode eq "120000";
1255 return ("dir", $diff_status) if $mode eq "040000";
1256 return ("file", $diff_status);
1259 sub md5sum {
1260 my $arg = shift;
1261 my $ref = ref $arg;
1262 my $md5 = Digest::MD5->new();
1263 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1264 $md5->addfile($arg) or croak $!;
1265 } elsif ($ref eq 'SCALAR') {
1266 $md5->add($$arg) or croak $!;
1267 } elsif (!$ref) {
1268 $md5->add($arg) or croak $!;
1269 } else {
1270 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1272 return $md5->hexdigest();
1275 package Git::SVN;
1276 use strict;
1277 use warnings;
1278 use Fcntl qw/:DEFAULT :seek/;
1279 use constant rev_map_fmt => 'NH40';
1280 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1281 $_repack $_repack_flags $_use_svm_props $_head
1282 $_use_svnsync_props $no_reuse_existing $_minimize_url
1283 $_use_log_author $_add_author_from/;
1284 use Carp qw/croak/;
1285 use File::Path qw/mkpath/;
1286 use File::Copy qw/copy/;
1287 use IPC::Open3;
1289 my ($_gc_nr, $_gc_period);
1291 # properties that we do not log:
1292 my %SKIP_PROP;
1293 BEGIN {
1294 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1295 svn:special svn:executable
1296 svn:entry:committed-rev
1297 svn:entry:last-author
1298 svn:entry:uuid
1299 svn:entry:committed-date/;
1301 # some options are read globally, but can be overridden locally
1302 # per [svn-remote "..."] section. Command-line options will *NOT*
1303 # override options set in an [svn-remote "..."] section
1304 no strict 'refs';
1305 for my $option (qw/follow_parent no_metadata use_svm_props
1306 use_svnsync_props/) {
1307 my $key = $option;
1308 $key =~ tr/_//d;
1309 my $prop = "-$option";
1310 *$option = sub {
1311 my ($self) = @_;
1312 return $self->{$prop} if exists $self->{$prop};
1313 my $k = "svn-remote.$self->{repo_id}.$key";
1314 eval { command_oneline(qw/config --get/, $k) };
1315 if ($@) {
1316 $self->{$prop} = ${"Git::SVN::_$option"};
1317 } else {
1318 my $v = command_oneline(qw/config --bool/,$k);
1319 $self->{$prop} = $v eq 'false' ? 0 : 1;
1321 return $self->{$prop};
1326 my (%LOCKFILES, %INDEX_FILES);
1327 END {
1328 unlink keys %LOCKFILES if %LOCKFILES;
1329 unlink keys %INDEX_FILES if %INDEX_FILES;
1332 sub resolve_local_globs {
1333 my ($url, $fetch, $glob_spec) = @_;
1334 return unless defined $glob_spec;
1335 my $ref = $glob_spec->{ref};
1336 my $path = $glob_spec->{path};
1337 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1338 next unless m#^refs/remotes/$ref->{regex}$#;
1339 my $p = $1;
1340 my $pathname = desanitize_refname($path->full_path($p));
1341 my $refname = desanitize_refname($ref->full_path($p));
1342 if (my $existing = $fetch->{$pathname}) {
1343 if ($existing ne $refname) {
1344 die "Refspec conflict:\n",
1345 "existing: refs/remotes/$existing\n",
1346 " globbed: refs/remotes/$refname\n";
1348 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1349 $u =~ s!^\Q$url\E(/|$)!! or die
1350 "refs/remotes/$refname: '$url' not found in '$u'\n";
1351 if ($pathname ne $u) {
1352 warn "W: Refspec glob conflict ",
1353 "(ref: refs/remotes/$refname):\n",
1354 "expected path: $pathname\n",
1355 " real path: $u\n",
1356 "Continuing ahead with $u\n";
1357 next;
1359 } else {
1360 $fetch->{$pathname} = $refname;
1365 sub parse_revision_argument {
1366 my ($base, $head) = @_;
1367 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1368 return ($base, $head);
1370 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1371 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1372 return ($head, $head) if ($::_revision eq 'HEAD');
1373 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1374 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1375 die "revision argument: $::_revision not understood by git-svn\n";
1378 sub fetch_all {
1379 my ($repo_id, $remotes) = @_;
1380 if (ref $repo_id) {
1381 my $gs = $repo_id;
1382 $repo_id = undef;
1383 $repo_id = $gs->{repo_id};
1385 $remotes ||= read_all_remotes();
1386 my $remote = $remotes->{$repo_id} or
1387 die "[svn-remote \"$repo_id\"] unknown\n";
1388 my $fetch = $remote->{fetch};
1389 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1390 my (@gs, @globs);
1391 my $ra = Git::SVN::Ra->new($url);
1392 my $uuid = $ra->get_uuid;
1393 my $head = $ra->get_latest_revnum;
1394 my $base = defined $fetch ? $head : 0;
1396 # read the max revs for wildcard expansion (branches/*, tags/*)
1397 foreach my $t (qw/branches tags/) {
1398 defined $remote->{$t} or next;
1399 push @globs, $remote->{$t};
1400 my $max_rev = eval { tmp_config(qw/--int --get/,
1401 "svn-remote.$repo_id.${t}-maxRev") };
1402 if (defined $max_rev && ($max_rev < $base)) {
1403 $base = $max_rev;
1404 } elsif (!defined $max_rev) {
1405 $base = 0;
1409 if ($fetch) {
1410 foreach my $p (sort keys %$fetch) {
1411 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1412 my $lr = $gs->rev_map_max;
1413 if (defined $lr) {
1414 $base = $lr if ($lr < $base);
1416 push @gs, $gs;
1420 ($base, $head) = parse_revision_argument($base, $head);
1421 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1424 sub read_all_remotes {
1425 my $r = {};
1426 my $use_svm_props = eval { command_oneline(qw/config --bool
1427 svn.useSvmProps/) };
1428 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1429 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1430 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1431 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1432 die("svn-remote.$remote: remote ref '$_remote_ref' "
1433 . "must start with 'refs/remotes/'\n")
1434 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1435 my $remote_ref = $1;
1436 $local_ref =~ s{^/}{};
1437 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1438 $r->{$remote}->{svm} = {} if $use_svm_props;
1439 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1440 $r->{$1}->{svm} = {};
1441 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1442 $r->{$1}->{url} = $2;
1443 } elsif (m!^(.+)\.(branches|tags)=
1444 (.*):refs/remotes/(.+)\s*$/!x) {
1445 my ($p, $g) = ($3, $4);
1446 my $rs = $r->{$1}->{$2} = {
1447 t => $2,
1448 remote => $1,
1449 path => Git::SVN::GlobSpec->new($p),
1450 ref => Git::SVN::GlobSpec->new($g) };
1451 if (length($rs->{ref}->{right}) != 0) {
1452 die "The '*' glob character must be the last ",
1453 "character of '$g'\n";
1458 map {
1459 if (defined $r->{$_}->{svm}) {
1460 my $svm;
1461 eval {
1462 my $section = "svn-remote.$_";
1463 $svm = {
1464 source => tmp_config('--get',
1465 "$section.svm-source"),
1466 replace => tmp_config('--get',
1467 "$section.svm-replace"),
1470 $r->{$_}->{svm} = $svm;
1472 } keys %$r;
1477 sub init_vars {
1478 $_gc_nr = $_gc_period = 1000;
1479 if (defined $_repack || defined $_repack_flags) {
1480 warn "Repack options are obsolete; they have no effect.\n";
1484 sub verify_remotes_sanity {
1485 return unless -d $ENV{GIT_DIR};
1486 my %seen;
1487 foreach (command(qw/config -l/)) {
1488 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1489 if ($seen{$1}) {
1490 die "Remote ref refs/remote/$1 is tracked by",
1491 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1492 "Please resolve this ambiguity in ",
1493 "your git configuration file before ",
1494 "continuing\n";
1496 $seen{$1} = $_;
1501 sub find_existing_remote {
1502 my ($url, $remotes) = @_;
1503 return undef if $no_reuse_existing;
1504 my $existing;
1505 foreach my $repo_id (keys %$remotes) {
1506 my $u = $remotes->{$repo_id}->{url} or next;
1507 next if $u ne $url;
1508 $existing = $repo_id;
1509 last;
1511 $existing;
1514 sub init_remote_config {
1515 my ($self, $url, $no_write) = @_;
1516 $url =~ s!/+$!!; # strip trailing slash
1517 my $r = read_all_remotes();
1518 my $existing = find_existing_remote($url, $r);
1519 if ($existing) {
1520 unless ($no_write) {
1521 print STDERR "Using existing ",
1522 "[svn-remote \"$existing\"]\n";
1524 $self->{repo_id} = $existing;
1525 } elsif ($_minimize_url) {
1526 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1527 $existing = find_existing_remote($min_url, $r);
1528 if ($existing) {
1529 unless ($no_write) {
1530 print STDERR "Using existing ",
1531 "[svn-remote \"$existing\"]\n";
1533 $self->{repo_id} = $existing;
1535 if ($min_url ne $url) {
1536 unless ($no_write) {
1537 print STDERR "Using higher level of URL: ",
1538 "$url => $min_url\n";
1540 my $old_path = $self->{path};
1541 $self->{path} = $url;
1542 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1543 if (length $old_path) {
1544 $self->{path} .= "/$old_path";
1546 $url = $min_url;
1549 my $orig_url;
1550 if (!$existing) {
1551 # verify that we aren't overwriting anything:
1552 $orig_url = eval {
1553 command_oneline('config', '--get',
1554 "svn-remote.$self->{repo_id}.url")
1556 if ($orig_url && ($orig_url ne $url)) {
1557 die "svn-remote.$self->{repo_id}.url already set: ",
1558 "$orig_url\nwanted to set to: $url\n";
1561 my ($xrepo_id, $xpath) = find_ref($self->refname);
1562 if (defined $xpath) {
1563 die "svn-remote.$xrepo_id.fetch already set to track ",
1564 "$xpath:refs/remotes/", $self->refname, "\n";
1566 unless ($no_write) {
1567 command_noisy('config',
1568 "svn-remote.$self->{repo_id}.url", $url);
1569 $self->{path} =~ s{^/}{};
1570 command_noisy('config', '--add',
1571 "svn-remote.$self->{repo_id}.fetch",
1572 "$self->{path}:".$self->refname);
1574 $self->{url} = $url;
1577 sub find_by_url { # repos_root and, path are optional
1578 my ($class, $full_url, $repos_root, $path) = @_;
1580 return undef unless defined $full_url;
1581 remove_username($full_url);
1582 remove_username($repos_root) if defined $repos_root;
1583 my $remotes = read_all_remotes();
1584 if (defined $full_url && defined $repos_root && !defined $path) {
1585 $path = $full_url;
1586 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1588 foreach my $repo_id (keys %$remotes) {
1589 my $u = $remotes->{$repo_id}->{url} or next;
1590 remove_username($u);
1591 next if defined $repos_root && $repos_root ne $u;
1593 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1594 foreach (qw/branches tags/) {
1595 resolve_local_globs($u, $fetch,
1596 $remotes->{$repo_id}->{$_});
1598 my $p = $path;
1599 my $rwr = rewrite_root({repo_id => $repo_id});
1600 my $svm = $remotes->{$repo_id}->{svm}
1601 if defined $remotes->{$repo_id}->{svm};
1602 unless (defined $p) {
1603 $p = $full_url;
1604 my $z = $u;
1605 my $prefix = '';
1606 if ($rwr) {
1607 $z = $rwr;
1608 } elsif (defined $svm) {
1609 $z = $svm->{source};
1610 $prefix = $svm->{replace};
1611 $prefix =~ s#^\Q$u\E(?:/|$)##;
1612 $prefix =~ s#/$##;
1614 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1616 foreach my $f (keys %$fetch) {
1617 next if $f ne $p;
1618 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1621 undef;
1624 sub init {
1625 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1626 my $self = _new($class, $repo_id, $ref_id, $path);
1627 if (defined $url) {
1628 $self->init_remote_config($url, $no_write);
1630 $self;
1633 sub find_ref {
1634 my ($ref_id) = @_;
1635 foreach (command(qw/config -l/)) {
1636 next unless m!^svn-remote\.(.+)\.fetch=
1637 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1638 my ($repo_id, $path, $ref) = ($1, $2, $3);
1639 if ($ref eq $ref_id) {
1640 $path = '' if ($path =~ m#^\./?#);
1641 return ($repo_id, $path);
1644 (undef, undef, undef);
1647 sub new {
1648 my ($class, $ref_id, $repo_id, $path) = @_;
1649 if (defined $ref_id && !defined $repo_id && !defined $path) {
1650 ($repo_id, $path) = find_ref($ref_id);
1651 if (!defined $repo_id) {
1652 die "Could not find a \"svn-remote.*.fetch\" key ",
1653 "in the repository configuration matching: ",
1654 "refs/remotes/$ref_id\n";
1657 my $self = _new($class, $repo_id, $ref_id, $path);
1658 if (!defined $self->{path} || !length $self->{path}) {
1659 my $fetch = command_oneline('config', '--get',
1660 "svn-remote.$repo_id.fetch",
1661 ":refs/remotes/$ref_id\$") or
1662 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1663 "\":refs/remotes/$ref_id\$\" in config\n";
1664 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1666 $self->{url} = command_oneline('config', '--get',
1667 "svn-remote.$repo_id.url") or
1668 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1669 $self->rebuild;
1670 $self;
1673 sub refname {
1674 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1676 # It cannot end with a slash /, we'll throw up on this because
1677 # SVN can't have directories with a slash in their name, either:
1678 if ($refname =~ m{/$}) {
1679 die "ref: '$refname' ends with a trailing slash, this is ",
1680 "not permitted by git nor Subversion\n";
1683 # It cannot have ASCII control character space, tilde ~, caret ^,
1684 # colon :, question-mark ?, asterisk *, space, or open bracket [
1685 # anywhere.
1687 # Additionally, % must be escaped because it is used for escaping
1688 # and we want our escaped refname to be reversible
1689 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1691 # no slash-separated component can begin with a dot .
1692 # /.* becomes /%2E*
1693 $refname =~ s{/\.}{/%2E}g;
1695 # It cannot have two consecutive dots .. anywhere
1696 # .. becomes %2E%2E
1697 $refname =~ s{\.\.}{%2E%2E}g;
1699 return $refname;
1702 sub desanitize_refname {
1703 my ($refname) = @_;
1704 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1705 return $refname;
1708 sub svm_uuid {
1709 my ($self) = @_;
1710 return $self->{svm}->{uuid} if $self->svm;
1711 $self->ra;
1712 unless ($self->{svm}) {
1713 die "SVM UUID not cached, and reading remotely failed\n";
1715 $self->{svm}->{uuid};
1718 sub svm {
1719 my ($self) = @_;
1720 return $self->{svm} if $self->{svm};
1721 my $svm;
1722 # see if we have it in our config, first:
1723 eval {
1724 my $section = "svn-remote.$self->{repo_id}";
1725 $svm = {
1726 source => tmp_config('--get', "$section.svm-source"),
1727 uuid => tmp_config('--get', "$section.svm-uuid"),
1728 replace => tmp_config('--get', "$section.svm-replace"),
1731 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1732 $self->{svm} = $svm;
1734 $self->{svm};
1737 sub _set_svm_vars {
1738 my ($self, $ra) = @_;
1739 return $ra if $self->svm;
1741 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1742 "(svm:source, svm:uuid) ",
1743 "from the following URLs:\n" );
1744 sub read_svm_props {
1745 my ($self, $ra, $path, $r) = @_;
1746 my $props = ($ra->get_dir($path, $r))[2];
1747 my $src = $props->{'svm:source'};
1748 my $uuid = $props->{'svm:uuid'};
1749 return undef if (!$src || !$uuid);
1751 chomp($src, $uuid);
1753 $uuid =~ m{^[0-9a-f\-]{30,}$}
1754 or die "doesn't look right - svm:uuid is '$uuid'\n";
1756 # the '!' is used to mark the repos_root!/relative/path
1757 $src =~ s{/?!/?}{/};
1758 $src =~ s{/+$}{}; # no trailing slashes please
1759 # username is of no interest
1760 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1762 my $replace = $ra->{url};
1763 $replace .= "/$path" if length $path;
1765 my $section = "svn-remote.$self->{repo_id}";
1766 tmp_config("$section.svm-source", $src);
1767 tmp_config("$section.svm-replace", $replace);
1768 tmp_config("$section.svm-uuid", $uuid);
1769 $self->{svm} = {
1770 source => $src,
1771 uuid => $uuid,
1772 replace => $replace
1776 my $r = $ra->get_latest_revnum;
1777 my $path = $self->{path};
1778 my %tried;
1779 while (length $path) {
1780 unless ($tried{"$self->{url}/$path"}) {
1781 return $ra if $self->read_svm_props($ra, $path, $r);
1782 $tried{"$self->{url}/$path"} = 1;
1784 $path =~ s#/?[^/]+$##;
1786 die "Path: '$path' should be ''\n" if $path ne '';
1787 return $ra if $self->read_svm_props($ra, $path, $r);
1788 $tried{"$self->{url}/$path"} = 1;
1790 if ($ra->{repos_root} eq $self->{url}) {
1791 die @err, (map { " $_\n" } keys %tried), "\n";
1794 # nope, make sure we're connected to the repository root:
1795 my $ok;
1796 my @tried_b;
1797 $path = $ra->{svn_path};
1798 $ra = Git::SVN::Ra->new($ra->{repos_root});
1799 while (length $path) {
1800 unless ($tried{"$ra->{url}/$path"}) {
1801 $ok = $self->read_svm_props($ra, $path, $r);
1802 last if $ok;
1803 $tried{"$ra->{url}/$path"} = 1;
1805 $path =~ s#/?[^/]+$##;
1807 die "Path: '$path' should be ''\n" if $path ne '';
1808 $ok ||= $self->read_svm_props($ra, $path, $r);
1809 $tried{"$ra->{url}/$path"} = 1;
1810 if (!$ok) {
1811 die @err, (map { " $_\n" } keys %tried), "\n";
1813 Git::SVN::Ra->new($self->{url});
1816 sub svnsync {
1817 my ($self) = @_;
1818 return $self->{svnsync} if $self->{svnsync};
1820 if ($self->no_metadata) {
1821 die "Can't have both 'noMetadata' and ",
1822 "'useSvnsyncProps' options set!\n";
1824 if ($self->rewrite_root) {
1825 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1826 "options set!\n";
1829 my $svnsync;
1830 # see if we have it in our config, first:
1831 eval {
1832 my $section = "svn-remote.$self->{repo_id}";
1834 my $url = tmp_config('--get', "$section.svnsync-url");
1835 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1836 die "doesn't look right - svn:sync-from-url is '$url'\n";
1838 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1839 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1840 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1842 $svnsync = { url => $url, uuid => $uuid }
1844 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1845 return $self->{svnsync} = $svnsync;
1848 my $err = "useSvnsyncProps set, but failed to read " .
1849 "svnsync property: svn:sync-from-";
1850 my $rp = $self->ra->rev_proplist(0);
1852 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1853 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1854 die "doesn't look right - svn:sync-from-url is '$url'\n";
1856 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1857 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1858 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1860 my $section = "svn-remote.$self->{repo_id}";
1861 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1862 tmp_config('--add', "$section.svnsync-url", $url);
1863 return $self->{svnsync} = { url => $url, uuid => $uuid };
1866 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1867 # remote lookup (useful for 'git svn log').
1868 sub ra_uuid {
1869 my ($self) = @_;
1870 unless ($self->{ra_uuid}) {
1871 my $key = "svn-remote.$self->{repo_id}.uuid";
1872 my $uuid = eval { tmp_config('--get', $key) };
1873 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1874 $self->{ra_uuid} = $uuid;
1875 } else {
1876 die "ra_uuid called without URL\n" unless $self->{url};
1877 $self->{ra_uuid} = $self->ra->get_uuid;
1878 tmp_config('--add', $key, $self->{ra_uuid});
1881 $self->{ra_uuid};
1884 sub _set_repos_root {
1885 my ($self, $repos_root) = @_;
1886 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1887 $repos_root ||= $self->ra->{repos_root};
1888 tmp_config($k, $repos_root);
1889 $repos_root;
1892 sub repos_root {
1893 my ($self) = @_;
1894 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1895 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1898 sub ra {
1899 my ($self) = shift;
1900 my $ra = Git::SVN::Ra->new($self->{url});
1901 $self->_set_repos_root($ra->{repos_root});
1902 if ($self->use_svm_props && !$self->{svm}) {
1903 if ($self->no_metadata) {
1904 die "Can't have both 'noMetadata' and ",
1905 "'useSvmProps' options set!\n";
1906 } elsif ($self->use_svnsync_props) {
1907 die "Can't have both 'useSvnsyncProps' and ",
1908 "'useSvmProps' options set!\n";
1910 $ra = $self->_set_svm_vars($ra);
1911 $self->{-want_revprops} = 1;
1913 $ra;
1916 sub rel_path {
1917 my ($self) = @_;
1918 my $repos_root = $self->ra->{repos_root};
1919 return $self->{path} if ($self->{url} eq $repos_root);
1920 my $url = $self->{url} .
1921 (length $self->{path} ? "/$self->{path}" : $self->{path});
1922 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1923 $url;
1926 # prop_walk(PATH, REV, SUB)
1927 # -------------------------
1928 # Recursively traverse PATH at revision REV and invoke SUB for each
1929 # directory that contains a SVN property. SUB will be invoked as
1930 # follows: &SUB(gs, path, props); where `gs' is this instance of
1931 # Git::SVN, `path' the path to the directory where the properties
1932 # `props' were found. The `path' will be relative to point of checkout,
1933 # that is, if url://repo/trunk is the current Git branch, and that
1934 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1935 # as `path' (note the trailing `/').
1936 sub prop_walk {
1937 my ($self, $path, $rev, $sub) = @_;
1939 $path =~ s#^/##;
1940 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1941 $path =~ s#^/*#/#g;
1942 my $p = $path;
1943 # Strip the irrelevant part of the path.
1944 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1945 # Ensure the path is terminated by a `/'.
1946 $p =~ s#/*$#/#;
1948 # The properties contain all the internal SVN stuff nobody
1949 # (usually) cares about.
1950 my $interesting_props = 0;
1951 foreach (keys %{$props}) {
1952 # If it doesn't start with `svn:', it must be a
1953 # user-defined property.
1954 ++$interesting_props and next if $_ !~ /^svn:/;
1955 # FIXME: Fragile, if SVN adds new public properties,
1956 # this needs to be updated.
1957 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1958 |eol-style|mime-type
1959 |externals|needs-lock)$/x;
1961 &$sub($self, $p, $props) if $interesting_props;
1963 foreach (sort keys %$dirent) {
1964 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1965 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1969 sub last_rev { ($_[0]->last_rev_commit)[0] }
1970 sub last_commit { ($_[0]->last_rev_commit)[1] }
1972 # returns the newest SVN revision number and newest commit SHA1
1973 sub last_rev_commit {
1974 my ($self) = @_;
1975 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1976 return ($self->{last_rev}, $self->{last_commit});
1978 my $c = ::verify_ref($self->refname.'^0');
1979 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1980 my $rev = (::cmt_metadata($c))[1];
1981 if (defined $rev) {
1982 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1983 return ($rev, $c);
1986 my $map_path = $self->map_path;
1987 unless (-e $map_path) {
1988 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1989 return (undef, undef);
1991 my ($rev, $commit) = $self->rev_map_max(1);
1992 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1993 return ($rev, $commit);
1996 sub get_fetch_range {
1997 my ($self, $min, $max) = @_;
1998 $max ||= $self->ra->get_latest_revnum;
1999 $min ||= $self->rev_map_max;
2000 (++$min, $max);
2003 sub tmp_config {
2004 my (@args) = @_;
2005 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2006 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2007 if (! -f $config && -f $old_def_config) {
2008 rename $old_def_config, $config or
2009 die "Failed rename $old_def_config => $config: $!\n";
2011 my $old_config = $ENV{GIT_CONFIG};
2012 $ENV{GIT_CONFIG} = $config;
2013 $@ = undef;
2014 my @ret = eval {
2015 unless (-f $config) {
2016 mkfile($config);
2017 open my $fh, '>', $config or
2018 die "Can't open $config: $!\n";
2019 print $fh "; This file is used internally by ",
2020 "git-svn\n" or die
2021 "Couldn't write to $config: $!\n";
2022 print $fh "; You should not have to edit it\n" or
2023 die "Couldn't write to $config: $!\n";
2024 close $fh or die "Couldn't close $config: $!\n";
2026 command('config', @args);
2028 my $err = $@;
2029 if (defined $old_config) {
2030 $ENV{GIT_CONFIG} = $old_config;
2031 } else {
2032 delete $ENV{GIT_CONFIG};
2034 die $err if $err;
2035 wantarray ? @ret : $ret[0];
2038 sub tmp_index_do {
2039 my ($self, $sub) = @_;
2040 my $old_index = $ENV{GIT_INDEX_FILE};
2041 $ENV{GIT_INDEX_FILE} = $self->{index};
2042 $@ = undef;
2043 my @ret = eval {
2044 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2045 mkpath([$dir]) unless -d $dir;
2046 &$sub;
2048 my $err = $@;
2049 if (defined $old_index) {
2050 $ENV{GIT_INDEX_FILE} = $old_index;
2051 } else {
2052 delete $ENV{GIT_INDEX_FILE};
2054 die $err if $err;
2055 wantarray ? @ret : $ret[0];
2058 sub assert_index_clean {
2059 my ($self, $treeish) = @_;
2061 $self->tmp_index_do(sub {
2062 command_noisy('read-tree', $treeish) unless -e $self->{index};
2063 my $x = command_oneline('write-tree');
2064 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2065 /^tree ($::sha1)/mo);
2066 return if $y eq $x;
2068 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2069 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2070 command_noisy('read-tree', $treeish);
2071 $x = command_oneline('write-tree');
2072 if ($y ne $x) {
2073 ::fatal "trees ($treeish) $y != $x\n",
2074 "Something is seriously wrong...";
2079 sub get_commit_parents {
2080 my ($self, $log_entry) = @_;
2081 my (%seen, @ret, @tmp);
2082 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2083 if (my $ip = $self->{inject_parents}) {
2084 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2085 push @tmp, $commit;
2088 if (my $cur = ::verify_ref($self->refname.'^0')) {
2089 push @tmp, $cur;
2091 if (my $ipd = $self->{inject_parents_dcommit}) {
2092 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2093 push @tmp, @$commit;
2096 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2097 while (my $p = shift @tmp) {
2098 next if $seen{$p};
2099 $seen{$p} = 1;
2100 push @ret, $p;
2101 # MAXPARENT is defined to 16 in commit-tree.c:
2102 last if @ret >= 16;
2104 if (@tmp) {
2105 die "r$log_entry->{revision}: No room for parents:\n\t",
2106 join("\n\t", @tmp), "\n";
2108 @ret;
2111 sub rewrite_root {
2112 my ($self) = @_;
2113 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2114 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2115 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2116 if ($rwr) {
2117 $rwr =~ s#/+$##;
2118 if ($rwr !~ m#^[a-z\+]+://#) {
2119 die "$rwr is not a valid URL (key: $k)\n";
2122 $self->{-rewrite_root} = $rwr;
2125 sub metadata_url {
2126 my ($self) = @_;
2127 ($self->rewrite_root || $self->{url}) .
2128 (length $self->{path} ? '/' . $self->{path} : '');
2131 sub full_url {
2132 my ($self) = @_;
2133 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2137 sub set_commit_header_env {
2138 my ($log_entry) = @_;
2139 my %env;
2140 foreach my $ned (qw/NAME EMAIL DATE/) {
2141 foreach my $ac (qw/AUTHOR COMMITTER/) {
2142 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2146 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2147 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2148 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2150 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2151 ? $log_entry->{commit_name}
2152 : $log_entry->{name};
2153 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2154 ? $log_entry->{commit_email}
2155 : $log_entry->{email};
2156 \%env;
2159 sub restore_commit_header_env {
2160 my ($env) = @_;
2161 foreach my $ned (qw/NAME EMAIL DATE/) {
2162 foreach my $ac (qw/AUTHOR COMMITTER/) {
2163 my $k = "GIT_${ac}_${ned}";
2164 if (defined $env->{$k}) {
2165 $ENV{$k} = $env->{$k};
2166 } else {
2167 delete $ENV{$k};
2173 sub gc {
2174 command_noisy('gc', '--auto');
2177 sub do_git_commit {
2178 my ($self, $log_entry) = @_;
2179 my $lr = $self->last_rev;
2180 if (defined $lr && $lr >= $log_entry->{revision}) {
2181 die "Last fetched revision of ", $self->refname,
2182 " was r$lr, but we are about to fetch: ",
2183 "r$log_entry->{revision}!\n";
2185 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2186 croak "$log_entry->{revision} = $c already exists! ",
2187 "Why are we refetching it?\n";
2189 my $old_env = set_commit_header_env($log_entry);
2190 my $tree = $log_entry->{tree};
2191 if (!defined $tree) {
2192 $tree = $self->tmp_index_do(sub {
2193 command_oneline('write-tree') });
2195 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2197 my @exec = ('git-commit-tree', $tree);
2198 foreach ($self->get_commit_parents($log_entry)) {
2199 push @exec, '-p', $_;
2201 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2202 or croak $!;
2203 print $msg_fh $log_entry->{log} or croak $!;
2204 restore_commit_header_env($old_env);
2205 unless ($self->no_metadata) {
2206 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2207 or croak $!;
2209 $msg_fh->flush == 0 or croak $!;
2210 close $msg_fh or croak $!;
2211 chomp(my $commit = do { local $/; <$out_fh> });
2212 close $out_fh or croak $!;
2213 waitpid $pid, 0;
2214 croak $? if $?;
2215 if ($commit !~ /^$::sha1$/o) {
2216 die "Failed to commit, invalid sha1: $commit\n";
2219 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2221 $self->{last_rev} = $log_entry->{revision};
2222 $self->{last_commit} = $commit;
2223 print "r$log_entry->{revision}";
2224 if (defined $log_entry->{svm_revision}) {
2225 print " (\@$log_entry->{svm_revision})";
2226 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2227 0, $self->svm_uuid);
2229 print " = $commit ($self->{ref_id})\n";
2230 if (--$_gc_nr == 0) {
2231 $_gc_nr = $_gc_period;
2232 gc();
2234 return $commit;
2237 sub match_paths {
2238 my ($self, $paths, $r) = @_;
2239 return 1 if $self->{path} eq '';
2240 if (my $path = $paths->{"/$self->{path}"}) {
2241 return ($path->{action} eq 'D') ? 0 : 1;
2243 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2244 if (grep /$self->{path_regex}/, keys %$paths) {
2245 return 1;
2247 my $c = '';
2248 foreach (split m#/#, $self->{path}) {
2249 $c .= "/$_";
2250 next unless ($paths->{$c} &&
2251 ($paths->{$c}->{action} =~ /^[AR]$/));
2252 if ($self->ra->check_path($self->{path}, $r) ==
2253 $SVN::Node::dir) {
2254 return 1;
2257 return 0;
2260 sub find_parent_branch {
2261 my ($self, $paths, $rev) = @_;
2262 return undef unless $self->follow_parent;
2263 unless (defined $paths) {
2264 my $err_handler = $SVN::Error::handler;
2265 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2266 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2267 $paths =
2268 Git::SVN::Ra::dup_changed_paths($_[0]) });
2269 $SVN::Error::handler = $err_handler;
2271 return undef unless defined $paths;
2273 # look for a parent from another branch:
2274 my @b_path_components = split m#/#, $self->rel_path;
2275 my @a_path_components;
2276 my $i;
2277 while (@b_path_components) {
2278 $i = $paths->{'/'.join('/', @b_path_components)};
2279 last if $i && defined $i->{copyfrom_path};
2280 unshift(@a_path_components, pop(@b_path_components));
2282 return undef unless defined $i && defined $i->{copyfrom_path};
2283 my $branch_from = $i->{copyfrom_path};
2284 if (@a_path_components) {
2285 print STDERR "branch_from: $branch_from => ";
2286 $branch_from .= '/'.join('/', @a_path_components);
2287 print STDERR $branch_from, "\n";
2289 my $r = $i->{copyfrom_rev};
2290 my $repos_root = $self->ra->{repos_root};
2291 my $url = $self->ra->{url};
2292 my $new_url = $repos_root . $branch_from;
2293 print STDERR "Found possible branch point: ",
2294 "$new_url => ", $self->full_url, ", $r\n";
2295 $branch_from =~ s#^/##;
2296 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2297 unless ($gs) {
2298 my $ref_id = $self->{ref_id};
2299 $ref_id =~ s/\@\d+$//;
2300 $ref_id .= "\@$r";
2301 # just grow a tail if we're not unique enough :x
2302 $ref_id .= '-' while find_ref($ref_id);
2303 print STDERR "Initializing parent: $ref_id\n";
2304 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2305 if ($u =~ s#^\Q$url\E(/|$)##) {
2306 $p = $u;
2307 $u = $url;
2308 $repo_id = $self->{repo_id};
2310 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2312 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2313 if (!defined $r0 || !defined $parent) {
2314 my ($base, $head) = parse_revision_argument(0, $r);
2315 if ($base <= $r) {
2316 $gs->fetch($base, $r);
2318 ($r0, $parent) = $gs->last_rev_commit;
2320 if (defined $r0 && defined $parent) {
2321 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2322 my $ed;
2323 if ($self->ra->can_do_switch) {
2324 $self->assert_index_clean($parent);
2325 print STDERR "Following parent with do_switch\n";
2326 # do_switch works with svn/trunk >= r22312, but that
2327 # is not included with SVN 1.4.3 (the latest version
2328 # at the moment), so we can't rely on it
2329 $self->{last_commit} = $parent;
2330 $ed = SVN::Git::Fetcher->new($self);
2331 $gs->ra->gs_do_switch($r0, $rev, $gs,
2332 $self->full_url, $ed)
2333 or die "SVN connection failed somewhere...\n";
2334 } elsif ($self->ra->trees_match($new_url, $r0,
2335 $self->full_url, $rev)) {
2336 print STDERR "Trees match:\n",
2337 " $new_url\@$r0\n",
2338 " ${\$self->full_url}\@$rev\n",
2339 "Following parent with no changes\n";
2340 $self->tmp_index_do(sub {
2341 command_noisy('read-tree', $parent);
2343 $self->{last_commit} = $parent;
2344 } else {
2345 print STDERR "Following parent with do_update\n";
2346 $ed = SVN::Git::Fetcher->new($self);
2347 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2348 or die "SVN connection failed somewhere...\n";
2350 print STDERR "Successfully followed parent\n";
2351 return $self->make_log_entry($rev, [$parent], $ed);
2353 return undef;
2356 sub do_fetch {
2357 my ($self, $paths, $rev) = @_;
2358 my $ed;
2359 my ($last_rev, @parents);
2360 if (my $lc = $self->last_commit) {
2361 # we can have a branch that was deleted, then re-added
2362 # under the same name but copied from another path, in
2363 # which case we'll have multiple parents (we don't
2364 # want to break the original ref, nor lose copypath info):
2365 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2366 push @{$log_entry->{parents}}, $lc;
2367 return $log_entry;
2369 $ed = SVN::Git::Fetcher->new($self);
2370 $last_rev = $self->{last_rev};
2371 $ed->{c} = $lc;
2372 @parents = ($lc);
2373 } else {
2374 $last_rev = $rev;
2375 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2376 return $log_entry;
2378 $ed = SVN::Git::Fetcher->new($self);
2380 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2381 die "SVN connection failed somewhere...\n";
2383 $self->make_log_entry($rev, \@parents, $ed);
2386 sub get_untracked {
2387 my ($self, $ed) = @_;
2388 my @out;
2389 my $h = $ed->{empty};
2390 foreach (sort keys %$h) {
2391 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2392 push @out, " $act: " . uri_encode($_);
2393 warn "W: $act: $_\n";
2395 foreach my $t (qw/dir_prop file_prop/) {
2396 $h = $ed->{$t} or next;
2397 foreach my $path (sort keys %$h) {
2398 my $ppath = $path eq '' ? '.' : $path;
2399 foreach my $prop (sort keys %{$h->{$path}}) {
2400 next if $SKIP_PROP{$prop};
2401 my $v = $h->{$path}->{$prop};
2402 my $t_ppath_prop = "$t: " .
2403 uri_encode($ppath) . ' ' .
2404 uri_encode($prop);
2405 if (defined $v) {
2406 push @out, " +$t_ppath_prop " .
2407 uri_encode($v);
2408 } else {
2409 push @out, " -$t_ppath_prop";
2414 foreach my $t (qw/absent_file absent_directory/) {
2415 $h = $ed->{$t} or next;
2416 foreach my $parent (sort keys %$h) {
2417 foreach my $path (sort @{$h->{$parent}}) {
2418 push @out, " $t: " .
2419 uri_encode("$parent/$path");
2420 warn "W: $t: $parent/$path ",
2421 "Insufficient permissions?\n";
2425 \@out;
2428 sub parse_svn_date {
2429 my $date = shift || return '+0000 1970-01-01 00:00:00';
2430 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2431 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2432 croak "Unable to parse date: $date\n";
2433 "+0000 $Y-$m-$d $H:$M:$S";
2436 sub check_author {
2437 my ($author) = @_;
2438 if (!defined $author || length $author == 0) {
2439 $author = '(no author)';
2440 } elsif (defined $::_authors && ! defined $::users{$author}) {
2441 die "Author: $author not defined in $::_authors file\n";
2443 $author;
2446 sub make_log_entry {
2447 my ($self, $rev, $parents, $ed) = @_;
2448 my $untracked = $self->get_untracked($ed);
2450 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2451 print $un "r$rev\n" or croak $!;
2452 print $un $_, "\n" foreach @$untracked;
2453 my %log_entry = ( parents => $parents || [], revision => $rev,
2454 log => '');
2456 my $headrev;
2457 my $logged = delete $self->{logged_rev_props};
2458 if (!$logged || $self->{-want_revprops}) {
2459 my $rp = $self->ra->rev_proplist($rev);
2460 foreach (sort keys %$rp) {
2461 my $v = $rp->{$_};
2462 if (/^svn:(author|date|log)$/) {
2463 $log_entry{$1} = $v;
2464 } elsif ($_ eq 'svm:headrev') {
2465 $headrev = $v;
2466 } else {
2467 print $un " rev_prop: ", uri_encode($_), ' ',
2468 uri_encode($v), "\n";
2471 } else {
2472 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2474 close $un or croak $!;
2476 $log_entry{date} = parse_svn_date($log_entry{date});
2477 $log_entry{log} .= "\n";
2478 my $author = $log_entry{author} = check_author($log_entry{author});
2479 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2480 : ($author, undef);
2482 my ($commit_name, $commit_email) = ($name, $email);
2483 if ($_use_log_author) {
2484 my $name_field;
2485 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2486 $name_field = $1;
2487 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2488 $name_field = $1;
2490 if (!defined $name_field) {
2491 if (!defined $email) {
2492 $email = $name;
2494 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2495 ($name, $email) = ($1, $2);
2496 } elsif ($name_field =~ /(.*)@/) {
2497 ($name, $email) = ($1, $name_field);
2498 } else {
2499 ($name, $email) = ($name_field, $name_field);
2502 if (defined $headrev && $self->use_svm_props) {
2503 if ($self->rewrite_root) {
2504 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2505 "options set!\n";
2507 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2508 # we don't want "SVM: initializing mirror for junk" ...
2509 return undef if $r == 0;
2510 my $svm = $self->svm;
2511 if ($uuid ne $svm->{uuid}) {
2512 die "UUID mismatch on SVM path:\n",
2513 "expected: $svm->{uuid}\n",
2514 " got: $uuid\n";
2516 my $full_url = $self->full_url;
2517 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2518 die "Failed to replace '$svm->{replace}' with ",
2519 "'$svm->{source}' in $full_url\n";
2520 # throw away username for storing in records
2521 remove_username($full_url);
2522 $log_entry{metadata} = "$full_url\@$r $uuid";
2523 $log_entry{svm_revision} = $r;
2524 $email ||= "$author\@$uuid";
2525 $commit_email ||= "$author\@$uuid";
2526 } elsif ($self->use_svnsync_props) {
2527 my $full_url = $self->svnsync->{url};
2528 $full_url .= "/$self->{path}" if length $self->{path};
2529 remove_username($full_url);
2530 my $uuid = $self->svnsync->{uuid};
2531 $log_entry{metadata} = "$full_url\@$rev $uuid";
2532 $email ||= "$author\@$uuid";
2533 $commit_email ||= "$author\@$uuid";
2534 } else {
2535 my $url = $self->metadata_url;
2536 remove_username($url);
2537 $log_entry{metadata} = "$url\@$rev " .
2538 $self->ra->get_uuid;
2539 $email ||= "$author\@" . $self->ra->get_uuid;
2540 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2542 $log_entry{name} = $name;
2543 $log_entry{email} = $email;
2544 $log_entry{commit_name} = $commit_name;
2545 $log_entry{commit_email} = $commit_email;
2546 \%log_entry;
2549 sub fetch {
2550 my ($self, $min_rev, $max_rev, @parents) = @_;
2551 my ($last_rev, $last_commit) = $self->last_rev_commit;
2552 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2553 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2556 sub set_tree_cb {
2557 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2558 $self->{inject_parents} = { $rev => $tree };
2559 $self->fetch(undef, undef);
2562 sub set_tree {
2563 my ($self, $tree) = (shift, shift);
2564 my $log_entry = ::get_commit_entry($tree);
2565 unless ($self->{last_rev}) {
2566 fatal("Must have an existing revision to commit");
2568 my %ed_opts = ( r => $self->{last_rev},
2569 log => $log_entry->{log},
2570 ra => $self->ra,
2571 tree_a => $self->{last_commit},
2572 tree_b => $tree,
2573 editor_cb => sub {
2574 $self->set_tree_cb($log_entry, $tree, @_) },
2575 svn_path => $self->{path} );
2576 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2577 print "No changes\nr$self->{last_rev} = $tree\n";
2581 sub rebuild_from_rev_db {
2582 my ($self, $path) = @_;
2583 my $r = -1;
2584 open my $fh, '<', $path or croak "open: $!";
2585 binmode $fh or croak "binmode: $!";
2586 while (<$fh>) {
2587 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2588 chomp($_);
2589 ++$r;
2590 next if $_ eq ('0' x 40);
2591 $self->rev_map_set($r, $_);
2592 print "r$r = $_\n";
2594 close $fh or croak "close: $!";
2595 unlink $path or croak "unlink: $!";
2598 sub rebuild {
2599 my ($self) = @_;
2600 my $map_path = $self->map_path;
2601 return if (-e $map_path && ! -z $map_path);
2602 return unless ::verify_ref($self->refname.'^0');
2603 if ($self->use_svm_props || $self->no_metadata) {
2604 my $rev_db = $self->rev_db_path;
2605 $self->rebuild_from_rev_db($rev_db);
2606 if ($self->use_svm_props) {
2607 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2608 $self->rebuild_from_rev_db($svm_rev_db);
2610 $self->unlink_rev_db_symlink;
2611 return;
2613 print "Rebuilding $map_path ...\n";
2614 my ($log, $ctx) =
2615 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2616 $self->refname, '--');
2617 my $metadata_url = $self->metadata_url;
2618 remove_username($metadata_url);
2619 my $svn_uuid = $self->ra_uuid;
2620 my $c;
2621 while (<$log>) {
2622 if ( m{^commit ($::sha1)$} ) {
2623 $c = $1;
2624 next;
2626 next unless s{^\s*(git-svn-id:)}{$1};
2627 my ($url, $rev, $uuid) = ::extract_metadata($_);
2628 remove_username($url);
2630 # ignore merges (from set-tree)
2631 next if (!defined $rev || !$uuid);
2633 # if we merged or otherwise started elsewhere, this is
2634 # how we break out of it
2635 if (($uuid ne $svn_uuid) ||
2636 ($metadata_url && $url && ($url ne $metadata_url))) {
2637 next;
2640 $self->rev_map_set($rev, $c);
2641 print "r$rev = $c\n";
2643 command_close_pipe($log, $ctx);
2644 print "Done rebuilding $map_path\n";
2645 my $rev_db_path = $self->rev_db_path;
2646 if (-f $self->rev_db_path) {
2647 unlink $self->rev_db_path or croak "unlink: $!";
2649 $self->unlink_rev_db_symlink;
2652 # rev_map:
2653 # Tie::File seems to be prone to offset errors if revisions get sparse,
2654 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2655 # one of my favorite modules is out :< Next up would be one of the DBM
2656 # modules, but I'm not sure which is most portable...
2658 # This is the replacement for the rev_db format, which was too big
2659 # and inefficient for large repositories with a lot of sparse history
2660 # (mainly tags)
2662 # The format is this:
2663 # - 24 bytes for every record,
2664 # * 4 bytes for the integer representing an SVN revision number
2665 # * 20 bytes representing the sha1 of a git commit
2666 # - No empty padding records like the old format
2667 # (except the last record, which can be overwritten)
2668 # - new records are written append-only since SVN revision numbers
2669 # increase monotonically
2670 # - lookups on SVN revision number are done via a binary search
2671 # - Piping the file to xxd -c24 is a good way of dumping it for
2672 # viewing or editing (piped back through xxd -r), should the need
2673 # ever arise.
2674 # - The last record can be padding revision with an all-zero sha1
2675 # This is used to optimize fetch performance when using multiple
2676 # "fetch" directives in .git/config
2678 # These files are disposable unless noMetadata or useSvmProps is set
2680 sub _rev_map_set {
2681 my ($fh, $rev, $commit) = @_;
2683 binmode $fh or croak "binmode: $!";
2684 my $size = (stat($fh))[7];
2685 ($size % 24) == 0 or croak "inconsistent size: $size";
2687 my $wr_offset = 0;
2688 if ($size > 0) {
2689 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2690 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2691 $read == 24 or croak "read only $read bytes (!= 24)";
2692 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2693 if ($last_commit eq ('0' x40)) {
2694 if ($size >= 48) {
2695 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2696 $read = sysread($fh, $buf, 24) or
2697 croak "read: $!";
2698 $read == 24 or
2699 croak "read only $read bytes (!= 24)";
2700 ($last_rev, $last_commit) =
2701 unpack(rev_map_fmt, $buf);
2702 if ($last_commit eq ('0' x40)) {
2703 croak "inconsistent .rev_map\n";
2706 if ($last_rev >= $rev) {
2707 croak "last_rev is higher!: $last_rev >= $rev";
2709 $wr_offset = -24;
2712 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2713 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2714 croak "write: $!";
2717 sub mkfile {
2718 my ($path) = @_;
2719 unless (-e $path) {
2720 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2721 mkpath([$dir]) unless -d $dir;
2722 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2723 close $fh or die "Couldn't close (create) $path: $!\n";
2727 sub rev_map_set {
2728 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2729 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2730 my $db = $self->map_path($uuid);
2731 my $db_lock = "$db.lock";
2732 my $sig;
2733 if ($update_ref) {
2734 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2735 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2737 mkfile($db);
2739 $LOCKFILES{$db_lock} = 1;
2740 my $sync;
2741 # both of these options make our .rev_db file very, very important
2742 # and we can't afford to lose it because rebuild() won't work
2743 if ($self->use_svm_props || $self->no_metadata) {
2744 $sync = 1;
2745 copy($db, $db_lock) or die "rev_map_set(@_): ",
2746 "Failed to copy: ",
2747 "$db => $db_lock ($!)\n";
2748 } else {
2749 rename $db, $db_lock or die "rev_map_set(@_): ",
2750 "Failed to rename: ",
2751 "$db => $db_lock ($!)\n";
2754 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2755 or croak "Couldn't open $db_lock: $!\n";
2756 _rev_map_set($fh, $rev, $commit);
2757 if ($sync) {
2758 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2759 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2761 close $fh or croak $!;
2762 if ($update_ref) {
2763 $_head = $self;
2764 command_noisy('update-ref', '-m', "r$rev",
2765 $self->refname, $commit);
2767 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2768 "$db_lock => $db ($!)\n";
2769 delete $LOCKFILES{$db_lock};
2770 if ($update_ref) {
2771 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2772 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2773 kill $sig, $$ if defined $sig;
2777 # If want_commit, this will return an array of (rev, commit) where
2778 # commit _must_ be a valid commit in the archive.
2779 # Otherwise, it'll return the max revision (whether or not the
2780 # commit is valid or just a 0x40 placeholder).
2781 sub rev_map_max {
2782 my ($self, $want_commit) = @_;
2783 $self->rebuild;
2784 my $map_path = $self->map_path;
2785 stat $map_path or return $want_commit ? (0, undef) : 0;
2786 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2787 binmode $fh or croak "binmode: $!";
2788 my $size = (stat($fh))[7];
2789 ($size % 24) == 0 or croak "inconsistent size: $size";
2791 if ($size == 0) {
2792 close $fh or croak "close: $!";
2793 return $want_commit ? (0, undef) : 0;
2796 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2797 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2798 my ($r, $c) = unpack(rev_map_fmt, $buf);
2799 if ($want_commit && $c eq ('0' x40)) {
2800 if ($size < 48) {
2801 return $want_commit ? (0, undef) : 0;
2803 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2804 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2805 ($r, $c) = unpack(rev_map_fmt, $buf);
2806 if ($c eq ('0'x40)) {
2807 croak "Penultimate record is all-zeroes in $map_path";
2810 close $fh or croak "close: $!";
2811 $want_commit ? ($r, $c) : $r;
2814 sub rev_map_get {
2815 my ($self, $rev, $uuid) = @_;
2816 my $map_path = $self->map_path($uuid);
2817 return undef unless -e $map_path;
2819 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2820 binmode $fh or croak "binmode: $!";
2821 my $size = (stat($fh))[7];
2822 ($size % 24) == 0 or croak "inconsistent size: $size";
2824 if ($size == 0) {
2825 close $fh or croak "close: $fh";
2826 return undef;
2829 my ($l, $u) = (0, $size - 24);
2830 my ($r, $c, $buf);
2832 while ($l <= $u) {
2833 my $i = int(($l/24 + $u/24) / 2) * 24;
2834 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2835 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2836 my ($r, $c) = unpack('NH40', $buf);
2838 if ($r < $rev) {
2839 $l = $i + 24;
2840 } elsif ($r > $rev) {
2841 $u = $i - 24;
2842 } else { # $r == $rev
2843 close($fh) or croak "close: $!";
2844 return $c eq ('0' x 40) ? undef : $c;
2847 close($fh) or croak "close: $!";
2848 undef;
2851 # Finds the first svn revision that exists on (if $eq_ok is true) or
2852 # before $rev for the current branch. It will not search any lower
2853 # than $min_rev. Returns the git commit hash and svn revision number
2854 # if found, else (undef, undef).
2855 sub find_rev_before {
2856 my ($self, $rev, $eq_ok, $min_rev) = @_;
2857 --$rev unless $eq_ok;
2858 $min_rev ||= 1;
2859 while ($rev >= $min_rev) {
2860 if (my $c = $self->rev_map_get($rev)) {
2861 return ($rev, $c);
2863 --$rev;
2865 return (undef, undef);
2868 # Finds the first svn revision that exists on (if $eq_ok is true) or
2869 # after $rev for the current branch. It will not search any higher
2870 # than $max_rev. Returns the git commit hash and svn revision number
2871 # if found, else (undef, undef).
2872 sub find_rev_after {
2873 my ($self, $rev, $eq_ok, $max_rev) = @_;
2874 ++$rev unless $eq_ok;
2875 $max_rev ||= $self->rev_map_max;
2876 while ($rev <= $max_rev) {
2877 if (my $c = $self->rev_map_get($rev)) {
2878 return ($rev, $c);
2880 ++$rev;
2882 return (undef, undef);
2885 sub _new {
2886 my ($class, $repo_id, $ref_id, $path) = @_;
2887 unless (defined $repo_id && length $repo_id) {
2888 $repo_id = $Git::SVN::default_repo_id;
2890 unless (defined $ref_id && length $ref_id) {
2891 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2893 $_[1] = $repo_id;
2894 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2895 $_[3] = $path = '' unless (defined $path);
2896 mkpath(["$ENV{GIT_DIR}/svn"]);
2897 bless {
2898 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2899 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2900 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2903 # for read-only access of old .rev_db formats
2904 sub unlink_rev_db_symlink {
2905 my ($self) = @_;
2906 my $link = $self->rev_db_path;
2907 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2908 if (-l $link) {
2909 unlink $link or croak "unlink: $link failed!";
2913 sub rev_db_path {
2914 my ($self, $uuid) = @_;
2915 my $db_path = $self->map_path($uuid);
2916 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2917 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2918 $db_path;
2921 # the new replacement for .rev_db
2922 sub map_path {
2923 my ($self, $uuid) = @_;
2924 $uuid ||= $self->ra_uuid;
2925 "$self->{map_root}.$uuid";
2928 sub uri_encode {
2929 my ($f) = @_;
2930 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2934 sub remove_username {
2935 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2938 package Git::SVN::Prompt;
2939 use strict;
2940 use warnings;
2941 require SVN::Core;
2942 use vars qw/$_no_auth_cache $_username/;
2944 sub simple {
2945 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2946 $may_save = undef if $_no_auth_cache;
2947 $default_username = $_username if defined $_username;
2948 if (defined $default_username && length $default_username) {
2949 if (defined $realm && length $realm) {
2950 print STDERR "Authentication realm: $realm\n";
2951 STDERR->flush;
2953 $cred->username($default_username);
2954 } else {
2955 username($cred, $realm, $may_save, $pool);
2957 $cred->password(_read_password("Password for '" .
2958 $cred->username . "': ", $realm));
2959 $cred->may_save($may_save);
2960 $SVN::_Core::SVN_NO_ERROR;
2963 sub ssl_server_trust {
2964 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2965 $may_save = undef if $_no_auth_cache;
2966 print STDERR "Error validating server certificate for '$realm':\n";
2968 no warnings 'once';
2969 # All variables SVN::Auth::SSL::* are used only once,
2970 # so we're shutting up Perl warnings about this.
2971 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2972 print STDERR " - The certificate is not issued ",
2973 "by a trusted authority. Use the\n",
2974 " fingerprint to validate ",
2975 "the certificate manually!\n";
2977 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2978 print STDERR " - The certificate hostname ",
2979 "does not match.\n";
2981 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2982 print STDERR " - The certificate is not yet valid.\n";
2984 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2985 print STDERR " - The certificate has expired.\n";
2987 if ($failures & $SVN::Auth::SSL::OTHER) {
2988 print STDERR " - The certificate has ",
2989 "an unknown error.\n";
2991 } # no warnings 'once'
2992 printf STDERR
2993 "Certificate information:\n".
2994 " - Hostname: %s\n".
2995 " - Valid: from %s until %s\n".
2996 " - Issuer: %s\n".
2997 " - Fingerprint: %s\n",
2998 map $cert_info->$_, qw(hostname valid_from valid_until
2999 issuer_dname fingerprint);
3000 my $choice;
3001 prompt:
3002 print STDERR $may_save ?
3003 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3004 "(R)eject or accept (t)emporarily? ";
3005 STDERR->flush;
3006 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3007 if ($choice =~ /^t$/i) {
3008 $cred->may_save(undef);
3009 } elsif ($choice =~ /^r$/i) {
3010 return -1;
3011 } elsif ($may_save && $choice =~ /^p$/i) {
3012 $cred->may_save($may_save);
3013 } else {
3014 goto prompt;
3016 $cred->accepted_failures($failures);
3017 $SVN::_Core::SVN_NO_ERROR;
3020 sub ssl_client_cert {
3021 my ($cred, $realm, $may_save, $pool) = @_;
3022 $may_save = undef if $_no_auth_cache;
3023 print STDERR "Client certificate filename: ";
3024 STDERR->flush;
3025 chomp(my $filename = <STDIN>);
3026 $cred->cert_file($filename);
3027 $cred->may_save($may_save);
3028 $SVN::_Core::SVN_NO_ERROR;
3031 sub ssl_client_cert_pw {
3032 my ($cred, $realm, $may_save, $pool) = @_;
3033 $may_save = undef if $_no_auth_cache;
3034 $cred->password(_read_password("Password: ", $realm));
3035 $cred->may_save($may_save);
3036 $SVN::_Core::SVN_NO_ERROR;
3039 sub username {
3040 my ($cred, $realm, $may_save, $pool) = @_;
3041 $may_save = undef if $_no_auth_cache;
3042 if (defined $realm && length $realm) {
3043 print STDERR "Authentication realm: $realm\n";
3045 my $username;
3046 if (defined $_username) {
3047 $username = $_username;
3048 } else {
3049 print STDERR "Username: ";
3050 STDERR->flush;
3051 chomp($username = <STDIN>);
3053 $cred->username($username);
3054 $cred->may_save($may_save);
3055 $SVN::_Core::SVN_NO_ERROR;
3058 sub _read_password {
3059 my ($prompt, $realm) = @_;
3060 print STDERR $prompt;
3061 STDERR->flush;
3062 require Term::ReadKey;
3063 Term::ReadKey::ReadMode('noecho');
3064 my $password = '';
3065 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3066 last if $key =~ /[\012\015]/; # \n\r
3067 $password .= $key;
3069 Term::ReadKey::ReadMode('restore');
3070 print STDERR "\n";
3071 STDERR->flush;
3072 $password;
3075 package SVN::Git::Fetcher;
3076 use vars qw/@ISA/;
3077 use strict;
3078 use warnings;
3079 use Carp qw/croak/;
3080 use File::Temp qw/tempfile/;
3081 use IO::File qw//;
3083 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3084 sub new {
3085 my ($class, $git_svn) = @_;
3086 my $self = SVN::Delta::Editor->new;
3087 bless $self, $class;
3088 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3089 $self->{empty} = {};
3090 $self->{dir_prop} = {};
3091 $self->{file_prop} = {};
3092 $self->{absent_dir} = {};
3093 $self->{absent_file} = {};
3094 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3095 $self;
3098 sub set_path_strip {
3099 my ($self, $path) = @_;
3100 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3103 sub open_root {
3104 { path => '' };
3107 sub open_directory {
3108 my ($self, $path, $pb, $rev) = @_;
3109 { path => $path };
3112 sub git_path {
3113 my ($self, $path) = @_;
3114 if ($self->{path_strip}) {
3115 $path =~ s!$self->{path_strip}!! or
3116 die "Failed to strip path '$path' ($self->{path_strip})\n";
3118 $path;
3121 sub delete_entry {
3122 my ($self, $path, $rev, $pb) = @_;
3124 my $gpath = $self->git_path($path);
3125 return undef if ($gpath eq '');
3127 # remove entire directories.
3128 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3129 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3130 -r --name-only -z/,
3131 $self->{c}, '--', $gpath);
3132 local $/ = "\0";
3133 while (<$ls>) {
3134 chomp;
3135 $self->{gii}->remove($_);
3136 print "\tD\t$_\n" unless $::_q;
3138 print "\tD\t$gpath/\n" unless $::_q;
3139 command_close_pipe($ls, $ctx);
3140 $self->{empty}->{$path} = 0
3141 } else {
3142 $self->{gii}->remove($gpath);
3143 print "\tD\t$gpath\n" unless $::_q;
3145 undef;
3148 sub open_file {
3149 my ($self, $path, $pb, $rev) = @_;
3150 my $gpath = $self->git_path($path);
3151 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3152 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3153 unless (defined $mode && defined $blob) {
3154 die "$path was not found in commit $self->{c} (r$rev)\n";
3156 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3157 pool => SVN::Pool->new, action => 'M' };
3160 sub add_file {
3161 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3162 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3163 delete $self->{empty}->{$dir};
3164 { path => $path, mode_a => 100644, mode_b => 100644,
3165 pool => SVN::Pool->new, action => 'A' };
3168 sub add_directory {
3169 my ($self, $path, $cp_path, $cp_rev) = @_;
3170 my $gpath = $self->git_path($path);
3171 if ($gpath eq '') {
3172 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3173 -r --name-only -z/,
3174 $self->{c});
3175 local $/ = "\0";
3176 while (<$ls>) {
3177 chomp;
3178 $self->{gii}->remove($_);
3179 print "\tD\t$_\n" unless $::_q;
3181 command_close_pipe($ls, $ctx);
3182 $self->{empty}->{$path} = 0;
3184 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3185 delete $self->{empty}->{$dir};
3186 $self->{empty}->{$path} = 1;
3187 { path => $path };
3190 sub change_dir_prop {
3191 my ($self, $db, $prop, $value) = @_;
3192 $self->{dir_prop}->{$db->{path}} ||= {};
3193 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3194 undef;
3197 sub absent_directory {
3198 my ($self, $path, $pb) = @_;
3199 $self->{absent_dir}->{$pb->{path}} ||= [];
3200 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3201 undef;
3204 sub absent_file {
3205 my ($self, $path, $pb) = @_;
3206 $self->{absent_file}->{$pb->{path}} ||= [];
3207 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3208 undef;
3211 sub change_file_prop {
3212 my ($self, $fb, $prop, $value) = @_;
3213 if ($prop eq 'svn:executable') {
3214 if ($fb->{mode_b} != 120000) {
3215 $fb->{mode_b} = defined $value ? 100755 : 100644;
3217 } elsif ($prop eq 'svn:special') {
3218 $fb->{mode_b} = defined $value ? 120000 : 100644;
3219 } else {
3220 $self->{file_prop}->{$fb->{path}} ||= {};
3221 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3223 undef;
3226 sub apply_textdelta {
3227 my ($self, $fb, $exp) = @_;
3228 my $fh = IO::File->new_tmpfile;
3229 $fh->autoflush(1);
3230 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3231 # (but $base does not,) so dup() it for reading in close_file
3232 open my $dup, '<&', $fh or croak $!;
3233 my $base = IO::File->new_tmpfile;
3234 $base->autoflush(1);
3235 if ($fb->{blob}) {
3236 print $base 'link ' if ($fb->{mode_a} == 120000);
3237 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3238 die "Failed to read object $fb->{blob}" if ($size < 0);
3240 if (defined $exp) {
3241 seek $base, 0, 0 or croak $!;
3242 my $got = ::md5sum($base);
3243 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3244 "expected: $exp\n",
3245 " got: $got\n" if ($got ne $exp);
3248 seek $base, 0, 0 or croak $!;
3249 $fb->{fh} = $dup;
3250 $fb->{base} = $base;
3251 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3254 sub close_file {
3255 my ($self, $fb, $exp) = @_;
3256 my $hash;
3257 my $path = $self->git_path($fb->{path});
3258 if (my $fh = $fb->{fh}) {
3259 if (defined $exp) {
3260 seek($fh, 0, 0) or croak $!;
3261 my $got = ::md5sum($fh);
3262 if ($got ne $exp) {
3263 die "Checksum mismatch: $path\n",
3264 "expected: $exp\n got: $got\n";
3267 sysseek($fh, 0, 0) or croak $!;
3268 if ($fb->{mode_b} == 120000) {
3269 eval {
3270 sysread($fh, my $buf, 5) == 5 or croak $!;
3271 $buf eq 'link ' or die "$path has mode 120000",
3272 " but is not a link";
3274 if ($@) {
3275 warn "$@\n";
3276 sysseek($fh, 0, 0) or croak $!;
3280 my ($tmp_fh, $tmp_filename) = File::Temp::tempfile(UNLINK => 1);
3281 my $result;
3282 while ($result = sysread($fh, my $string, 1024)) {
3283 my $wrote = syswrite($tmp_fh, $string, $result);
3284 defined($wrote) && $wrote == $result
3285 or croak("write $tmp_filename: $!\n");
3287 defined $result or croak $!;
3288 close $tmp_fh or croak $!;
3290 close $fh or croak $!;
3292 $hash = $::_repository->hash_and_insert_object($tmp_filename);
3293 unlink($tmp_filename);
3294 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3295 close $fb->{base} or croak $!;
3296 } else {
3297 $hash = $fb->{blob} or die "no blob information\n";
3299 $fb->{pool}->clear;
3300 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3301 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3302 undef;
3305 sub abort_edit {
3306 my $self = shift;
3307 $self->{nr} = $self->{gii}->{nr};
3308 delete $self->{gii};
3309 $self->SUPER::abort_edit(@_);
3312 sub close_edit {
3313 my $self = shift;
3314 $self->{git_commit_ok} = 1;
3315 $self->{nr} = $self->{gii}->{nr};
3316 delete $self->{gii};
3317 $self->SUPER::close_edit(@_);
3320 package SVN::Git::Editor;
3321 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3322 use strict;
3323 use warnings;
3324 use Carp qw/croak/;
3325 use IO::File;
3327 sub new {
3328 my ($class, $opts) = @_;
3329 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3330 die "$_ required!\n" unless (defined $opts->{$_});
3333 my $pool = SVN::Pool->new;
3334 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3335 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3336 $opts->{r}, $mods);
3338 # $opts->{ra} functions should not be used after this:
3339 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3340 $opts->{editor_cb}, $pool);
3341 my $self = SVN::Delta::Editor->new(@ce, $pool);
3342 bless $self, $class;
3343 foreach (qw/svn_path r tree_a tree_b/) {
3344 $self->{$_} = $opts->{$_};
3346 $self->{url} = $opts->{ra}->{url};
3347 $self->{mods} = $mods;
3348 $self->{types} = $types;
3349 $self->{pool} = $pool;
3350 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3351 $self->{rm} = { };
3352 $self->{path_prefix} = length $self->{svn_path} ?
3353 "$self->{svn_path}/" : '';
3354 $self->{config} = $opts->{config};
3355 return $self;
3358 sub generate_diff {
3359 my ($tree_a, $tree_b) = @_;
3360 my @diff_tree = qw(diff-tree -z -r);
3361 if ($_cp_similarity) {
3362 push @diff_tree, "-C$_cp_similarity";
3363 } else {
3364 push @diff_tree, '-C';
3366 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3367 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3368 push @diff_tree, $tree_a, $tree_b;
3369 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3370 local $/ = "\0";
3371 my $state = 'meta';
3372 my @mods;
3373 while (<$diff_fh>) {
3374 chomp $_; # this gets rid of the trailing "\0"
3375 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3376 $::sha1\s($::sha1)\s
3377 ([MTCRAD])\d*$/xo) {
3378 push @mods, { mode_a => $1, mode_b => $2,
3379 sha1_b => $3, chg => $4 };
3380 if ($4 =~ /^(?:C|R)$/) {
3381 $state = 'file_a';
3382 } else {
3383 $state = 'file_b';
3385 } elsif ($state eq 'file_a') {
3386 my $x = $mods[$#mods] or croak "Empty array\n";
3387 if ($x->{chg} !~ /^(?:C|R)$/) {
3388 croak "Error parsing $_, $x->{chg}\n";
3390 $x->{file_a} = $_;
3391 $state = 'file_b';
3392 } elsif ($state eq 'file_b') {
3393 my $x = $mods[$#mods] or croak "Empty array\n";
3394 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3395 croak "Error parsing $_, $x->{chg}\n";
3397 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3398 croak "Error parsing $_, $x->{chg}\n";
3400 $x->{file_b} = $_;
3401 $state = 'meta';
3402 } else {
3403 croak "Error parsing $_\n";
3406 command_close_pipe($diff_fh, $ctx);
3407 \@mods;
3410 sub check_diff_paths {
3411 my ($ra, $pfx, $rev, $mods) = @_;
3412 my %types;
3413 $pfx .= '/' if length $pfx;
3415 sub type_diff_paths {
3416 my ($ra, $types, $path, $rev) = @_;
3417 my @p = split m#/+#, $path;
3418 my $c = shift @p;
3419 unless (defined $types->{$c}) {
3420 $types->{$c} = $ra->check_path($c, $rev);
3422 while (@p) {
3423 $c .= '/' . shift @p;
3424 next if defined $types->{$c};
3425 $types->{$c} = $ra->check_path($c, $rev);
3429 foreach my $m (@$mods) {
3430 foreach my $f (qw/file_a file_b/) {
3431 next unless defined $m->{$f};
3432 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3433 if (length $pfx.$dir && ! defined $types{$dir}) {
3434 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3438 \%types;
3441 sub split_path {
3442 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3445 sub repo_path {
3446 my ($self, $path) = @_;
3447 $self->{path_prefix}.(defined $path ? $path : '');
3450 sub url_path {
3451 my ($self, $path) = @_;
3452 if ($self->{url} =~ m#^https?://#) {
3453 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3455 $self->{url} . '/' . $self->repo_path($path);
3458 sub rmdirs {
3459 my ($self) = @_;
3460 my $rm = $self->{rm};
3461 delete $rm->{''}; # we never delete the url we're tracking
3462 return unless %$rm;
3464 foreach (keys %$rm) {
3465 my @d = split m#/#, $_;
3466 my $c = shift @d;
3467 $rm->{$c} = 1;
3468 while (@d) {
3469 $c .= '/' . shift @d;
3470 $rm->{$c} = 1;
3473 delete $rm->{$self->{svn_path}};
3474 delete $rm->{''}; # we never delete the url we're tracking
3475 return unless %$rm;
3477 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3478 $self->{tree_b});
3479 local $/ = "\0";
3480 while (<$fh>) {
3481 chomp;
3482 my @dn = split m#/#, $_;
3483 while (pop @dn) {
3484 delete $rm->{join '/', @dn};
3486 unless (%$rm) {
3487 close $fh;
3488 return;
3491 command_close_pipe($fh, $ctx);
3493 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3494 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3495 $self->close_directory($bat->{$d}, $p);
3496 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3497 print "\tD+\t$d/\n" unless $::_q;
3498 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3499 delete $bat->{$d};
3503 sub open_or_add_dir {
3504 my ($self, $full_path, $baton) = @_;
3505 my $t = $self->{types}->{$full_path};
3506 if (!defined $t) {
3507 die "$full_path not known in r$self->{r} or we have a bug!\n";
3510 no warnings 'once';
3511 # SVN::Node::none and SVN::Node::file are used only once,
3512 # so we're shutting up Perl's warnings about them.
3513 if ($t == $SVN::Node::none) {
3514 return $self->add_directory($full_path, $baton,
3515 undef, -1, $self->{pool});
3516 } elsif ($t == $SVN::Node::dir) {
3517 return $self->open_directory($full_path, $baton,
3518 $self->{r}, $self->{pool});
3519 } # no warnings 'once'
3520 print STDERR "$full_path already exists in repository at ",
3521 "r$self->{r} and it is not a directory (",
3522 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3523 } # no warnings 'once'
3524 exit 1;
3527 sub ensure_path {
3528 my ($self, $path) = @_;
3529 my $bat = $self->{bat};
3530 my $repo_path = $self->repo_path($path);
3531 return $bat->{''} unless (length $repo_path);
3532 my @p = split m#/+#, $repo_path;
3533 my $c = shift @p;
3534 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3535 while (@p) {
3536 my $c0 = $c;
3537 $c .= '/' . shift @p;
3538 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3540 return $bat->{$c};
3543 # Subroutine to convert a globbing pattern to a regular expression.
3544 # From perl cookbook.
3545 sub glob2pat {
3546 my $globstr = shift;
3547 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3548 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3549 return '^' . $globstr . '$';
3552 sub check_autoprop {
3553 my ($self, $pattern, $properties, $file, $fbat) = @_;
3554 # Convert the globbing pattern to a regular expression.
3555 my $regex = glob2pat($pattern);
3556 # Check if the pattern matches the file name.
3557 if($file =~ m/($regex)/) {
3558 # Parse the list of properties to set.
3559 my @props = split(/;/, $properties);
3560 foreach my $prop (@props) {
3561 # Parse 'name=value' syntax and set the property.
3562 if ($prop =~ /([^=]+)=(.*)/) {
3563 my ($n,$v) = ($1,$2);
3564 for ($n, $v) {
3565 s/^\s+//; s/\s+$//;
3567 $self->change_file_prop($fbat, $n, $v);
3573 sub apply_autoprops {
3574 my ($self, $file, $fbat) = @_;
3575 my $conf_t = ${$self->{config}}{'config'};
3576 no warnings 'once';
3577 # Check [miscellany]/enable-auto-props in svn configuration.
3578 if (SVN::_Core::svn_config_get_bool(
3579 $conf_t,
3580 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3581 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3582 0)) {
3583 # Auto-props are enabled. Enumerate them to look for matches.
3584 my $callback = sub {
3585 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3587 SVN::_Core::svn_config_enumerate(
3588 $conf_t,
3589 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3590 $callback);
3594 sub A {
3595 my ($self, $m) = @_;
3596 my ($dir, $file) = split_path($m->{file_b});
3597 my $pbat = $self->ensure_path($dir);
3598 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3599 undef, -1);
3600 print "\tA\t$m->{file_b}\n" unless $::_q;
3601 $self->apply_autoprops($file, $fbat);
3602 $self->chg_file($fbat, $m);
3603 $self->close_file($fbat,undef,$self->{pool});
3606 sub C {
3607 my ($self, $m) = @_;
3608 my ($dir, $file) = split_path($m->{file_b});
3609 my $pbat = $self->ensure_path($dir);
3610 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3611 $self->url_path($m->{file_a}), $self->{r});
3612 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3613 $self->chg_file($fbat, $m);
3614 $self->close_file($fbat,undef,$self->{pool});
3617 sub delete_entry {
3618 my ($self, $path, $pbat) = @_;
3619 my $rpath = $self->repo_path($path);
3620 my ($dir, $file) = split_path($rpath);
3621 $self->{rm}->{$dir} = 1;
3622 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3625 sub R {
3626 my ($self, $m) = @_;
3627 my ($dir, $file) = split_path($m->{file_b});
3628 my $pbat = $self->ensure_path($dir);
3629 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3630 $self->url_path($m->{file_a}), $self->{r});
3631 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3632 $self->chg_file($fbat, $m);
3633 $self->close_file($fbat,undef,$self->{pool});
3635 ($dir, $file) = split_path($m->{file_a});
3636 $pbat = $self->ensure_path($dir);
3637 $self->delete_entry($m->{file_a}, $pbat);
3640 sub M {
3641 my ($self, $m) = @_;
3642 my ($dir, $file) = split_path($m->{file_b});
3643 my $pbat = $self->ensure_path($dir);
3644 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3645 $pbat,$self->{r},$self->{pool});
3646 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3647 $self->chg_file($fbat, $m);
3648 $self->close_file($fbat,undef,$self->{pool});
3651 sub T { shift->M(@_) }
3653 sub change_file_prop {
3654 my ($self, $fbat, $pname, $pval) = @_;
3655 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3658 sub chg_file {
3659 my ($self, $fbat, $m) = @_;
3660 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3661 $self->change_file_prop($fbat,'svn:executable','*');
3662 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3663 $self->change_file_prop($fbat,'svn:executable',undef);
3665 my $fh = IO::File->new_tmpfile or croak $!;
3666 if ($m->{mode_b} =~ /^120/) {
3667 print $fh 'link ' or croak $!;
3668 $self->change_file_prop($fbat,'svn:special','*');
3669 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3670 $self->change_file_prop($fbat,'svn:special',undef);
3672 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
3673 croak "Failed to read object $m->{sha1_b}" if ($size < 0);
3674 $fh->flush == 0 or croak $!;
3675 seek $fh, 0, 0 or croak $!;
3677 my $exp = ::md5sum($fh);
3678 seek $fh, 0, 0 or croak $!;
3680 my $pool = SVN::Pool->new;
3681 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3682 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3683 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3684 $pool->clear;
3686 close $fh or croak $!;
3689 sub D {
3690 my ($self, $m) = @_;
3691 my ($dir, $file) = split_path($m->{file_b});
3692 my $pbat = $self->ensure_path($dir);
3693 print "\tD\t$m->{file_b}\n" unless $::_q;
3694 $self->delete_entry($m->{file_b}, $pbat);
3697 sub close_edit {
3698 my ($self) = @_;
3699 my ($p,$bat) = ($self->{pool}, $self->{bat});
3700 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3701 next if $_ eq '';
3702 $self->close_directory($bat->{$_}, $p);
3704 $self->close_directory($bat->{''}, $p);
3705 $self->SUPER::close_edit($p);
3706 $p->clear;
3709 sub abort_edit {
3710 my ($self) = @_;
3711 $self->SUPER::abort_edit($self->{pool});
3714 sub DESTROY {
3715 my $self = shift;
3716 $self->SUPER::DESTROY(@_);
3717 $self->{pool}->clear;
3720 # this drives the editor
3721 sub apply_diff {
3722 my ($self) = @_;
3723 my $mods = $self->{mods};
3724 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3725 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3726 my $f = $m->{chg};
3727 if (defined $o{$f}) {
3728 $self->$f($m);
3729 } else {
3730 fatal("Invalid change type: $f");
3733 $self->rmdirs if $_rmdir;
3734 if (@$mods == 0) {
3735 $self->abort_edit;
3736 } else {
3737 $self->close_edit;
3739 return scalar @$mods;
3742 package Git::SVN::Ra;
3743 use vars qw/@ISA $config_dir $_log_window_size/;
3744 use strict;
3745 use warnings;
3746 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3748 BEGIN {
3749 # enforce temporary pool usage for some simple functions
3750 no strict 'refs';
3751 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3752 my $SUPER = "SUPER::$f";
3753 *$f = sub {
3754 my $self = shift;
3755 my $pool = SVN::Pool->new;
3756 my @ret = $self->$SUPER(@_,$pool);
3757 $pool->clear;
3758 wantarray ? @ret : $ret[0];
3763 sub _auth_providers () {
3765 SVN::Client::get_simple_provider(),
3766 SVN::Client::get_ssl_server_trust_file_provider(),
3767 SVN::Client::get_simple_prompt_provider(
3768 \&Git::SVN::Prompt::simple, 2),
3769 SVN::Client::get_ssl_client_cert_file_provider(),
3770 SVN::Client::get_ssl_client_cert_prompt_provider(
3771 \&Git::SVN::Prompt::ssl_client_cert, 2),
3772 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3773 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3774 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3775 SVN::Client::get_username_provider(),
3776 SVN::Client::get_ssl_server_trust_prompt_provider(
3777 \&Git::SVN::Prompt::ssl_server_trust),
3778 SVN::Client::get_username_prompt_provider(
3779 \&Git::SVN::Prompt::username, 2)
3783 sub escape_uri_only {
3784 my ($uri) = @_;
3785 my @tmp;
3786 foreach (split m{/}, $uri) {
3787 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3788 push @tmp, $_;
3790 join('/', @tmp);
3793 sub escape_url {
3794 my ($url) = @_;
3795 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3796 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3797 $url = "$scheme://$domain$uri";
3799 $url;
3802 sub new {
3803 my ($class, $url) = @_;
3804 $url =~ s!/+$!!;
3805 return $RA if ($RA && $RA->{url} eq $url);
3807 SVN::_Core::svn_config_ensure($config_dir, undef);
3808 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3809 my $config = SVN::Core::config_get_config($config_dir);
3810 $RA = undef;
3811 my $dont_store_passwords = 1;
3812 my $conf_t = ${$config}{'config'};
3814 no warnings 'once';
3815 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3816 # produces warnings that variables are used only once.
3817 # I had not found the better way to shut them up, so
3818 # the warnings of type 'once' are disabled in this block.
3819 if (SVN::_Core::svn_config_get_bool($conf_t,
3820 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3821 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3822 1) == 0) {
3823 SVN::_Core::svn_auth_set_parameter($baton,
3824 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3825 bless (\$dont_store_passwords, "_p_void"));
3827 if (SVN::_Core::svn_config_get_bool($conf_t,
3828 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3829 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3830 1) == 0) {
3831 $Git::SVN::Prompt::_no_auth_cache = 1;
3833 } # no warnings 'once'
3834 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3835 config => $config,
3836 pool => SVN::Pool->new,
3837 auth_provider_callbacks => $callbacks);
3838 $self->{url} = $url;
3839 $self->{svn_path} = $url;
3840 $self->{repos_root} = $self->get_repos_root;
3841 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3842 $self->{cache} = { check_path => { r => 0, data => {} },
3843 get_dir => { r => 0, data => {} } };
3844 $RA = bless $self, $class;
3847 sub check_path {
3848 my ($self, $path, $r) = @_;
3849 my $cache = $self->{cache}->{check_path};
3850 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3851 return $cache->{data}->{$path};
3853 my $pool = SVN::Pool->new;
3854 my $t = $self->SUPER::check_path($path, $r, $pool);
3855 $pool->clear;
3856 if ($r != $cache->{r}) {
3857 %{$cache->{data}} = ();
3858 $cache->{r} = $r;
3860 $cache->{data}->{$path} = $t;
3863 sub get_dir {
3864 my ($self, $dir, $r) = @_;
3865 my $cache = $self->{cache}->{get_dir};
3866 if ($r == $cache->{r}) {
3867 if (my $x = $cache->{data}->{$dir}) {
3868 return wantarray ? @$x : $x->[0];
3871 my $pool = SVN::Pool->new;
3872 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3873 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3874 $pool->clear;
3875 if ($r != $cache->{r}) {
3876 %{$cache->{data}} = ();
3877 $cache->{r} = $r;
3879 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3880 wantarray ? (\%dirents, $r, $props) : \%dirents;
3883 sub DESTROY {
3884 # do not call the real DESTROY since we store ourselves in $RA
3887 sub get_log {
3888 my ($self, @args) = @_;
3889 my $pool = SVN::Pool->new;
3890 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3891 my $ret = $self->SUPER::get_log(@args, $pool);
3892 $pool->clear;
3893 $ret;
3896 sub trees_match {
3897 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3898 my $ctx = SVN::Client->new(auth => _auth_providers);
3899 my $out = IO::File->new_tmpfile;
3901 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3902 # $ctx->diff(), so we'll create a default one
3903 my $pool = SVN::Pool->new_default_sub;
3905 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3906 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3907 $out->flush;
3908 my $ret = (($out->stat)[7] == 0);
3909 close $out or croak $!;
3911 $ret;
3914 sub get_commit_editor {
3915 my ($self, $log, $cb, $pool) = @_;
3916 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3917 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3920 sub gs_do_update {
3921 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3922 my $new = ($rev_a == $rev_b);
3923 my $path = $gs->{path};
3925 if ($new && -e $gs->{index}) {
3926 unlink $gs->{index} or die
3927 "Couldn't unlink index: $gs->{index}: $!\n";
3929 my $pool = SVN::Pool->new;
3930 $editor->set_path_strip($path);
3931 my (@pc) = split m#/#, $path;
3932 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3933 1, $editor, $pool);
3934 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3936 # Since we can't rely on svn_ra_reparent being available, we'll
3937 # just have to do some magic with set_path to make it so
3938 # we only want a partial path.
3939 my $sp = '';
3940 my $final = join('/', @pc);
3941 while (@pc) {
3942 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3943 $sp .= '/' if length $sp;
3944 $sp .= shift @pc;
3946 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3948 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3950 $reporter->finish_report($pool);
3951 $pool->clear;
3952 $editor->{git_commit_ok};
3955 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3956 # svn_ra_reparent didn't work before 1.4)
3957 sub gs_do_switch {
3958 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3959 my $path = $gs->{path};
3960 my $pool = SVN::Pool->new;
3962 my $full_url = $self->{url};
3963 my $old_url = $full_url;
3964 $full_url .= '/' . escape_uri_only($path) if length $path;
3965 my ($ra, $reparented);
3966 if ($old_url ne $full_url) {
3967 if ($old_url !~ m#^svn(\+ssh)?://#) {
3968 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3969 $pool);
3970 $self->{url} = $full_url;
3971 $reparented = 1;
3972 } else {
3973 $_[0] = undef;
3974 $self = undef;
3975 $RA = undef;
3976 $ra = Git::SVN::Ra->new($full_url);
3977 $ra_invalid = 1;
3980 $ra ||= $self;
3981 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3982 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3983 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3984 $reporter->finish_report($pool);
3986 if ($reparented) {
3987 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3988 $self->{url} = $old_url;
3991 $pool->clear;
3992 $editor->{git_commit_ok};
3995 sub longest_common_path {
3996 my ($gsv, $globs) = @_;
3997 my %common;
3998 my $common_max = scalar @$gsv;
4000 foreach my $gs (@$gsv) {
4001 my @tmp = split m#/#, $gs->{path};
4002 my $p = '';
4003 foreach (@tmp) {
4004 $p .= length($p) ? "/$_" : $_;
4005 $common{$p} ||= 0;
4006 $common{$p}++;
4009 $globs ||= [];
4010 $common_max += scalar @$globs;
4011 foreach my $glob (@$globs) {
4012 my @tmp = split m#/#, $glob->{path}->{left};
4013 my $p = '';
4014 foreach (@tmp) {
4015 $p .= length($p) ? "/$_" : $_;
4016 $common{$p} ||= 0;
4017 $common{$p}++;
4021 my $longest_path = '';
4022 foreach (sort {length $b <=> length $a} keys %common) {
4023 if ($common{$_} == $common_max) {
4024 $longest_path = $_;
4025 last;
4028 $longest_path;
4031 sub gs_fetch_loop_common {
4032 my ($self, $base, $head, $gsv, $globs) = @_;
4033 return if ($base > $head);
4034 my $inc = $_log_window_size;
4035 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4036 my $longest_path = longest_common_path($gsv, $globs);
4037 my $ra_url = $self->{url};
4038 while (1) {
4039 my %revs;
4040 my $err;
4041 my $err_handler = $SVN::Error::handler;
4042 $SVN::Error::handler = sub {
4043 ($err) = @_;
4044 skip_unknown_revs($err);
4046 sub _cb {
4047 my ($paths, $r, $author, $date, $log) = @_;
4048 [ dup_changed_paths($paths),
4049 { author => $author, date => $date, log => $log } ];
4051 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4052 sub { $revs{$_[1]} = _cb(@_) });
4053 if ($err && $max >= $head) {
4054 print STDERR "Path '$longest_path' ",
4055 "was probably deleted:\n",
4056 $err->expanded_message,
4057 "\nWill attempt to follow ",
4058 "revisions r$min .. r$max ",
4059 "committed before the deletion\n";
4060 my $hi = $max;
4061 while (--$hi >= $min) {
4062 my $ok;
4063 $self->get_log([$longest_path], $min, $hi,
4064 0, 1, 1, sub {
4065 $ok ||= $_[1];
4066 $revs{$_[1]} = _cb(@_) });
4067 if ($ok) {
4068 print STDERR "r$min .. r$ok OK\n";
4069 last;
4073 $SVN::Error::handler = $err_handler;
4075 my %exists = map { $_->{path} => $_ } @$gsv;
4076 foreach my $r (sort {$a <=> $b} keys %revs) {
4077 my ($paths, $logged) = @{$revs{$r}};
4079 foreach my $gs ($self->match_globs(\%exists, $paths,
4080 $globs, $r)) {
4081 if ($gs->rev_map_max >= $r) {
4082 next;
4084 next unless $gs->match_paths($paths, $r);
4085 $gs->{logged_rev_props} = $logged;
4086 if (my $last_commit = $gs->last_commit) {
4087 $gs->assert_index_clean($last_commit);
4089 my $log_entry = $gs->do_fetch($paths, $r);
4090 if ($log_entry) {
4091 $gs->do_git_commit($log_entry);
4093 $INDEX_FILES{$gs->{index}} = 1;
4095 foreach my $g (@$globs) {
4096 my $k = "svn-remote.$g->{remote}." .
4097 "$g->{t}-maxRev";
4098 Git::SVN::tmp_config($k, $r);
4100 if ($ra_invalid) {
4101 $_[0] = undef;
4102 $self = undef;
4103 $RA = undef;
4104 $self = Git::SVN::Ra->new($ra_url);
4105 $ra_invalid = undef;
4108 # pre-fill the .rev_db since it'll eventually get filled in
4109 # with '0' x40 if something new gets committed
4110 foreach my $gs (@$gsv) {
4111 next if $gs->rev_map_max >= $max;
4112 next if defined $gs->rev_map_get($max);
4113 $gs->rev_map_set($max, 0 x40);
4115 foreach my $g (@$globs) {
4116 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4117 Git::SVN::tmp_config($k, $max);
4119 last if $max >= $head;
4120 $min = $max + 1;
4121 $max += $inc;
4122 $max = $head if ($max > $head);
4124 Git::SVN::gc();
4127 sub match_globs {
4128 my ($self, $exists, $paths, $globs, $r) = @_;
4130 sub get_dir_check {
4131 my ($self, $exists, $g, $r) = @_;
4132 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
4133 return unless scalar @x == 3;
4134 my $dirents = $x[0];
4135 foreach my $de (keys %$dirents) {
4136 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4137 my $p = $g->{path}->full_path($de);
4138 next if $exists->{$p};
4139 next if (length $g->{path}->{right} &&
4140 ($self->check_path($p, $r) !=
4141 $SVN::Node::dir));
4142 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4143 $g->{ref}->full_path($de), 1);
4146 foreach my $g (@$globs) {
4147 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4148 if ($path->{action} =~ /^[AR]$/) {
4149 get_dir_check($self, $exists, $g, $r);
4152 foreach (keys %$paths) {
4153 if (/$g->{path}->{left_regex}/ &&
4154 !/$g->{path}->{regex}/) {
4155 next if $paths->{$_}->{action} !~ /^[AR]$/;
4156 get_dir_check($self, $exists, $g, $r);
4158 next unless /$g->{path}->{regex}/;
4159 my $p = $1;
4160 my $pathname = $g->{path}->full_path($p);
4161 next if $exists->{$pathname};
4162 next if ($self->check_path($pathname, $r) !=
4163 $SVN::Node::dir);
4164 $exists->{$pathname} = Git::SVN->init(
4165 $self->{url}, $pathname, undef,
4166 $g->{ref}->full_path($p), 1);
4168 my $c = '';
4169 foreach (split m#/#, $g->{path}->{left}) {
4170 $c .= "/$_";
4171 next unless ($paths->{$c} &&
4172 ($paths->{$c}->{action} =~ /^[AR]$/));
4173 get_dir_check($self, $exists, $g, $r);
4176 values %$exists;
4179 sub minimize_url {
4180 my ($self) = @_;
4181 return $self->{url} if ($self->{url} eq $self->{repos_root});
4182 my $url = $self->{repos_root};
4183 my @components = split(m!/!, $self->{svn_path});
4184 my $c = '';
4185 do {
4186 $url .= "/$c" if length $c;
4187 eval { (ref $self)->new($url)->get_latest_revnum };
4188 } while ($@ && ($c = shift @components));
4189 $url;
4192 sub can_do_switch {
4193 my $self = shift;
4194 unless (defined $can_do_switch) {
4195 my $pool = SVN::Pool->new;
4196 my $rep = eval {
4197 $self->do_switch(1, '', 0, $self->{url},
4198 SVN::Delta::Editor->new, $pool);
4200 if ($@) {
4201 $can_do_switch = 0;
4202 } else {
4203 $rep->abort_report($pool);
4204 $can_do_switch = 1;
4206 $pool->clear;
4208 $can_do_switch;
4211 sub skip_unknown_revs {
4212 my ($err) = @_;
4213 my $errno = $err->apr_err();
4214 # Maybe the branch we're tracking didn't
4215 # exist when the repo started, so it's
4216 # not an error if it doesn't, just continue
4218 # Wonderfully consistent library, eh?
4219 # 160013 - svn:// and file://
4220 # 175002 - http(s)://
4221 # 175007 - http(s):// (this repo required authorization, too...)
4222 # More codes may be discovered later...
4223 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4224 my $err_key = $err->expanded_message;
4225 # revision numbers change every time, filter them out
4226 $err_key =~ s/\d+/\0/g;
4227 $err_key = "$errno\0$err_key";
4228 unless ($ignored_err{$err_key}) {
4229 warn "W: Ignoring error from SVN, path probably ",
4230 "does not exist: ($errno): ",
4231 $err->expanded_message,"\n";
4232 warn "W: Do not be alarmed at the above message ",
4233 "git-svn is just searching aggressively for ",
4234 "old history.\n",
4235 "This may take a while on large repositories\n";
4236 $ignored_err{$err_key} = 1;
4238 return;
4240 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4243 # svn_log_changed_path_t objects passed to get_log are likely to be
4244 # overwritten even if only the refs are copied to an external variable,
4245 # so we should dup the structures in their entirety. Using an externally
4246 # passed pool (instead of our temporary and quickly cleared pool in
4247 # Git::SVN::Ra) does not help matters at all...
4248 sub dup_changed_paths {
4249 my ($paths) = @_;
4250 return undef unless $paths;
4251 my %ret;
4252 foreach my $p (keys %$paths) {
4253 my $i = $paths->{$p};
4254 my %s = map { $_ => $i->$_ }
4255 qw/copyfrom_path copyfrom_rev action/;
4256 $ret{$p} = \%s;
4258 \%ret;
4261 package Git::SVN::Log;
4262 use strict;
4263 use warnings;
4264 use POSIX qw/strftime/;
4265 use constant commit_log_separator => ('-' x 72) . "\n";
4266 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4267 %rusers $show_commit $incremental/;
4268 my $l_fmt;
4270 sub cmt_showable {
4271 my ($c) = @_;
4272 return 1 if defined $c->{r};
4274 # big commit message got truncated by the 16k pretty buffer in rev-list
4275 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4276 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4277 @{$c->{l}} = ();
4278 my @log = command(qw/cat-file commit/, $c->{c});
4280 # shift off the headers
4281 shift @log while ($log[0] ne '');
4282 shift @log;
4284 # TODO: make $c->{l} not have a trailing newline in the future
4285 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4287 (undef, $c->{r}, undef) = ::extract_metadata(
4288 (grep(/^git-svn-id: /, @log))[-1]);
4290 return defined $c->{r};
4293 sub log_use_color {
4294 return $color || Git->repository->get_colorbool('color.diff');
4297 sub git_svn_log_cmd {
4298 my ($r_min, $r_max, @args) = @_;
4299 my $head = 'HEAD';
4300 my (@files, @log_opts);
4301 foreach my $x (@args) {
4302 if ($x eq '--' || @files) {
4303 push @files, $x;
4304 } else {
4305 if (::verify_ref("$x^0")) {
4306 $head = $x;
4307 } else {
4308 push @log_opts, $x;
4313 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4314 $gs ||= Git::SVN->_new;
4315 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4316 $gs->refname);
4317 push @cmd, '-r' unless $non_recursive;
4318 push @cmd, qw/--raw --name-status/ if $verbose;
4319 push @cmd, '--color' if log_use_color();
4320 push @cmd, @log_opts;
4321 if (defined $r_max && $r_max == $r_min) {
4322 push @cmd, '--max-count=1';
4323 if (my $c = $gs->rev_map_get($r_max)) {
4324 push @cmd, $c;
4326 } elsif (defined $r_max) {
4327 if ($r_max < $r_min) {
4328 ($r_min, $r_max) = ($r_max, $r_min);
4330 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4331 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4332 # If there are no commits in the range, both $c_max and $c_min
4333 # will be undefined. If there is at least 1 commit in the
4334 # range, both will be defined.
4335 return () if !defined $c_min || !defined $c_max;
4336 if ($c_min eq $c_max) {
4337 push @cmd, '--max-count=1', $c_min;
4338 } else {
4339 push @cmd, '--boundary', "$c_min..$c_max";
4342 return (@cmd, @files);
4345 # adapted from pager.c
4346 sub config_pager {
4347 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4348 if (!defined $pager) {
4349 $pager = 'less';
4350 } elsif (length $pager == 0 || $pager eq 'cat') {
4351 $pager = undef;
4353 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4356 sub run_pager {
4357 return unless -t *STDOUT && defined $pager;
4358 pipe my $rfd, my $wfd or return;
4359 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4360 if (!$pid) {
4361 open STDOUT, '>&', $wfd or
4362 ::fatal "Can't redirect to stdout: $!";
4363 return;
4365 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4366 $ENV{LESS} ||= 'FRSX';
4367 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4370 sub format_svn_date {
4371 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4374 sub parse_git_date {
4375 my ($t, $tz) = @_;
4376 # Date::Parse isn't in the standard Perl distro :(
4377 if ($tz =~ s/^\+//) {
4378 $t += tz_to_s_offset($tz);
4379 } elsif ($tz =~ s/^\-//) {
4380 $t -= tz_to_s_offset($tz);
4382 return $t;
4385 sub set_local_timezone {
4386 if (defined $TZ) {
4387 $ENV{TZ} = $TZ;
4388 } else {
4389 delete $ENV{TZ};
4393 sub tz_to_s_offset {
4394 my ($tz) = @_;
4395 $tz =~ s/(\d\d)$//;
4396 return ($1 * 60) + ($tz * 3600);
4399 sub get_author_info {
4400 my ($dest, $author, $t, $tz) = @_;
4401 $author =~ s/(?:^\s*|\s*$)//g;
4402 $dest->{a_raw} = $author;
4403 my $au;
4404 if ($::_authors) {
4405 $au = $rusers{$author} || undef;
4407 if (!$au) {
4408 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4410 $dest->{t} = $t;
4411 $dest->{tz} = $tz;
4412 $dest->{a} = $au;
4413 $dest->{t_utc} = parse_git_date($t, $tz);
4416 sub process_commit {
4417 my ($c, $r_min, $r_max, $defer) = @_;
4418 if (defined $r_min && defined $r_max) {
4419 if ($r_min == $c->{r} && $r_min == $r_max) {
4420 show_commit($c);
4421 return 0;
4423 return 1 if $r_min == $r_max;
4424 if ($r_min < $r_max) {
4425 # we need to reverse the print order
4426 return 0 if (defined $limit && --$limit < 0);
4427 push @$defer, $c;
4428 return 1;
4430 if ($r_min != $r_max) {
4431 return 1 if ($r_min < $c->{r});
4432 return 1 if ($r_max > $c->{r});
4435 return 0 if (defined $limit && --$limit < 0);
4436 show_commit($c);
4437 return 1;
4440 sub show_commit {
4441 my $c = shift;
4442 if ($oneline) {
4443 my $x = "\n";
4444 if (my $l = $c->{l}) {
4445 while ($l->[0] =~ /^\s*$/) { shift @$l }
4446 $x = $l->[0];
4448 $l_fmt ||= 'A' . length($c->{r});
4449 print 'r',pack($l_fmt, $c->{r}),' | ';
4450 print "$c->{c} | " if $show_commit;
4451 print $x;
4452 } else {
4453 show_commit_normal($c);
4457 sub show_commit_changed_paths {
4458 my ($c) = @_;
4459 return unless $c->{changed};
4460 print "Changed paths:\n", @{$c->{changed}};
4463 sub show_commit_normal {
4464 my ($c) = @_;
4465 print commit_log_separator, "r$c->{r} | ";
4466 print "$c->{c} | " if $show_commit;
4467 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4468 my $nr_line = 0;
4470 if (my $l = $c->{l}) {
4471 while ($l->[$#$l] eq "\n" && $#$l > 0
4472 && $l->[($#$l - 1)] eq "\n") {
4473 pop @$l;
4475 $nr_line = scalar @$l;
4476 if (!$nr_line) {
4477 print "1 line\n\n\n";
4478 } else {
4479 if ($nr_line == 1) {
4480 $nr_line = '1 line';
4481 } else {
4482 $nr_line .= ' lines';
4484 print $nr_line, "\n";
4485 show_commit_changed_paths($c);
4486 print "\n";
4487 print $_ foreach @$l;
4489 } else {
4490 print "1 line\n";
4491 show_commit_changed_paths($c);
4492 print "\n";
4495 foreach my $x (qw/raw stat diff/) {
4496 if ($c->{$x}) {
4497 print "\n";
4498 print $_ foreach @{$c->{$x}}
4503 sub cmd_show_log {
4504 my (@args) = @_;
4505 my ($r_min, $r_max);
4506 my $r_last = -1; # prevent dupes
4507 set_local_timezone();
4508 if (defined $::_revision) {
4509 if ($::_revision =~ /^(\d+):(\d+)$/) {
4510 ($r_min, $r_max) = ($1, $2);
4511 } elsif ($::_revision =~ /^\d+$/) {
4512 $r_min = $r_max = $::_revision;
4513 } else {
4514 ::fatal "-r$::_revision is not supported, use ",
4515 "standard 'git log' arguments instead";
4519 config_pager();
4520 @args = git_svn_log_cmd($r_min, $r_max, @args);
4521 if (!@args) {
4522 print commit_log_separator unless $incremental || $oneline;
4523 return;
4525 my $log = command_output_pipe(@args);
4526 run_pager();
4527 my (@k, $c, $d, $stat);
4528 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4529 while (<$log>) {
4530 if (/^${esc_color}commit -?($::sha1_short)/o) {
4531 my $cmt = $1;
4532 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4533 $r_last = $c->{r};
4534 process_commit($c, $r_min, $r_max, \@k) or
4535 goto out;
4537 $d = undef;
4538 $c = { c => $cmt };
4539 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4540 get_author_info($c, $1, $2, $3);
4541 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4542 # ignore
4543 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4544 push @{$c->{raw}}, $_;
4545 } elsif (/^${esc_color}[ACRMDT]\t/) {
4546 # we could add $SVN->{svn_path} here, but that requires
4547 # remote access at the moment (repo_path_split)...
4548 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4549 push @{$c->{changed}}, $_;
4550 } elsif (/^${esc_color}diff /o) {
4551 $d = 1;
4552 push @{$c->{diff}}, $_;
4553 } elsif ($d) {
4554 push @{$c->{diff}}, $_;
4555 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4556 $esc_color*[\+\-]*$esc_color$/x) {
4557 $stat = 1;
4558 push @{$c->{stat}}, $_;
4559 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4560 push @{$c->{stat}}, $_;
4561 $stat = undef;
4562 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4563 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4564 } elsif (s/^${esc_color} //o) {
4565 push @{$c->{l}}, $_;
4568 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4569 $r_last = $c->{r};
4570 process_commit($c, $r_min, $r_max, \@k);
4572 if (@k) {
4573 ($r_min, $r_max) = ($r_max, $r_min);
4574 process_commit($_, $r_min, $r_max) foreach reverse @k;
4576 out:
4577 close $log;
4578 print commit_log_separator unless $incremental || $oneline;
4581 sub cmd_blame {
4582 my $path = pop;
4584 config_pager();
4585 run_pager();
4587 my ($fh, $ctx, $rev);
4589 if ($_git_format) {
4590 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4591 while (my $line = <$fh>) {
4592 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4593 # Uncommitted edits show up as a rev ID of
4594 # all zeros, which we can't look up with
4595 # cmt_metadata
4596 if ($1 !~ /^0+$/) {
4597 (undef, $rev, undef) =
4598 ::cmt_metadata($1);
4599 $rev = '0' if (!$rev);
4600 } else {
4601 $rev = '0';
4603 $rev = sprintf('%-10s', $rev);
4604 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4606 print $line;
4608 } else {
4609 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4610 '--', $path);
4611 my ($sha1);
4612 my %authors;
4613 while (my $line = <$fh>) {
4614 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4615 $sha1 = $1;
4616 (undef, $rev, undef) = ::cmt_metadata($1);
4617 $rev = '0' if (!$rev);
4619 elsif ($line =~ /^author (.*)/) {
4620 $authors{$rev} = $1;
4621 $authors{$rev} =~ s/\s/_/g;
4623 elsif ($line =~ /^\t(.*)$/) {
4624 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4628 command_close_pipe($fh, $ctx);
4631 package Git::SVN::Migration;
4632 # these version numbers do NOT correspond to actual version numbers
4633 # of git nor git-svn. They are just relative.
4635 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4637 # v1 layout: .git/$id/info/url, refs/remotes/$id
4639 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4641 # v3 layout: .git/svn/$id, refs/remotes/$id
4642 # - info/url may remain for backwards compatibility
4643 # - this is what we migrate up to this layout automatically,
4644 # - this will be used by git svn init on single branches
4645 # v3.1 layout (auto migrated):
4646 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4647 # for backwards compatibility
4649 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4650 # - this is only created for newly multi-init-ed
4651 # repositories. Similar in spirit to the
4652 # --use-separate-remotes option in git-clone (now default)
4653 # - we do not automatically migrate to this (following
4654 # the example set by core git)
4656 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4657 # - newer, more-efficient format that uses 24-bytes per record
4658 # with no filler space.
4659 # - use xxd -c24 < .rev_map.$UUID to view and debug
4660 # - This is a one-way migration, repositories updated to the
4661 # new format will not be able to use old git-svn without
4662 # rebuilding the .rev_db. Rebuilding the rev_db is not
4663 # possible if noMetadata or useSvmProps are set; but should
4664 # be no problem for users that use the (sensible) defaults.
4665 use strict;
4666 use warnings;
4667 use Carp qw/croak/;
4668 use File::Path qw/mkpath/;
4669 use File::Basename qw/dirname basename/;
4670 use vars qw/$_minimize/;
4672 sub migrate_from_v0 {
4673 my $git_dir = $ENV{GIT_DIR};
4674 return undef unless -d $git_dir;
4675 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4676 my $migrated = 0;
4677 while (<$fh>) {
4678 chomp;
4679 my ($id, $orig_ref) = ($_, $_);
4680 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4681 next unless -f "$git_dir/$id/info/url";
4682 my $new_ref = "refs/remotes/$id";
4683 if (::verify_ref("$new_ref^0")) {
4684 print STDERR "W: $orig_ref is probably an old ",
4685 "branch used by an ancient version of ",
4686 "git-svn.\n",
4687 "However, $new_ref also exists.\n",
4688 "We will not be able ",
4689 "to use this branch until this ",
4690 "ambiguity is resolved.\n";
4691 next;
4693 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4694 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4695 command_noisy('update-ref', $new_ref, $orig_ref);
4696 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4697 $migrated++;
4699 command_close_pipe($fh, $ctx);
4700 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4701 $migrated;
4704 sub migrate_from_v1 {
4705 my $git_dir = $ENV{GIT_DIR};
4706 my $migrated = 0;
4707 return $migrated unless -d $git_dir;
4708 my $svn_dir = "$git_dir/svn";
4710 # just in case somebody used 'svn' as their $id at some point...
4711 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4713 print STDERR "Migrating from a git-svn v1 layout...\n";
4714 mkpath([$svn_dir]);
4715 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4716 "$svn_dir\n\t(required for this version ",
4717 "($::VERSION) of git-svn) does not exist.\n";
4718 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4719 while (<$fh>) {
4720 my $x = $_;
4721 next unless $x =~ s#^refs/remotes/##;
4722 chomp $x;
4723 next unless -f "$git_dir/$x/info/url";
4724 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4725 next unless $u;
4726 my $dn = dirname("$git_dir/svn/$x");
4727 mkpath([$dn]) unless -d $dn;
4728 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4729 mkpath(["$git_dir/svn/svn"]);
4730 print STDERR " - $git_dir/$x/info => ",
4731 "$git_dir/svn/$x/info\n";
4732 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4733 croak "$!: $x";
4734 # don't worry too much about these, they probably
4735 # don't exist with repos this old (save for index,
4736 # and we can easily regenerate that)
4737 foreach my $f (qw/unhandled.log index .rev_db/) {
4738 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4740 } else {
4741 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4742 rename "$git_dir/$x", "$git_dir/svn/$x" or
4743 croak "$!: $x";
4745 $migrated++;
4747 command_close_pipe($fh, $ctx);
4748 print STDERR "Done migrating from a git-svn v1 layout\n";
4749 $migrated;
4752 sub read_old_urls {
4753 my ($l_map, $pfx, $path) = @_;
4754 my @dir;
4755 foreach (<$path/*>) {
4756 if (-r "$_/info/url") {
4757 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4758 my $ref_id = $pfx . basename $_;
4759 my $url = ::file_to_s("$_/info/url");
4760 $l_map->{$ref_id} = $url;
4761 } elsif (-d $_) {
4762 push @dir, $_;
4765 foreach (@dir) {
4766 my $x = $_;
4767 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4768 read_old_urls($l_map, $x, $_);
4772 sub migrate_from_v2 {
4773 my @cfg = command(qw/config -l/);
4774 return if grep /^svn-remote\..+\.url=/, @cfg;
4775 my %l_map;
4776 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4777 my $migrated = 0;
4779 foreach my $ref_id (sort keys %l_map) {
4780 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4781 if ($@) {
4782 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4784 $migrated++;
4786 $migrated;
4789 sub minimize_connections {
4790 my $r = Git::SVN::read_all_remotes();
4791 my $new_urls = {};
4792 my $root_repos = {};
4793 foreach my $repo_id (keys %$r) {
4794 my $url = $r->{$repo_id}->{url} or next;
4795 my $fetch = $r->{$repo_id}->{fetch} or next;
4796 my $ra = Git::SVN::Ra->new($url);
4798 # skip existing cases where we already connect to the root
4799 if (($ra->{url} eq $ra->{repos_root}) ||
4800 ($ra->{repos_root} eq $repo_id)) {
4801 $root_repos->{$ra->{url}} = $repo_id;
4802 next;
4805 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4806 my $root_path = $ra->{url};
4807 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4808 foreach my $path (keys %$fetch) {
4809 my $ref_id = $fetch->{$path};
4810 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4812 # make sure we can read when connecting to
4813 # a higher level of a repository
4814 my ($last_rev, undef) = $gs->last_rev_commit;
4815 if (!defined $last_rev) {
4816 $last_rev = eval {
4817 $root_ra->get_latest_revnum;
4819 next if $@;
4821 my $new = $root_path;
4822 $new .= length $path ? "/$path" : '';
4823 eval {
4824 $root_ra->get_log([$new], $last_rev, $last_rev,
4825 0, 0, 1, sub { });
4827 next if $@;
4828 $new_urls->{$ra->{repos_root}}->{$new} =
4829 { ref_id => $ref_id,
4830 old_repo_id => $repo_id,
4831 old_path => $path };
4835 my @emptied;
4836 foreach my $url (keys %$new_urls) {
4837 # see if we can re-use an existing [svn-remote "repo_id"]
4838 # instead of creating a(n ugly) new section:
4839 my $repo_id = $root_repos->{$url} || $url;
4841 my $fetch = $new_urls->{$url};
4842 foreach my $path (keys %$fetch) {
4843 my $x = $fetch->{$path};
4844 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4845 my $pfx = "svn-remote.$x->{old_repo_id}";
4847 my $old_fetch = quotemeta("$x->{old_path}:".
4848 "refs/remotes/$x->{ref_id}");
4849 command_noisy(qw/config --unset/,
4850 "$pfx.fetch", '^'. $old_fetch . '$');
4851 delete $r->{$x->{old_repo_id}}->
4852 {fetch}->{$x->{old_path}};
4853 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4854 command_noisy(qw/config --unset/,
4855 "$pfx.url");
4856 push @emptied, $x->{old_repo_id}
4860 if (@emptied) {
4861 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4862 "$ENV{GIT_DIR}/config";
4863 print STDERR <<EOF;
4864 The following [svn-remote] sections in your config file ($file) are empty
4865 and can be safely removed:
4867 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4871 sub migration_check {
4872 migrate_from_v0();
4873 migrate_from_v1();
4874 migrate_from_v2();
4875 minimize_connections() if $_minimize;
4878 package Git::IndexInfo;
4879 use strict;
4880 use warnings;
4881 use Git qw/command_input_pipe command_close_pipe/;
4883 sub new {
4884 my ($class) = @_;
4885 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4886 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4889 sub remove {
4890 my ($self, $path) = @_;
4891 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4892 return ++$self->{nr};
4894 undef;
4897 sub update {
4898 my ($self, $mode, $hash, $path) = @_;
4899 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4900 return ++$self->{nr};
4902 undef;
4905 sub DESTROY {
4906 my ($self) = @_;
4907 command_close_pipe($self->{gui}, $self->{ctx});
4910 package Git::SVN::GlobSpec;
4911 use strict;
4912 use warnings;
4914 sub new {
4915 my ($class, $glob) = @_;
4916 my $re = $glob;
4917 $re =~ s!/+$!!g; # no need for trailing slashes
4918 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4919 my ($left, $right) = ($1, $2);
4920 if ($nr > 1) {
4921 die "Only one '*' wildcard expansion ",
4922 "is supported (got $nr): '$glob'\n";
4923 } elsif ($nr == 0) {
4924 die "One '*' is needed for glob: '$glob'\n";
4926 $re = quotemeta($left) . $re . quotemeta($right);
4927 if (length $left && !($left =~ s!/+$!!g)) {
4928 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4930 if (length $right && !($right =~ s!^/+!!g)) {
4931 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4933 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4934 bless { left => $left, right => $right, left_regex => $left_re,
4935 regex => qr/$re/, glob => $glob }, $class;
4938 sub full_path {
4939 my ($self, $path) = @_;
4940 return (length $self->{left} ? "$self->{left}/" : '') .
4941 $path . (length $self->{right} ? "/$self->{right}" : '');
4944 __END__
4946 Data structures:
4949 $remotes = { # returned by read_all_remotes()
4950 'svn' => {
4951 # svn-remote.svn.url=https://svn.musicpd.org
4952 url => 'https://svn.musicpd.org',
4953 # svn-remote.svn.fetch=mpd/trunk:trunk
4954 fetch => {
4955 'mpd/trunk' => 'trunk',
4957 # svn-remote.svn.tags=mpd/tags/*:tags/*
4958 tags => {
4959 path => {
4960 left => 'mpd/tags',
4961 right => '',
4962 regex => qr!mpd/tags/([^/]+)$!,
4963 glob => 'tags/*',
4965 ref => {
4966 left => 'tags',
4967 right => '',
4968 regex => qr!tags/([^/]+)$!,
4969 glob => 'tags/*',
4975 $log_entry hashref as returned by libsvn_log_entry()
4977 log => 'whitespace-formatted log entry
4978 ', # trailing newline is preserved
4979 revision => '8', # integer
4980 date => '2004-02-24T17:01:44.108345Z', # commit date
4981 author => 'committer name'
4985 # this is generated by generate_diff();
4986 @mods = array of diff-index line hashes, each element represents one line
4987 of diff-index output
4989 diff-index line ($m hash)
4991 mode_a => first column of diff-index output, no leading ':',
4992 mode_b => second column of diff-index output,
4993 sha1_b => sha1sum of the final blob,
4994 chg => change type [MCRADT],
4995 file_a => original file name of a file (iff chg is 'C' or 'R')
4996 file_b => new/current file name of a file (any chg)
5000 # retval of read_url_paths{,_all}();
5001 $l_map = {
5002 # repository root url
5003 'https://svn.musicpd.org' => {
5004 # repository path # GIT_SVN_ID
5005 'mpd/trunk' => 'trunk',
5006 'mpd/tags/0.11.5' => 'tags/0.11.5',
5010 Notes:
5011 I don't trust the each() function on unless I created %hash myself
5012 because the internal iterator may not have started at base.