git-svn: Add per-svn-remote ignore-paths config
[git.git] / git-svn.perl
blob279847921ba4c2333af299535d41cb4b2d3bc750
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 command_bidi_pipe command_close_bidi_pipe/) {
52 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
53 Git::SVN::Migration Git::SVN::Log Git::SVN),
54 __PACKAGE__) {
55 *{"${package}::$_"} = \&{"Git::$_"};
60 my ($SVN);
62 $sha1 = qr/[a-f\d]{40}/;
63 $sha1_short = qr/[a-f\d]{4,40}/;
64 my ($_stdin, $_help, $_edit,
65 $_message, $_file,
66 $_template, $_shared,
67 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
68 $_merge, $_strategy, $_dry_run, $_local,
69 $_prefix, $_no_checkout, $_url, $_verbose,
70 $_git_format, $_commit_url, $_tag);
71 $Git::SVN::_follow_parent = 1;
72 $_q ||= 0;
73 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
74 'config-dir=s' => \$Git::SVN::Ra::config_dir,
75 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
76 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
77 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
78 'authors-file|A=s' => \$_authors,
79 'repack:i' => \$Git::SVN::_repack,
80 'noMetadata' => \$Git::SVN::_no_metadata,
81 'useSvmProps' => \$Git::SVN::_use_svm_props,
82 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
83 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
84 'no-checkout' => \$_no_checkout,
85 'quiet|q+' => \$_q,
86 'repack-flags|repack-args|repack-opts=s' =>
87 \$Git::SVN::_repack_flags,
88 'use-log-author' => \$Git::SVN::_use_log_author,
89 'add-author-from' => \$Git::SVN::_add_author_from,
90 'localtime' => \$Git::SVN::_localtime,
91 %remote_opts );
93 my ($_trunk, $_tags, $_branches, $_stdlayout);
94 my %icv;
95 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
96 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
97 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
98 'stdlayout|s' => \$_stdlayout,
99 'minimize-url|m' => \$Git::SVN::_minimize_url,
100 'no-metadata' => sub { $icv{noMetadata} = 1 },
101 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
102 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
103 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
104 %remote_opts );
105 my %cmt_opts = ( 'edit|e' => \$_edit,
106 'rmdir' => \$SVN::Git::Editor::_rmdir,
107 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
108 'l=i' => \$SVN::Git::Editor::_rename_limit,
109 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
112 my %cmd = (
113 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
114 { 'revision|r=s' => \$_revision,
115 'fetch-all|all' => \$_fetch_all,
116 'parent|p' => \$_fetch_parent,
117 %fc_opts } ],
118 clone => [ \&cmd_clone, "Initialize and fetch revisions",
119 { 'revision|r=s' => \$_revision,
120 %fc_opts, %init_opts } ],
121 init => [ \&cmd_init, "Initialize a repo for tracking" .
122 " (requires URL argument)",
123 \%init_opts ],
124 'multi-init' => [ \&cmd_multi_init,
125 "Deprecated alias for ".
126 "'$0 init -T<trunk> -b<branches> -t<tags>'",
127 \%init_opts ],
128 dcommit => [ \&cmd_dcommit,
129 'Commit several diffs to merge with upstream',
130 { 'merge|m|M' => \$_merge,
131 'strategy|s=s' => \$_strategy,
132 'verbose|v' => \$_verbose,
133 'dry-run|n' => \$_dry_run,
134 'fetch-all|all' => \$_fetch_all,
135 'commit-url=s' => \$_commit_url,
136 'revision|r=i' => \$_revision,
137 'no-rebase' => \$_no_rebase,
138 %cmt_opts, %fc_opts } ],
139 branch => [ \&cmd_branch,
140 'Create a branch in the SVN repository',
141 { 'message|m=s' => \$_message,
142 'dry-run|n' => \$_dry_run,
143 'tag|t' => \$_tag } ],
144 tag => [ sub { $_tag = 1; cmd_branch(@_) },
145 'Create a tag in the SVN repository',
146 { 'message|m=s' => \$_message,
147 'dry-run|n' => \$_dry_run } ],
148 'set-tree' => [ \&cmd_set_tree,
149 "Set an SVN repository to a git tree-ish",
150 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
151 'create-ignore' => [ \&cmd_create_ignore,
152 'Create a .gitignore per svn:ignore',
153 { 'revision|r=i' => \$_revision
154 } ],
155 'propget' => [ \&cmd_propget,
156 'Print the value of a property on a file or directory',
157 { 'revision|r=i' => \$_revision } ],
158 'proplist' => [ \&cmd_proplist,
159 'List all properties of a file or directory',
160 { 'revision|r=i' => \$_revision } ],
161 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
162 { 'revision|r=i' => \$_revision
163 } ],
164 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
165 { 'revision|r=i' => \$_revision
166 } ],
167 'multi-fetch' => [ \&cmd_multi_fetch,
168 "Deprecated alias for $0 fetch --all",
169 { 'revision|r=s' => \$_revision, %fc_opts } ],
170 'migrate' => [ sub { },
171 # no-op, we automatically run this anyways,
172 'Migrate configuration/metadata/layout from
173 previous versions of git-svn',
174 { 'minimize' => \$Git::SVN::Migration::_minimize,
175 %remote_opts } ],
176 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
177 { 'limit=i' => \$Git::SVN::Log::limit,
178 'revision|r=s' => \$_revision,
179 'verbose|v' => \$Git::SVN::Log::verbose,
180 'incremental' => \$Git::SVN::Log::incremental,
181 'oneline' => \$Git::SVN::Log::oneline,
182 'show-commit' => \$Git::SVN::Log::show_commit,
183 'non-recursive' => \$Git::SVN::Log::non_recursive,
184 'authors-file|A=s' => \$_authors,
185 'color' => \$Git::SVN::Log::color,
186 'pager=s' => \$Git::SVN::Log::pager
187 } ],
188 'find-rev' => [ \&cmd_find_rev,
189 "Translate between SVN revision numbers and tree-ish",
190 {} ],
191 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
192 { 'merge|m|M' => \$_merge,
193 'verbose|v' => \$_verbose,
194 'strategy|s=s' => \$_strategy,
195 'local|l' => \$_local,
196 'fetch-all|all' => \$_fetch_all,
197 'dry-run|n' => \$_dry_run,
198 %fc_opts } ],
199 'commit-diff' => [ \&cmd_commit_diff,
200 'Commit a diff between two trees',
201 { 'message|m=s' => \$_message,
202 'file|F=s' => \$_file,
203 'revision|r=s' => \$_revision,
204 %cmt_opts } ],
205 'info' => [ \&cmd_info,
206 "Show info about the latest SVN revision
207 on the current branch",
208 { 'url' => \$_url, } ],
209 'blame' => [ \&Git::SVN::Log::cmd_blame,
210 "Show what revision and author last modified each line of a file",
211 { 'git-format' => \$_git_format } ],
214 my $cmd;
215 for (my $i = 0; $i < @ARGV; $i++) {
216 if (defined $cmd{$ARGV[$i]}) {
217 $cmd = $ARGV[$i];
218 splice @ARGV, $i, 1;
219 last;
223 # make sure we're always running at the top-level working directory
224 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
225 unless (-d $ENV{GIT_DIR}) {
226 if ($git_dir_user_set) {
227 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
228 "but it is not a directory\n";
230 my $git_dir = delete $ENV{GIT_DIR};
231 my $cdup = undef;
232 git_cmd_try {
233 $cdup = command_oneline(qw/rev-parse --show-cdup/);
234 $git_dir = '.' unless ($cdup);
235 chomp $cdup if ($cdup);
236 $cdup = "." unless ($cdup && length $cdup);
237 } "Already at toplevel, but $git_dir not found\n";
238 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
239 unless (-d $git_dir) {
240 die "$git_dir still not found after going to ",
241 "'$cdup'\n";
243 $ENV{GIT_DIR} = $git_dir;
245 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
248 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
250 read_repo_config(\%opts);
251 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
252 Getopt::Long::Configure('pass_through');
254 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
255 'minimize-connections' => \$Git::SVN::Migration::_minimize,
256 'id|i=s' => \$Git::SVN::default_ref_id,
257 'svn-remote|remote|R=s' => sub {
258 $Git::SVN::no_reuse_existing = 1;
259 $Git::SVN::default_repo_id = $_[1] });
260 exit 1 if (!$rv && $cmd && $cmd ne 'log');
262 usage(0) if $_help;
263 version() if $_version;
264 usage(1) unless defined $cmd;
265 load_authors() if $_authors;
267 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
268 Git::SVN::Migration::migration_check();
270 Git::SVN::init_vars();
271 eval {
272 Git::SVN::verify_remotes_sanity();
273 $cmd{$cmd}->[0]->(@ARGV);
275 fatal $@ if $@;
276 post_fetch_checkout();
277 exit 0;
279 ####################### primary functions ######################
280 sub usage {
281 my $exit = shift || 0;
282 my $fd = $exit ? \*STDERR : \*STDOUT;
283 print $fd <<"";
284 git-svn - bidirectional operations between a single Subversion tree and git
285 Usage: git svn <command> [options] [arguments]\n
287 print $fd "Available commands:\n" unless $cmd;
289 foreach (sort keys %cmd) {
290 next if $cmd && $cmd ne $_;
291 next if /^multi-/; # don't show deprecated commands
292 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
293 foreach (sort keys %{$cmd{$_}->[2]}) {
294 # mixed-case options are for .git/config only
295 next if /[A-Z]/ && /^[a-z]+$/i;
296 # prints out arguments as they should be passed:
297 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
298 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
299 "--$_" : "-$_" }
300 split /\|/,$_)," $x\n";
303 print $fd <<"";
304 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
305 arbitrary identifier if you're tracking multiple SVN branches/repositories in
306 one git repository and want to keep them separate. See git-svn(1) for more
307 information.
309 exit $exit;
312 sub version {
313 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
314 exit 0;
317 sub do_git_init_db {
318 unless (-d $ENV{GIT_DIR}) {
319 my @init_db = ('init');
320 push @init_db, "--template=$_template" if defined $_template;
321 if (defined $_shared) {
322 if ($_shared =~ /[a-z]/) {
323 push @init_db, "--shared=$_shared";
324 } else {
325 push @init_db, "--shared";
328 command_noisy(@init_db);
329 $_repository = Git->repository(Repository => ".git");
331 my $set;
332 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
333 foreach my $i (keys %icv) {
334 die "'$set' and '$i' cannot both be set\n" if $set;
335 next unless defined $icv{$i};
336 command_noisy('config', "$pfx.$i", $icv{$i});
337 $set = $i;
341 sub init_subdir {
342 my $repo_path = shift or return;
343 mkpath([$repo_path]) unless -d $repo_path;
344 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
345 $ENV{GIT_DIR} = '.git';
346 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
349 sub cmd_clone {
350 my ($url, $path) = @_;
351 if (!defined $path &&
352 (defined $_trunk || defined $_branches || defined $_tags ||
353 defined $_stdlayout) &&
354 $url !~ m#^[a-z\+]+://#) {
355 $path = $url;
357 $path = basename($url) if !defined $path || !length $path;
358 cmd_init($url, $path);
359 Git::SVN::fetch_all($Git::SVN::default_repo_id);
362 sub cmd_init {
363 if (defined $_stdlayout) {
364 $_trunk = 'trunk' if (!defined $_trunk);
365 $_tags = 'tags' if (!defined $_tags);
366 $_branches = 'branches' if (!defined $_branches);
368 if (defined $_trunk || defined $_branches || defined $_tags) {
369 return cmd_multi_init(@_);
371 my $url = shift or die "SVN repository location required ",
372 "as a command-line argument\n";
373 init_subdir(@_);
374 do_git_init_db();
376 Git::SVN->init($url);
379 sub cmd_fetch {
380 if (grep /^\d+=./, @_) {
381 die "'<rev>=<commit>' fetch arguments are ",
382 "no longer supported.\n";
384 my ($remote) = @_;
385 if (@_ > 1) {
386 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
388 if ($_fetch_parent) {
389 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
390 unless ($gs) {
391 die "Unable to determine upstream SVN information from ",
392 "working tree history\n";
394 # just fetch, don't checkout.
395 $_no_checkout = 'true';
396 $_fetch_all ? $gs->fetch_all : $gs->fetch;
397 } elsif ($_fetch_all) {
398 cmd_multi_fetch();
399 } else {
400 $remote ||= $Git::SVN::default_repo_id;
401 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
405 sub cmd_set_tree {
406 my (@commits) = @_;
407 if ($_stdin || !@commits) {
408 print "Reading from stdin...\n";
409 @commits = ();
410 while (<STDIN>) {
411 if (/\b($sha1_short)\b/o) {
412 unshift @commits, $1;
416 my @revs;
417 foreach my $c (@commits) {
418 my @tmp = command('rev-parse',$c);
419 if (scalar @tmp == 1) {
420 push @revs, $tmp[0];
421 } elsif (scalar @tmp > 1) {
422 push @revs, reverse(command('rev-list',@tmp));
423 } else {
424 fatal "Failed to rev-parse $c";
427 my $gs = Git::SVN->new;
428 my ($r_last, $cmt_last) = $gs->last_rev_commit;
429 $gs->fetch;
430 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
431 fatal "There are new revisions that were fetched ",
432 "and need to be merged (or acknowledged) ",
433 "before committing.\nlast rev: $r_last\n",
434 " current: $gs->{last_rev}";
436 $gs->set_tree($_) foreach @revs;
437 print "Done committing ",scalar @revs," revisions to SVN\n";
438 unlink $gs->{index};
441 sub cmd_dcommit {
442 my $head = shift;
443 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
444 'Cannot dcommit with a dirty index. Commit your changes first, '
445 . "or stash them with `git stash'.\n";
446 $head ||= 'HEAD';
447 my @refs;
448 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
449 unless ($gs) {
450 die "Unable to determine upstream SVN information from ",
451 "$head history.\nPerhaps the repository is empty.";
454 if (defined $_commit_url) {
455 $url = $_commit_url;
456 } else {
457 $url = eval { command_oneline('config', '--get',
458 "svn-remote.$gs->{repo_id}.commiturl") };
459 if (!$url) {
460 $url = $gs->full_url
464 my $last_rev = $_revision if defined $_revision;
465 if ($url) {
466 print "Committing to $url ...\n";
468 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
469 if ($_no_rebase && scalar(@$linear_refs) > 1) {
470 warn "Attempting to commit more than one change while ",
471 "--no-rebase is enabled.\n",
472 "If these changes depend on each other, re-running ",
473 "without --no-rebase may be required."
475 my $expect_url = $url;
476 Git::SVN::remove_username($expect_url);
477 while (1) {
478 my $d = shift @$linear_refs or last;
479 unless (defined $last_rev) {
480 (undef, $last_rev, undef) = cmt_metadata("$d~1");
481 unless (defined $last_rev) {
482 fatal "Unable to extract revision information ",
483 "from commit $d~1";
486 if ($_dry_run) {
487 print "diff-tree $d~1 $d\n";
488 } else {
489 my $cmt_rev;
490 my %ed_opts = ( r => $last_rev,
491 log => get_commit_entry($d)->{log},
492 ra => Git::SVN::Ra->new($url),
493 config => SVN::Core::config_get_config(
494 $Git::SVN::Ra::config_dir
496 tree_a => "$d~1",
497 tree_b => $d,
498 editor_cb => sub {
499 print "Committed r$_[0]\n";
500 $cmt_rev = $_[0];
502 svn_path => '');
503 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
504 print "No changes\n$d~1 == $d\n";
505 } elsif ($parents->{$d} && @{$parents->{$d}}) {
506 $gs->{inject_parents_dcommit}->{$cmt_rev} =
507 $parents->{$d};
509 $_fetch_all ? $gs->fetch_all : $gs->fetch;
510 $last_rev = $cmt_rev;
511 next if $_no_rebase;
513 # we always want to rebase against the current HEAD,
514 # not any head that was passed to us
515 my @diff = command('diff-tree', $d,
516 $gs->refname, '--');
517 my @finish;
518 if (@diff) {
519 @finish = rebase_cmd();
520 print STDERR "W: $d and ", $gs->refname,
521 " differ, using @finish:\n",
522 join("\n", @diff), "\n";
523 } else {
524 print "No changes between current HEAD and ",
525 $gs->refname,
526 "\nResetting to the latest ",
527 $gs->refname, "\n";
528 @finish = qw/reset --mixed/;
530 command_noisy(@finish, $gs->refname);
531 if (@diff) {
532 @refs = ();
533 my ($url_, $rev_, $uuid_, $gs_) =
534 working_head_info($head, \@refs);
535 my ($linear_refs_, $parents_) =
536 linearize_history($gs_, \@refs);
537 if (scalar(@$linear_refs) !=
538 scalar(@$linear_refs_)) {
539 fatal "# of revisions changed ",
540 "\nbefore:\n",
541 join("\n", @$linear_refs),
542 "\n\nafter:\n",
543 join("\n", @$linear_refs_), "\n",
544 'If you are attempting to commit ',
545 "merges, try running:\n\t",
546 'git rebase --interactive',
547 '--preserve-merges ',
548 $gs->refname,
549 "\nBefore dcommitting";
551 if ($url_ ne $expect_url) {
552 fatal "URL mismatch after rebase: ",
553 "$url_ != $expect_url";
555 if ($uuid_ ne $uuid) {
556 fatal "uuid mismatch after rebase: ",
557 "$uuid_ != $uuid";
559 # remap parents
560 my (%p, @l, $i);
561 for ($i = 0; $i < scalar @$linear_refs; $i++) {
562 my $new = $linear_refs_->[$i] or next;
563 $p{$new} =
564 $parents->{$linear_refs->[$i]};
565 push @l, $new;
567 $parents = \%p;
568 $linear_refs = \@l;
572 unlink $gs->{index};
575 sub cmd_branch {
576 my ($branch_name, $head) = @_;
578 unless (defined $branch_name && length $branch_name) {
579 die(($_tag ? "tag" : "branch") . " name required\n");
581 $head ||= 'HEAD';
583 my ($src, $rev, undef, $gs) = working_head_info($head);
585 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
586 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
587 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
588 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
590 my $ctx = SVN::Client->new(
591 auth => Git::SVN::Ra::_auth_providers(),
592 log_msg => sub {
593 ${ $_[0] } = defined $_message
594 ? $_message
595 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
596 . $branch_name;
600 eval {
601 $ctx->ls($dst, 'HEAD', 0);
602 } and die "branch ${branch_name} already exists\n";
604 print "Copying ${src} at r${rev} to ${dst}...\n";
605 $ctx->copy($src, $rev, $dst)
606 unless $_dry_run;
608 $gs->fetch_all;
611 sub cmd_find_rev {
612 my $revision_or_hash = shift or die "SVN or git revision required ",
613 "as a command-line argument\n";
614 my $result;
615 if ($revision_or_hash =~ /^r\d+$/) {
616 my $head = shift;
617 $head ||= 'HEAD';
618 my @refs;
619 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
620 unless ($gs) {
621 die "Unable to determine upstream SVN information from ",
622 "$head history\n";
624 my $desired_revision = substr($revision_or_hash, 1);
625 $result = $gs->rev_map_get($desired_revision, $uuid);
626 } else {
627 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
628 $result = $rev;
630 print "$result\n" if $result;
633 sub cmd_rebase {
634 command_noisy(qw/update-index --refresh/);
635 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
636 unless ($gs) {
637 die "Unable to determine upstream SVN information from ",
638 "working tree history\n";
640 if ($_dry_run) {
641 print "Remote Branch: " . $gs->refname . "\n";
642 print "SVN URL: " . $url . "\n";
643 return;
645 if (command(qw/diff-index HEAD --/)) {
646 print STDERR "Cannot rebase with uncommited changes:\n";
647 command_noisy('status');
648 exit 1;
650 unless ($_local) {
651 # rebase will checkout for us, so no need to do it explicitly
652 $_no_checkout = 'true';
653 $_fetch_all ? $gs->fetch_all : $gs->fetch;
655 command_noisy(rebase_cmd(), $gs->refname);
658 sub cmd_show_ignore {
659 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
660 $gs ||= Git::SVN->new;
661 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
662 $gs->prop_walk($gs->{path}, $r, sub {
663 my ($gs, $path, $props) = @_;
664 print STDOUT "\n# $path\n";
665 my $s = $props->{'svn:ignore'} or return;
666 $s =~ s/[\r\n]+/\n/g;
667 chomp $s;
668 $s =~ s#^#$path#gm;
669 print STDOUT "$s\n";
673 sub cmd_show_externals {
674 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
675 $gs ||= Git::SVN->new;
676 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
677 $gs->prop_walk($gs->{path}, $r, sub {
678 my ($gs, $path, $props) = @_;
679 print STDOUT "\n# $path\n";
680 my $s = $props->{'svn:externals'} or return;
681 $s =~ s/[\r\n]+/\n/g;
682 chomp $s;
683 $s =~ s#^#$path#gm;
684 print STDOUT "$s\n";
688 sub cmd_create_ignore {
689 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
690 $gs ||= Git::SVN->new;
691 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
692 $gs->prop_walk($gs->{path}, $r, sub {
693 my ($gs, $path, $props) = @_;
694 # $path is of the form /path/to/dir/
695 $path = '.' . $path;
696 # SVN can have attributes on empty directories,
697 # which git won't track
698 mkpath([$path]) unless -d $path;
699 my $ignore = $path . '.gitignore';
700 my $s = $props->{'svn:ignore'} or return;
701 open(GITIGNORE, '>', $ignore)
702 or fatal("Failed to open `$ignore' for writing: $!");
703 $s =~ s/[\r\n]+/\n/g;
704 chomp $s;
705 # Prefix all patterns so that the ignore doesn't apply
706 # to sub-directories.
707 $s =~ s#^#/#gm;
708 print GITIGNORE "$s\n";
709 close(GITIGNORE)
710 or fatal("Failed to close `$ignore': $!");
711 command_noisy('add', '-f', $ignore);
715 sub canonicalize_path {
716 my ($path) = @_;
717 my $dot_slash_added = 0;
718 if (substr($path, 0, 1) ne "/") {
719 $path = "./" . $path;
720 $dot_slash_added = 1;
722 # File::Spec->canonpath doesn't collapse x/../y into y (for a
723 # good reason), so let's do this manually.
724 $path =~ s#/+#/#g;
725 $path =~ s#/\.(?:/|$)#/#g;
726 $path =~ s#/[^/]+/\.\.##g;
727 $path =~ s#/$##g;
728 $path =~ s#^\./## if $dot_slash_added;
729 $path =~ s#^/##;
730 $path =~ s#^\.$##;
731 return $path;
734 # get_svnprops(PATH)
735 # ------------------
736 # Helper for cmd_propget and cmd_proplist below.
737 sub get_svnprops {
738 my $path = shift;
739 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
740 $gs ||= Git::SVN->new;
742 # prefix THE PATH by the sub-directory from which the user
743 # invoked us.
744 $path = $cmd_dir_prefix . $path;
745 fatal("No such file or directory: $path") unless -e $path;
746 my $is_dir = -d $path ? 1 : 0;
747 $path = $gs->{path} . '/' . $path;
749 # canonicalize the path (otherwise libsvn will abort or fail to
750 # find the file)
751 $path = canonicalize_path($path);
753 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
754 my $props;
755 if ($is_dir) {
756 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
758 else {
759 (undef, $props) = $gs->ra->get_file($path, $r, undef);
761 return $props;
764 # cmd_propget (PROP, PATH)
765 # ------------------------
766 # Print the SVN property PROP for PATH.
767 sub cmd_propget {
768 my ($prop, $path) = @_;
769 $path = '.' if not defined $path;
770 usage(1) if not defined $prop;
771 my $props = get_svnprops($path);
772 if (not defined $props->{$prop}) {
773 fatal("`$path' does not have a `$prop' SVN property.");
775 print $props->{$prop} . "\n";
778 # cmd_proplist (PATH)
779 # -------------------
780 # Print the list of SVN properties for PATH.
781 sub cmd_proplist {
782 my $path = shift;
783 $path = '.' if not defined $path;
784 my $props = get_svnprops($path);
785 print "Properties on '$path':\n";
786 foreach (sort keys %{$props}) {
787 print " $_\n";
791 sub cmd_multi_init {
792 my $url = shift;
793 unless (defined $_trunk || defined $_branches || defined $_tags) {
794 usage(1);
797 # there are currently some bugs that prevent multi-init/multi-fetch
798 # setups from working well without this.
799 $Git::SVN::_minimize_url = 1;
801 $_prefix = '' unless defined $_prefix;
802 if (defined $url) {
803 $url =~ s#/+$##;
804 init_subdir(@_);
806 do_git_init_db();
807 if (defined $_trunk) {
808 my $trunk_ref = $_prefix . 'trunk';
809 # try both old-style and new-style lookups:
810 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
811 unless ($gs_trunk) {
812 my ($trunk_url, $trunk_path) =
813 complete_svn_url($url, $_trunk);
814 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
815 undef, $trunk_ref);
818 return unless defined $_branches || defined $_tags;
819 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
820 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
821 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
824 sub cmd_multi_fetch {
825 my $remotes = Git::SVN::read_all_remotes();
826 foreach my $repo_id (sort keys %$remotes) {
827 if ($remotes->{$repo_id}->{url}) {
828 Git::SVN::fetch_all($repo_id, $remotes);
833 # this command is special because it requires no metadata
834 sub cmd_commit_diff {
835 my ($ta, $tb, $url) = @_;
836 my $usage = "Usage: $0 commit-diff -r<revision> ".
837 "<tree-ish> <tree-ish> [<URL>]";
838 fatal($usage) if (!defined $ta || !defined $tb);
839 my $svn_path = '';
840 if (!defined $url) {
841 my $gs = eval { Git::SVN->new };
842 if (!$gs) {
843 fatal("Needed URL or usable git-svn --id in ",
844 "the command-line\n", $usage);
846 $url = $gs->{url};
847 $svn_path = $gs->{path};
849 unless (defined $_revision) {
850 fatal("-r|--revision is a required argument\n", $usage);
852 if (defined $_message && defined $_file) {
853 fatal("Both --message/-m and --file/-F specified ",
854 "for the commit message.\n",
855 "I have no idea what you mean");
857 if (defined $_file) {
858 $_message = file_to_s($_file);
859 } else {
860 $_message ||= get_commit_entry($tb)->{log};
862 my $ra ||= Git::SVN::Ra->new($url);
863 my $r = $_revision;
864 if ($r eq 'HEAD') {
865 $r = $ra->get_latest_revnum;
866 } elsif ($r !~ /^\d+$/) {
867 die "revision argument: $r not understood by git-svn\n";
869 my %ed_opts = ( r => $r,
870 log => $_message,
871 ra => $ra,
872 tree_a => $ta,
873 tree_b => $tb,
874 editor_cb => sub { print "Committed r$_[0]\n" },
875 svn_path => $svn_path );
876 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
877 print "No changes\n$ta == $tb\n";
881 sub escape_uri_only {
882 my ($uri) = @_;
883 my @tmp;
884 foreach (split m{/}, $uri) {
885 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
886 push @tmp, $_;
888 join('/', @tmp);
891 sub escape_url {
892 my ($url) = @_;
893 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
894 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
895 $url = "$scheme://$domain$uri";
897 $url;
900 sub cmd_info {
901 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
902 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
903 if (exists $_[1]) {
904 die "Too many arguments specified\n";
907 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
909 if (!$file_type && !$diff_status) {
910 print STDERR "svn: '$path' is not under version control\n";
911 exit 1;
914 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
915 unless ($gs) {
916 die "Unable to determine upstream SVN information from ",
917 "working tree history\n";
920 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
921 $path = "." if $path eq "";
923 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
925 if ($_url) {
926 print escape_url($full_url), "\n";
927 return;
930 my $result = "Path: $path\n";
931 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
932 $result .= "URL: " . escape_url($full_url) . "\n";
934 eval {
935 my $repos_root = $gs->repos_root;
936 Git::SVN::remove_username($repos_root);
937 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
939 if ($@) {
940 $result .= "Repository Root: (offline)\n";
942 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
943 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
944 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
946 $result .= "Node Kind: " .
947 ($file_type eq "dir" ? "directory" : "file") . "\n";
949 my $schedule = $diff_status eq "A"
950 ? "add"
951 : ($diff_status eq "D" ? "delete" : "normal");
952 $result .= "Schedule: $schedule\n";
954 if ($diff_status eq "A") {
955 print $result, "\n";
956 return;
959 my ($lc_author, $lc_rev, $lc_date_utc);
960 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
961 my $log = command_output_pipe(@args);
962 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
963 while (<$log>) {
964 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
965 $lc_author = $1;
966 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
967 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
968 (undef, $lc_rev, undef) = ::extract_metadata($1);
971 close $log;
973 Git::SVN::Log::set_local_timezone();
975 $result .= "Last Changed Author: $lc_author\n";
976 $result .= "Last Changed Rev: $lc_rev\n";
977 $result .= "Last Changed Date: " .
978 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
980 if ($file_type ne "dir") {
981 my $text_last_updated_date =
982 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
983 $result .=
984 "Text Last Updated: " .
985 Git::SVN::Log::format_svn_date($text_last_updated_date) .
986 "\n";
987 my $checksum;
988 if ($diff_status eq "D") {
989 my ($fh, $ctx) =
990 command_output_pipe(qw(cat-file blob), "HEAD:$path");
991 if ($file_type eq "link") {
992 my $file_name = <$fh>;
993 $checksum = md5sum("link $file_name");
994 } else {
995 $checksum = md5sum($fh);
997 command_close_pipe($fh, $ctx);
998 } elsif ($file_type eq "link") {
999 my $file_name =
1000 command(qw(cat-file blob), "HEAD:$path");
1001 $checksum =
1002 md5sum("link " . $file_name);
1003 } else {
1004 open FILE, "<", $path or die $!;
1005 $checksum = md5sum(\*FILE);
1006 close FILE or die $!;
1008 $result .= "Checksum: " . $checksum . "\n";
1011 print $result, "\n";
1014 ########################### utility functions #########################
1016 sub rebase_cmd {
1017 my @cmd = qw/rebase/;
1018 push @cmd, '-v' if $_verbose;
1019 push @cmd, qw/--merge/ if $_merge;
1020 push @cmd, "--strategy=$_strategy" if $_strategy;
1021 @cmd;
1024 sub post_fetch_checkout {
1025 return if $_no_checkout;
1026 my $gs = $Git::SVN::_head or return;
1027 return if verify_ref('refs/heads/master^0');
1029 my $valid_head = verify_ref('HEAD^0');
1030 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1031 return if ($valid_head || !verify_ref('HEAD^0'));
1033 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1034 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1035 return if -f $index;
1037 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1038 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1039 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1040 print STDERR "Checked out HEAD:\n ",
1041 $gs->full_url, " r", $gs->last_rev, "\n";
1044 sub complete_svn_url {
1045 my ($url, $path) = @_;
1046 $path =~ s#/+$##;
1047 if ($path !~ m#^[a-z\+]+://#) {
1048 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1049 fatal("E: '$path' is not a complete URL ",
1050 "and a separate URL is not specified");
1052 return ($url, $path);
1054 return ($path, '');
1057 sub complete_url_ls_init {
1058 my ($ra, $repo_path, $switch, $pfx) = @_;
1059 unless ($repo_path) {
1060 print STDERR "W: $switch not specified\n";
1061 return;
1063 $repo_path =~ s#/+$##;
1064 if ($repo_path =~ m#^[a-z\+]+://#) {
1065 $ra = Git::SVN::Ra->new($repo_path);
1066 $repo_path = '';
1067 } else {
1068 $repo_path =~ s#^/+##;
1069 unless ($ra) {
1070 fatal("E: '$repo_path' is not a complete URL ",
1071 "and a separate URL is not specified");
1074 my $url = $ra->{url};
1075 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1076 my $k = "svn-remote.$gs->{repo_id}.url";
1077 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1078 if ($orig_url && ($orig_url ne $gs->{url})) {
1079 die "$k already set: $orig_url\n",
1080 "wanted to set to: $gs->{url}\n";
1082 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1083 my $remote_path = "$ra->{svn_path}/$repo_path";
1084 $remote_path =~ s#/+#/#g;
1085 $remote_path =~ s#^/##g;
1086 $remote_path .= "/*" if $remote_path !~ /\*/;
1087 my ($n) = ($switch =~ /^--(\w+)/);
1088 if (length $pfx && $pfx !~ m#/$#) {
1089 die "--prefix='$pfx' must have a trailing slash '/'\n";
1091 command_noisy('config',
1092 "svn-remote.$gs->{repo_id}.$n",
1093 "$remote_path:refs/remotes/$pfx*" .
1094 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1097 sub verify_ref {
1098 my ($ref) = @_;
1099 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1100 { STDERR => 0 }); };
1103 sub get_tree_from_treeish {
1104 my ($treeish) = @_;
1105 # $treeish can be a symbolic ref, too:
1106 my $type = command_oneline(qw/cat-file -t/, $treeish);
1107 my $expected;
1108 while ($type eq 'tag') {
1109 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1111 if ($type eq 'commit') {
1112 $expected = (grep /^tree /, command(qw/cat-file commit/,
1113 $treeish))[0];
1114 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1115 die "Unable to get tree from $treeish\n" unless $expected;
1116 } elsif ($type eq 'tree') {
1117 $expected = $treeish;
1118 } else {
1119 die "$treeish is a $type, expected tree, tag or commit\n";
1121 return $expected;
1124 sub get_commit_entry {
1125 my ($treeish) = shift;
1126 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1127 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1128 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1129 open my $log_fh, '>', $commit_editmsg or croak $!;
1131 my $type = command_oneline(qw/cat-file -t/, $treeish);
1132 if ($type eq 'commit' || $type eq 'tag') {
1133 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1134 $type, $treeish);
1135 my $in_msg = 0;
1136 my $author;
1137 my $saw_from = 0;
1138 my $msgbuf = "";
1139 while (<$msg_fh>) {
1140 if (!$in_msg) {
1141 $in_msg = 1 if (/^\s*$/);
1142 $author = $1 if (/^author (.*>)/);
1143 } elsif (/^git-svn-id: /) {
1144 # skip this for now, we regenerate the
1145 # correct one on re-fetch anyways
1146 # TODO: set *:merge properties or like...
1147 } else {
1148 if (/^From:/ || /^Signed-off-by:/) {
1149 $saw_from = 1;
1151 $msgbuf .= $_;
1154 $msgbuf =~ s/\s+$//s;
1155 if ($Git::SVN::_add_author_from && defined($author)
1156 && !$saw_from) {
1157 $msgbuf .= "\n\nFrom: $author";
1159 print $log_fh $msgbuf or croak $!;
1160 command_close_pipe($msg_fh, $ctx);
1162 close $log_fh or croak $!;
1164 if ($_edit || ($type eq 'tree')) {
1165 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1166 # TODO: strip out spaces, comments, like git-commit.sh
1167 system($editor, $commit_editmsg);
1169 rename $commit_editmsg, $commit_msg or croak $!;
1171 # SVN requires messages to be UTF-8 when entering the repo
1172 local $/;
1173 open $log_fh, '<', $commit_msg or croak $!;
1174 binmode $log_fh;
1175 chomp($log_entry{log} = <$log_fh>);
1177 if (my $enc = Git::config('i18n.commitencoding')) {
1178 require Encode;
1179 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1181 close $log_fh or croak $!;
1183 unlink $commit_msg;
1184 \%log_entry;
1187 sub s_to_file {
1188 my ($str, $file, $mode) = @_;
1189 open my $fd,'>',$file or croak $!;
1190 print $fd $str,"\n" or croak $!;
1191 close $fd or croak $!;
1192 chmod ($mode &~ umask, $file) if (defined $mode);
1195 sub file_to_s {
1196 my $file = shift;
1197 open my $fd,'<',$file or croak "$!: file: $file\n";
1198 local $/;
1199 my $ret = <$fd>;
1200 close $fd or croak $!;
1201 $ret =~ s/\s*$//s;
1202 return $ret;
1205 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1206 sub load_authors {
1207 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1208 my $log = $cmd eq 'log';
1209 while (<$authors>) {
1210 chomp;
1211 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1212 my ($user, $name, $email) = ($1, $2, $3);
1213 if ($log) {
1214 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1215 } else {
1216 $users{$user} = [$name, $email];
1219 close $authors or croak $!;
1222 # convert GetOpt::Long specs for use by git-config
1223 sub read_repo_config {
1224 return unless -d $ENV{GIT_DIR};
1225 my $opts = shift;
1226 my @config_only;
1227 foreach my $o (keys %$opts) {
1228 # if we have mixedCase and a long option-only, then
1229 # it's a config-only variable that we don't need for
1230 # the command-line.
1231 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1232 my $v = $opts->{$o};
1233 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1234 $key =~ s/-//g;
1235 my $arg = 'git config';
1236 $arg .= ' --int' if ($o =~ /[:=]i$/);
1237 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1238 if (ref $v eq 'ARRAY') {
1239 chomp(my @tmp = `$arg --get-all svn.$key`);
1240 @$v = @tmp if @tmp;
1241 } else {
1242 chomp(my $tmp = `$arg --get svn.$key`);
1243 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1244 $$v = $tmp;
1248 delete @$opts{@config_only} if @config_only;
1251 sub extract_metadata {
1252 my $id = shift or return (undef, undef, undef);
1253 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1254 \s([a-f\d\-]+)$/x);
1255 if (!defined $rev || !$uuid || !$url) {
1256 # some of the original repositories I made had
1257 # identifiers like this:
1258 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1260 return ($url, $rev, $uuid);
1263 sub cmt_metadata {
1264 return extract_metadata((grep(/^git-svn-id: /,
1265 command(qw/cat-file commit/, shift)))[-1]);
1268 sub cmt_sha2rev_batch {
1269 my %s2r;
1270 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1271 my $list = shift;
1273 foreach my $sha (@{$list}) {
1274 my $first = 1;
1275 my $size = 0;
1276 print $out $sha, "\n";
1278 while (my $line = <$in>) {
1279 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1280 last;
1281 } elsif ($first &&
1282 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1283 $first = 0;
1284 $size = $1;
1285 next;
1286 } elsif ($line =~ /^(git-svn-id: )/) {
1287 my (undef, $rev, undef) =
1288 extract_metadata($line);
1289 $s2r{$sha} = $rev;
1292 $size -= length($line);
1293 last if ($size == 0);
1297 command_close_bidi_pipe($pid, $in, $out, $ctx);
1299 return \%s2r;
1302 sub working_head_info {
1303 my ($head, $refs) = @_;
1304 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1305 my ($fh, $ctx) = command_output_pipe(@args, $head);
1306 my $hash;
1307 my %max;
1308 while (<$fh>) {
1309 if ( m{^commit ($::sha1)$} ) {
1310 unshift @$refs, $hash if $hash and $refs;
1311 $hash = $1;
1312 next;
1314 next unless s{^\s*(git-svn-id:)}{$1};
1315 my ($url, $rev, $uuid) = extract_metadata($_);
1316 if (defined $url && defined $rev) {
1317 next if $max{$url} and $max{$url} < $rev;
1318 if (my $gs = Git::SVN->find_by_url($url)) {
1319 my $c = $gs->rev_map_get($rev, $uuid);
1320 if ($c && $c eq $hash) {
1321 close $fh; # break the pipe
1322 return ($url, $rev, $uuid, $gs);
1323 } else {
1324 $max{$url} ||= $gs->rev_map_max;
1329 command_close_pipe($fh, $ctx);
1330 (undef, undef, undef, undef);
1333 sub read_commit_parents {
1334 my ($parents, $c) = @_;
1335 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1336 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1337 @{$parents->{$c}} = split(/ /, $p);
1340 sub linearize_history {
1341 my ($gs, $refs) = @_;
1342 my %parents;
1343 foreach my $c (@$refs) {
1344 read_commit_parents(\%parents, $c);
1347 my @linear_refs;
1348 my %skip = ();
1349 my $last_svn_commit = $gs->last_commit;
1350 foreach my $c (reverse @$refs) {
1351 next if $c eq $last_svn_commit;
1352 last if $skip{$c};
1354 unshift @linear_refs, $c;
1355 $skip{$c} = 1;
1357 # we only want the first parent to diff against for linear
1358 # history, we save the rest to inject when we finalize the
1359 # svn commit
1360 my $fp_a = verify_ref("$c~1");
1361 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1362 if (!$fp_a || !$fp_b) {
1363 die "Commit $c\n",
1364 "has no parent commit, and therefore ",
1365 "nothing to diff against.\n",
1366 "You should be working from a repository ",
1367 "originally created by git-svn\n";
1369 if ($fp_a ne $fp_b) {
1370 die "$c~1 = $fp_a, however parsing commit $c ",
1371 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1374 foreach my $p (@{$parents{$c}}) {
1375 $skip{$p} = 1;
1378 (\@linear_refs, \%parents);
1381 sub find_file_type_and_diff_status {
1382 my ($path) = @_;
1383 return ('dir', '') if $path eq '';
1385 my $diff_output =
1386 command_oneline(qw(diff --cached --name-status --), $path) || "";
1387 my $diff_status = (split(' ', $diff_output))[0] || "";
1389 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1391 return (undef, undef) if !$diff_status && !$ls_tree;
1393 if ($diff_status eq "A") {
1394 return ("link", $diff_status) if -l $path;
1395 return ("dir", $diff_status) if -d $path;
1396 return ("file", $diff_status);
1399 my $mode = (split(' ', $ls_tree))[0] || "";
1401 return ("link", $diff_status) if $mode eq "120000";
1402 return ("dir", $diff_status) if $mode eq "040000";
1403 return ("file", $diff_status);
1406 sub md5sum {
1407 my $arg = shift;
1408 my $ref = ref $arg;
1409 my $md5 = Digest::MD5->new();
1410 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1411 $md5->addfile($arg) or croak $!;
1412 } elsif ($ref eq 'SCALAR') {
1413 $md5->add($$arg) or croak $!;
1414 } elsif (!$ref) {
1415 $md5->add($arg) or croak $!;
1416 } else {
1417 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1419 return $md5->hexdigest();
1422 package Git::SVN;
1423 use strict;
1424 use warnings;
1425 use Fcntl qw/:DEFAULT :seek/;
1426 use constant rev_map_fmt => 'NH40';
1427 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1428 $_repack $_repack_flags $_use_svm_props $_head
1429 $_use_svnsync_props $no_reuse_existing $_minimize_url
1430 $_use_log_author $_add_author_from $_localtime/;
1431 use Carp qw/croak/;
1432 use File::Path qw/mkpath/;
1433 use File::Copy qw/copy/;
1434 use IPC::Open3;
1436 my ($_gc_nr, $_gc_period);
1438 # properties that we do not log:
1439 my %SKIP_PROP;
1440 BEGIN {
1441 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1442 svn:special svn:executable
1443 svn:entry:committed-rev
1444 svn:entry:last-author
1445 svn:entry:uuid
1446 svn:entry:committed-date/;
1448 # some options are read globally, but can be overridden locally
1449 # per [svn-remote "..."] section. Command-line options will *NOT*
1450 # override options set in an [svn-remote "..."] section
1451 no strict 'refs';
1452 for my $option (qw/follow_parent no_metadata use_svm_props
1453 use_svnsync_props/) {
1454 my $key = $option;
1455 $key =~ tr/_//d;
1456 my $prop = "-$option";
1457 *$option = sub {
1458 my ($self) = @_;
1459 return $self->{$prop} if exists $self->{$prop};
1460 my $k = "svn-remote.$self->{repo_id}.$key";
1461 eval { command_oneline(qw/config --get/, $k) };
1462 if ($@) {
1463 $self->{$prop} = ${"Git::SVN::_$option"};
1464 } else {
1465 my $v = command_oneline(qw/config --bool/,$k);
1466 $self->{$prop} = $v eq 'false' ? 0 : 1;
1468 return $self->{$prop};
1474 my (%LOCKFILES, %INDEX_FILES);
1475 END {
1476 unlink keys %LOCKFILES if %LOCKFILES;
1477 unlink keys %INDEX_FILES if %INDEX_FILES;
1480 sub resolve_local_globs {
1481 my ($url, $fetch, $glob_spec) = @_;
1482 return unless defined $glob_spec;
1483 my $ref = $glob_spec->{ref};
1484 my $path = $glob_spec->{path};
1485 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1486 next unless m#^refs/remotes/$ref->{regex}$#;
1487 my $p = $1;
1488 my $pathname = desanitize_refname($path->full_path($p));
1489 my $refname = desanitize_refname($ref->full_path($p));
1490 if (my $existing = $fetch->{$pathname}) {
1491 if ($existing ne $refname) {
1492 die "Refspec conflict:\n",
1493 "existing: refs/remotes/$existing\n",
1494 " globbed: refs/remotes/$refname\n";
1496 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1497 $u =~ s!^\Q$url\E(/|$)!! or die
1498 "refs/remotes/$refname: '$url' not found in '$u'\n";
1499 if ($pathname ne $u) {
1500 warn "W: Refspec glob conflict ",
1501 "(ref: refs/remotes/$refname):\n",
1502 "expected path: $pathname\n",
1503 " real path: $u\n",
1504 "Continuing ahead with $u\n";
1505 next;
1507 } else {
1508 $fetch->{$pathname} = $refname;
1513 sub parse_revision_argument {
1514 my ($base, $head) = @_;
1515 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1516 return ($base, $head);
1518 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1519 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1520 return ($head, $head) if ($::_revision eq 'HEAD');
1521 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1522 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1523 die "revision argument: $::_revision not understood by git-svn\n";
1526 sub fetch_all {
1527 my ($repo_id, $remotes) = @_;
1528 if (ref $repo_id) {
1529 my $gs = $repo_id;
1530 $repo_id = undef;
1531 $repo_id = $gs->{repo_id};
1533 $remotes ||= read_all_remotes();
1534 my $remote = $remotes->{$repo_id} or
1535 die "[svn-remote \"$repo_id\"] unknown\n";
1536 my $fetch = $remote->{fetch};
1537 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1538 my (@gs, @globs);
1539 my $ra = Git::SVN::Ra->new($url);
1540 my $uuid = $ra->get_uuid;
1541 my $head = $ra->get_latest_revnum;
1542 my $base = defined $fetch ? $head : 0;
1544 # read the max revs for wildcard expansion (branches/*, tags/*)
1545 foreach my $t (qw/branches tags/) {
1546 defined $remote->{$t} or next;
1547 push @globs, $remote->{$t};
1548 my $max_rev = eval { tmp_config(qw/--int --get/,
1549 "svn-remote.$repo_id.${t}-maxRev") };
1550 if (defined $max_rev && ($max_rev < $base)) {
1551 $base = $max_rev;
1552 } elsif (!defined $max_rev) {
1553 $base = 0;
1557 if ($fetch) {
1558 foreach my $p (sort keys %$fetch) {
1559 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1560 my $lr = $gs->rev_map_max;
1561 if (defined $lr) {
1562 $base = $lr if ($lr < $base);
1564 push @gs, $gs;
1568 ($base, $head) = parse_revision_argument($base, $head);
1569 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1572 sub read_all_remotes {
1573 my $r = {};
1574 my $use_svm_props = eval { command_oneline(qw/config --bool
1575 svn.useSvmProps/) };
1576 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1577 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1578 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1579 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1580 die("svn-remote.$remote: remote ref '$_remote_ref' "
1581 . "must start with 'refs/remotes/'\n")
1582 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1583 my $remote_ref = $1;
1584 $local_ref =~ s{^/}{};
1585 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1586 $r->{$remote}->{svm} = {} if $use_svm_props;
1587 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1588 $r->{$1}->{svm} = {};
1589 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1590 $r->{$1}->{url} = $2;
1591 } elsif (m!^(.+)\.(branches|tags)=
1592 (.*):refs/remotes/(.+)\s*$/!x) {
1593 my ($p, $g) = ($3, $4);
1594 my $rs = $r->{$1}->{$2} = {
1595 t => $2,
1596 remote => $1,
1597 path => Git::SVN::GlobSpec->new($p),
1598 ref => Git::SVN::GlobSpec->new($g) };
1599 if (length($rs->{ref}->{right}) != 0) {
1600 die "The '*' glob character must be the last ",
1601 "character of '$g'\n";
1606 map {
1607 if (defined $r->{$_}->{svm}) {
1608 my $svm;
1609 eval {
1610 my $section = "svn-remote.$_";
1611 $svm = {
1612 source => tmp_config('--get',
1613 "$section.svm-source"),
1614 replace => tmp_config('--get',
1615 "$section.svm-replace"),
1618 $r->{$_}->{svm} = $svm;
1620 } keys %$r;
1625 sub init_vars {
1626 $_gc_nr = $_gc_period = 1000;
1627 if (defined $_repack || defined $_repack_flags) {
1628 warn "Repack options are obsolete; they have no effect.\n";
1632 sub verify_remotes_sanity {
1633 return unless -d $ENV{GIT_DIR};
1634 my %seen;
1635 foreach (command(qw/config -l/)) {
1636 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1637 if ($seen{$1}) {
1638 die "Remote ref refs/remote/$1 is tracked by",
1639 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1640 "Please resolve this ambiguity in ",
1641 "your git configuration file before ",
1642 "continuing\n";
1644 $seen{$1} = $_;
1649 sub find_existing_remote {
1650 my ($url, $remotes) = @_;
1651 return undef if $no_reuse_existing;
1652 my $existing;
1653 foreach my $repo_id (keys %$remotes) {
1654 my $u = $remotes->{$repo_id}->{url} or next;
1655 next if $u ne $url;
1656 $existing = $repo_id;
1657 last;
1659 $existing;
1662 sub init_remote_config {
1663 my ($self, $url, $no_write) = @_;
1664 $url =~ s!/+$!!; # strip trailing slash
1665 my $r = read_all_remotes();
1666 my $existing = find_existing_remote($url, $r);
1667 if ($existing) {
1668 unless ($no_write) {
1669 print STDERR "Using existing ",
1670 "[svn-remote \"$existing\"]\n";
1672 $self->{repo_id} = $existing;
1673 } elsif ($_minimize_url) {
1674 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1675 $existing = find_existing_remote($min_url, $r);
1676 if ($existing) {
1677 unless ($no_write) {
1678 print STDERR "Using existing ",
1679 "[svn-remote \"$existing\"]\n";
1681 $self->{repo_id} = $existing;
1683 if ($min_url ne $url) {
1684 unless ($no_write) {
1685 print STDERR "Using higher level of URL: ",
1686 "$url => $min_url\n";
1688 my $old_path = $self->{path};
1689 $self->{path} = $url;
1690 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1691 if (length $old_path) {
1692 $self->{path} .= "/$old_path";
1694 $url = $min_url;
1697 my $orig_url;
1698 if (!$existing) {
1699 # verify that we aren't overwriting anything:
1700 $orig_url = eval {
1701 command_oneline('config', '--get',
1702 "svn-remote.$self->{repo_id}.url")
1704 if ($orig_url && ($orig_url ne $url)) {
1705 die "svn-remote.$self->{repo_id}.url already set: ",
1706 "$orig_url\nwanted to set to: $url\n";
1709 my ($xrepo_id, $xpath) = find_ref($self->refname);
1710 if (defined $xpath) {
1711 die "svn-remote.$xrepo_id.fetch already set to track ",
1712 "$xpath:refs/remotes/", $self->refname, "\n";
1714 unless ($no_write) {
1715 command_noisy('config',
1716 "svn-remote.$self->{repo_id}.url", $url);
1717 $self->{path} =~ s{^/}{};
1718 command_noisy('config', '--add',
1719 "svn-remote.$self->{repo_id}.fetch",
1720 "$self->{path}:".$self->refname);
1722 $self->{url} = $url;
1725 sub find_by_url { # repos_root and, path are optional
1726 my ($class, $full_url, $repos_root, $path) = @_;
1728 return undef unless defined $full_url;
1729 remove_username($full_url);
1730 remove_username($repos_root) if defined $repos_root;
1731 my $remotes = read_all_remotes();
1732 if (defined $full_url && defined $repos_root && !defined $path) {
1733 $path = $full_url;
1734 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1736 foreach my $repo_id (keys %$remotes) {
1737 my $u = $remotes->{$repo_id}->{url} or next;
1738 remove_username($u);
1739 next if defined $repos_root && $repos_root ne $u;
1741 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1742 foreach (qw/branches tags/) {
1743 resolve_local_globs($u, $fetch,
1744 $remotes->{$repo_id}->{$_});
1746 my $p = $path;
1747 my $rwr = rewrite_root({repo_id => $repo_id});
1748 my $svm = $remotes->{$repo_id}->{svm}
1749 if defined $remotes->{$repo_id}->{svm};
1750 unless (defined $p) {
1751 $p = $full_url;
1752 my $z = $u;
1753 my $prefix = '';
1754 if ($rwr) {
1755 $z = $rwr;
1756 remove_username($z);
1757 } elsif (defined $svm) {
1758 $z = $svm->{source};
1759 $prefix = $svm->{replace};
1760 $prefix =~ s#^\Q$u\E(?:/|$)##;
1761 $prefix =~ s#/$##;
1763 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1765 foreach my $f (keys %$fetch) {
1766 next if $f ne $p;
1767 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1770 undef;
1773 sub init {
1774 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1775 my $self = _new($class, $repo_id, $ref_id, $path);
1776 if (defined $url) {
1777 $self->init_remote_config($url, $no_write);
1779 $self;
1782 sub find_ref {
1783 my ($ref_id) = @_;
1784 foreach (command(qw/config -l/)) {
1785 next unless m!^svn-remote\.(.+)\.fetch=
1786 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1787 my ($repo_id, $path, $ref) = ($1, $2, $3);
1788 if ($ref eq $ref_id) {
1789 $path = '' if ($path =~ m#^\./?#);
1790 return ($repo_id, $path);
1793 (undef, undef, undef);
1796 sub new {
1797 my ($class, $ref_id, $repo_id, $path) = @_;
1798 if (defined $ref_id && !defined $repo_id && !defined $path) {
1799 ($repo_id, $path) = find_ref($ref_id);
1800 if (!defined $repo_id) {
1801 die "Could not find a \"svn-remote.*.fetch\" key ",
1802 "in the repository configuration matching: ",
1803 "refs/remotes/$ref_id\n";
1806 my $self = _new($class, $repo_id, $ref_id, $path);
1807 if (!defined $self->{path} || !length $self->{path}) {
1808 my $fetch = command_oneline('config', '--get',
1809 "svn-remote.$repo_id.fetch",
1810 ":refs/remotes/$ref_id\$") or
1811 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1812 "\":refs/remotes/$ref_id\$\" in config\n";
1813 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1815 $self->{url} = command_oneline('config', '--get',
1816 "svn-remote.$repo_id.url") or
1817 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1818 $self->rebuild;
1819 $self;
1822 sub refname {
1823 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1825 # It cannot end with a slash /, we'll throw up on this because
1826 # SVN can't have directories with a slash in their name, either:
1827 if ($refname =~ m{/$}) {
1828 die "ref: '$refname' ends with a trailing slash, this is ",
1829 "not permitted by git nor Subversion\n";
1832 # It cannot have ASCII control character space, tilde ~, caret ^,
1833 # colon :, question-mark ?, asterisk *, space, or open bracket [
1834 # anywhere.
1836 # Additionally, % must be escaped because it is used for escaping
1837 # and we want our escaped refname to be reversible
1838 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1840 # no slash-separated component can begin with a dot .
1841 # /.* becomes /%2E*
1842 $refname =~ s{/\.}{/%2E}g;
1844 # It cannot have two consecutive dots .. anywhere
1845 # .. becomes %2E%2E
1846 $refname =~ s{\.\.}{%2E%2E}g;
1848 return $refname;
1851 sub desanitize_refname {
1852 my ($refname) = @_;
1853 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1854 return $refname;
1857 sub svm_uuid {
1858 my ($self) = @_;
1859 return $self->{svm}->{uuid} if $self->svm;
1860 $self->ra;
1861 unless ($self->{svm}) {
1862 die "SVM UUID not cached, and reading remotely failed\n";
1864 $self->{svm}->{uuid};
1867 sub svm {
1868 my ($self) = @_;
1869 return $self->{svm} if $self->{svm};
1870 my $svm;
1871 # see if we have it in our config, first:
1872 eval {
1873 my $section = "svn-remote.$self->{repo_id}";
1874 $svm = {
1875 source => tmp_config('--get', "$section.svm-source"),
1876 uuid => tmp_config('--get', "$section.svm-uuid"),
1877 replace => tmp_config('--get', "$section.svm-replace"),
1880 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1881 $self->{svm} = $svm;
1883 $self->{svm};
1886 sub _set_svm_vars {
1887 my ($self, $ra) = @_;
1888 return $ra if $self->svm;
1890 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1891 "(svm:source, svm:uuid) ",
1892 "from the following URLs:\n" );
1893 sub read_svm_props {
1894 my ($self, $ra, $path, $r) = @_;
1895 my $props = ($ra->get_dir($path, $r))[2];
1896 my $src = $props->{'svm:source'};
1897 my $uuid = $props->{'svm:uuid'};
1898 return undef if (!$src || !$uuid);
1900 chomp($src, $uuid);
1902 $uuid =~ m{^[0-9a-f\-]{30,}$}
1903 or die "doesn't look right - svm:uuid is '$uuid'\n";
1905 # the '!' is used to mark the repos_root!/relative/path
1906 $src =~ s{/?!/?}{/};
1907 $src =~ s{/+$}{}; # no trailing slashes please
1908 # username is of no interest
1909 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1911 my $replace = $ra->{url};
1912 $replace .= "/$path" if length $path;
1914 my $section = "svn-remote.$self->{repo_id}";
1915 tmp_config("$section.svm-source", $src);
1916 tmp_config("$section.svm-replace", $replace);
1917 tmp_config("$section.svm-uuid", $uuid);
1918 $self->{svm} = {
1919 source => $src,
1920 uuid => $uuid,
1921 replace => $replace
1925 my $r = $ra->get_latest_revnum;
1926 my $path = $self->{path};
1927 my %tried;
1928 while (length $path) {
1929 unless ($tried{"$self->{url}/$path"}) {
1930 return $ra if $self->read_svm_props($ra, $path, $r);
1931 $tried{"$self->{url}/$path"} = 1;
1933 $path =~ s#/?[^/]+$##;
1935 die "Path: '$path' should be ''\n" if $path ne '';
1936 return $ra if $self->read_svm_props($ra, $path, $r);
1937 $tried{"$self->{url}/$path"} = 1;
1939 if ($ra->{repos_root} eq $self->{url}) {
1940 die @err, (map { " $_\n" } keys %tried), "\n";
1943 # nope, make sure we're connected to the repository root:
1944 my $ok;
1945 my @tried_b;
1946 $path = $ra->{svn_path};
1947 $ra = Git::SVN::Ra->new($ra->{repos_root});
1948 while (length $path) {
1949 unless ($tried{"$ra->{url}/$path"}) {
1950 $ok = $self->read_svm_props($ra, $path, $r);
1951 last if $ok;
1952 $tried{"$ra->{url}/$path"} = 1;
1954 $path =~ s#/?[^/]+$##;
1956 die "Path: '$path' should be ''\n" if $path ne '';
1957 $ok ||= $self->read_svm_props($ra, $path, $r);
1958 $tried{"$ra->{url}/$path"} = 1;
1959 if (!$ok) {
1960 die @err, (map { " $_\n" } keys %tried), "\n";
1962 Git::SVN::Ra->new($self->{url});
1965 sub svnsync {
1966 my ($self) = @_;
1967 return $self->{svnsync} if $self->{svnsync};
1969 if ($self->no_metadata) {
1970 die "Can't have both 'noMetadata' and ",
1971 "'useSvnsyncProps' options set!\n";
1973 if ($self->rewrite_root) {
1974 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1975 "options set!\n";
1978 my $svnsync;
1979 # see if we have it in our config, first:
1980 eval {
1981 my $section = "svn-remote.$self->{repo_id}";
1983 my $url = tmp_config('--get', "$section.svnsync-url");
1984 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1985 die "doesn't look right - svn:sync-from-url is '$url'\n";
1987 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1988 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1989 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1991 $svnsync = { url => $url, uuid => $uuid }
1993 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1994 return $self->{svnsync} = $svnsync;
1997 my $err = "useSvnsyncProps set, but failed to read " .
1998 "svnsync property: svn:sync-from-";
1999 my $rp = $self->ra->rev_proplist(0);
2001 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2002 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2003 die "doesn't look right - svn:sync-from-url is '$url'\n";
2005 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2006 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2007 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2009 my $section = "svn-remote.$self->{repo_id}";
2010 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2011 tmp_config('--add', "$section.svnsync-url", $url);
2012 return $self->{svnsync} = { url => $url, uuid => $uuid };
2015 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2016 # remote lookup (useful for 'git svn log').
2017 sub ra_uuid {
2018 my ($self) = @_;
2019 unless ($self->{ra_uuid}) {
2020 my $key = "svn-remote.$self->{repo_id}.uuid";
2021 my $uuid = eval { tmp_config('--get', $key) };
2022 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2023 $self->{ra_uuid} = $uuid;
2024 } else {
2025 die "ra_uuid called without URL\n" unless $self->{url};
2026 $self->{ra_uuid} = $self->ra->get_uuid;
2027 tmp_config('--add', $key, $self->{ra_uuid});
2030 $self->{ra_uuid};
2033 sub _set_repos_root {
2034 my ($self, $repos_root) = @_;
2035 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2036 $repos_root ||= $self->ra->{repos_root};
2037 tmp_config($k, $repos_root);
2038 $repos_root;
2041 sub repos_root {
2042 my ($self) = @_;
2043 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2044 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2047 sub ra {
2048 my ($self) = shift;
2049 my $ra = Git::SVN::Ra->new($self->{url});
2050 $self->_set_repos_root($ra->{repos_root});
2051 if ($self->use_svm_props && !$self->{svm}) {
2052 if ($self->no_metadata) {
2053 die "Can't have both 'noMetadata' and ",
2054 "'useSvmProps' options set!\n";
2055 } elsif ($self->use_svnsync_props) {
2056 die "Can't have both 'useSvnsyncProps' and ",
2057 "'useSvmProps' options set!\n";
2059 $ra = $self->_set_svm_vars($ra);
2060 $self->{-want_revprops} = 1;
2062 $ra;
2065 sub rel_path {
2066 my ($self) = @_;
2067 my $repos_root = $self->ra->{repos_root};
2068 return $self->{path} if ($self->{url} eq $repos_root);
2069 my $url = $self->{url} .
2070 (length $self->{path} ? "/$self->{path}" : $self->{path});
2071 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2072 $url;
2075 # prop_walk(PATH, REV, SUB)
2076 # -------------------------
2077 # Recursively traverse PATH at revision REV and invoke SUB for each
2078 # directory that contains a SVN property. SUB will be invoked as
2079 # follows: &SUB(gs, path, props); where `gs' is this instance of
2080 # Git::SVN, `path' the path to the directory where the properties
2081 # `props' were found. The `path' will be relative to point of checkout,
2082 # that is, if url://repo/trunk is the current Git branch, and that
2083 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2084 # as `path' (note the trailing `/').
2085 sub prop_walk {
2086 my ($self, $path, $rev, $sub) = @_;
2088 $path =~ s#^/##;
2089 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2090 $path =~ s#^/*#/#g;
2091 my $p = $path;
2092 # Strip the irrelevant part of the path.
2093 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2094 # Ensure the path is terminated by a `/'.
2095 $p =~ s#/*$#/#;
2097 # The properties contain all the internal SVN stuff nobody
2098 # (usually) cares about.
2099 my $interesting_props = 0;
2100 foreach (keys %{$props}) {
2101 # If it doesn't start with `svn:', it must be a
2102 # user-defined property.
2103 ++$interesting_props and next if $_ !~ /^svn:/;
2104 # FIXME: Fragile, if SVN adds new public properties,
2105 # this needs to be updated.
2106 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2107 |eol-style|mime-type
2108 |externals|needs-lock)$/x;
2110 &$sub($self, $p, $props) if $interesting_props;
2112 foreach (sort keys %$dirent) {
2113 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2114 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2118 sub last_rev { ($_[0]->last_rev_commit)[0] }
2119 sub last_commit { ($_[0]->last_rev_commit)[1] }
2121 # returns the newest SVN revision number and newest commit SHA1
2122 sub last_rev_commit {
2123 my ($self) = @_;
2124 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2125 return ($self->{last_rev}, $self->{last_commit});
2127 my $c = ::verify_ref($self->refname.'^0');
2128 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2129 my $rev = (::cmt_metadata($c))[1];
2130 if (defined $rev) {
2131 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2132 return ($rev, $c);
2135 my $map_path = $self->map_path;
2136 unless (-e $map_path) {
2137 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2138 return (undef, undef);
2140 my ($rev, $commit) = $self->rev_map_max(1);
2141 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2142 return ($rev, $commit);
2145 sub get_fetch_range {
2146 my ($self, $min, $max) = @_;
2147 $max ||= $self->ra->get_latest_revnum;
2148 $min ||= $self->rev_map_max;
2149 (++$min, $max);
2152 sub tmp_config {
2153 my (@args) = @_;
2154 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2155 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2156 if (! -f $config && -f $old_def_config) {
2157 rename $old_def_config, $config or
2158 die "Failed rename $old_def_config => $config: $!\n";
2160 my $old_config = $ENV{GIT_CONFIG};
2161 $ENV{GIT_CONFIG} = $config;
2162 $@ = undef;
2163 my @ret = eval {
2164 unless (-f $config) {
2165 mkfile($config);
2166 open my $fh, '>', $config or
2167 die "Can't open $config: $!\n";
2168 print $fh "; This file is used internally by ",
2169 "git-svn\n" or die
2170 "Couldn't write to $config: $!\n";
2171 print $fh "; You should not have to edit it\n" or
2172 die "Couldn't write to $config: $!\n";
2173 close $fh or die "Couldn't close $config: $!\n";
2175 command('config', @args);
2177 my $err = $@;
2178 if (defined $old_config) {
2179 $ENV{GIT_CONFIG} = $old_config;
2180 } else {
2181 delete $ENV{GIT_CONFIG};
2183 die $err if $err;
2184 wantarray ? @ret : $ret[0];
2187 sub tmp_index_do {
2188 my ($self, $sub) = @_;
2189 my $old_index = $ENV{GIT_INDEX_FILE};
2190 $ENV{GIT_INDEX_FILE} = $self->{index};
2191 $@ = undef;
2192 my @ret = eval {
2193 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2194 mkpath([$dir]) unless -d $dir;
2195 &$sub;
2197 my $err = $@;
2198 if (defined $old_index) {
2199 $ENV{GIT_INDEX_FILE} = $old_index;
2200 } else {
2201 delete $ENV{GIT_INDEX_FILE};
2203 die $err if $err;
2204 wantarray ? @ret : $ret[0];
2207 sub assert_index_clean {
2208 my ($self, $treeish) = @_;
2210 $self->tmp_index_do(sub {
2211 command_noisy('read-tree', $treeish) unless -e $self->{index};
2212 my $x = command_oneline('write-tree');
2213 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2214 /^tree ($::sha1)/mo);
2215 return if $y eq $x;
2217 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2218 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2219 command_noisy('read-tree', $treeish);
2220 $x = command_oneline('write-tree');
2221 if ($y ne $x) {
2222 ::fatal "trees ($treeish) $y != $x\n",
2223 "Something is seriously wrong...";
2228 sub get_commit_parents {
2229 my ($self, $log_entry) = @_;
2230 my (%seen, @ret, @tmp);
2231 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2232 if (my $ip = $self->{inject_parents}) {
2233 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2234 push @tmp, $commit;
2237 if (my $cur = ::verify_ref($self->refname.'^0')) {
2238 push @tmp, $cur;
2240 if (my $ipd = $self->{inject_parents_dcommit}) {
2241 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2242 push @tmp, @$commit;
2245 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2246 while (my $p = shift @tmp) {
2247 next if $seen{$p};
2248 $seen{$p} = 1;
2249 push @ret, $p;
2250 # MAXPARENT is defined to 16 in commit-tree.c:
2251 last if @ret >= 16;
2253 if (@tmp) {
2254 die "r$log_entry->{revision}: No room for parents:\n\t",
2255 join("\n\t", @tmp), "\n";
2257 @ret;
2260 sub rewrite_root {
2261 my ($self) = @_;
2262 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2263 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2264 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2265 if ($rwr) {
2266 $rwr =~ s#/+$##;
2267 if ($rwr !~ m#^[a-z\+]+://#) {
2268 die "$rwr is not a valid URL (key: $k)\n";
2271 $self->{-rewrite_root} = $rwr;
2274 sub metadata_url {
2275 my ($self) = @_;
2276 ($self->rewrite_root || $self->{url}) .
2277 (length $self->{path} ? '/' . $self->{path} : '');
2280 sub full_url {
2281 my ($self) = @_;
2282 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2286 sub set_commit_header_env {
2287 my ($log_entry) = @_;
2288 my %env;
2289 foreach my $ned (qw/NAME EMAIL DATE/) {
2290 foreach my $ac (qw/AUTHOR COMMITTER/) {
2291 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2295 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2296 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2297 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2299 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2300 ? $log_entry->{commit_name}
2301 : $log_entry->{name};
2302 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2303 ? $log_entry->{commit_email}
2304 : $log_entry->{email};
2305 \%env;
2308 sub restore_commit_header_env {
2309 my ($env) = @_;
2310 foreach my $ned (qw/NAME EMAIL DATE/) {
2311 foreach my $ac (qw/AUTHOR COMMITTER/) {
2312 my $k = "GIT_${ac}_${ned}";
2313 if (defined $env->{$k}) {
2314 $ENV{$k} = $env->{$k};
2315 } else {
2316 delete $ENV{$k};
2322 sub gc {
2323 command_noisy('gc', '--auto');
2326 sub do_git_commit {
2327 my ($self, $log_entry) = @_;
2328 my $lr = $self->last_rev;
2329 if (defined $lr && $lr >= $log_entry->{revision}) {
2330 die "Last fetched revision of ", $self->refname,
2331 " was r$lr, but we are about to fetch: ",
2332 "r$log_entry->{revision}!\n";
2334 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2335 croak "$log_entry->{revision} = $c already exists! ",
2336 "Why are we refetching it?\n";
2338 my $old_env = set_commit_header_env($log_entry);
2339 my $tree = $log_entry->{tree};
2340 if (!defined $tree) {
2341 $tree = $self->tmp_index_do(sub {
2342 command_oneline('write-tree') });
2344 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2346 my @exec = ('git', 'commit-tree', $tree);
2347 foreach ($self->get_commit_parents($log_entry)) {
2348 push @exec, '-p', $_;
2350 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2351 or croak $!;
2352 binmode $msg_fh;
2354 # we always get UTF-8 from SVN, but we may want our commits in
2355 # a different encoding.
2356 if (my $enc = Git::config('i18n.commitencoding')) {
2357 require Encode;
2358 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2360 print $msg_fh $log_entry->{log} or croak $!;
2361 restore_commit_header_env($old_env);
2362 unless ($self->no_metadata) {
2363 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2364 or croak $!;
2366 $msg_fh->flush == 0 or croak $!;
2367 close $msg_fh or croak $!;
2368 chomp(my $commit = do { local $/; <$out_fh> });
2369 close $out_fh or croak $!;
2370 waitpid $pid, 0;
2371 croak $? if $?;
2372 if ($commit !~ /^$::sha1$/o) {
2373 die "Failed to commit, invalid sha1: $commit\n";
2376 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2378 $self->{last_rev} = $log_entry->{revision};
2379 $self->{last_commit} = $commit;
2380 print "r$log_entry->{revision}" unless $::_q > 1;
2381 if (defined $log_entry->{svm_revision}) {
2382 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2383 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2384 0, $self->svm_uuid);
2386 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2387 if (--$_gc_nr == 0) {
2388 $_gc_nr = $_gc_period;
2389 gc();
2391 return $commit;
2394 sub match_paths {
2395 my ($self, $paths, $r) = @_;
2396 return 1 if $self->{path} eq '';
2397 if (my $path = $paths->{"/$self->{path}"}) {
2398 return ($path->{action} eq 'D') ? 0 : 1;
2400 my $repos_root = $self->ra->{repos_root};
2401 my $extended_path = $self->{url} . '/' . $self->{path};
2402 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2403 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2404 if (grep /$self->{path_regex}/, keys %$paths) {
2405 return 1;
2407 my $c = '';
2408 foreach (split m#/#, $self->{path}) {
2409 $c .= "/$_";
2410 next unless ($paths->{$c} &&
2411 ($paths->{$c}->{action} =~ /^[AR]$/));
2412 if ($self->ra->check_path($self->{path}, $r) ==
2413 $SVN::Node::dir) {
2414 return 1;
2417 return 0;
2420 sub find_parent_branch {
2421 my ($self, $paths, $rev) = @_;
2422 return undef unless $self->follow_parent;
2423 unless (defined $paths) {
2424 my $err_handler = $SVN::Error::handler;
2425 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2426 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2427 $paths =
2428 Git::SVN::Ra::dup_changed_paths($_[0]) });
2429 $SVN::Error::handler = $err_handler;
2431 return undef unless defined $paths;
2433 # look for a parent from another branch:
2434 my @b_path_components = split m#/#, $self->rel_path;
2435 my @a_path_components;
2436 my $i;
2437 while (@b_path_components) {
2438 $i = $paths->{'/'.join('/', @b_path_components)};
2439 last if $i && defined $i->{copyfrom_path};
2440 unshift(@a_path_components, pop(@b_path_components));
2442 return undef unless defined $i && defined $i->{copyfrom_path};
2443 my $branch_from = $i->{copyfrom_path};
2444 if (@a_path_components) {
2445 print STDERR "branch_from: $branch_from => ";
2446 $branch_from .= '/'.join('/', @a_path_components);
2447 print STDERR $branch_from, "\n";
2449 my $r = $i->{copyfrom_rev};
2450 my $repos_root = $self->ra->{repos_root};
2451 my $url = $self->ra->{url};
2452 my $new_url = $repos_root . $branch_from;
2453 print STDERR "Found possible branch point: ",
2454 "$new_url => ", $self->full_url, ", $r\n";
2455 $branch_from =~ s#^/##;
2456 my $gs = $self->other_gs($new_url, $url, $repos_root,
2457 $branch_from, $r, $self->{ref_id});
2458 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2460 my ($base, $head);
2461 if (!defined $r0 || !defined $parent) {
2462 ($base, $head) = parse_revision_argument(0, $r);
2463 } else {
2464 if ($r0 < $r) {
2465 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2466 0, 1, sub { $base = $_[1] - 1 });
2469 if (defined $base && $base <= $r) {
2470 $gs->fetch($base, $r);
2472 ($r0, $parent) = $gs->find_rev_before($r, 1);
2474 if (defined $r0 && defined $parent) {
2475 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2476 my $ed;
2477 if ($self->ra->can_do_switch) {
2478 $self->assert_index_clean($parent);
2479 print STDERR "Following parent with do_switch\n";
2480 # do_switch works with svn/trunk >= r22312, but that
2481 # is not included with SVN 1.4.3 (the latest version
2482 # at the moment), so we can't rely on it
2483 $self->{last_rev} = $r0;
2484 $self->{last_commit} = $parent;
2485 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2486 $gs->ra->gs_do_switch($r0, $rev, $gs,
2487 $self->full_url, $ed)
2488 or die "SVN connection failed somewhere...\n";
2489 } elsif ($self->ra->trees_match($new_url, $r0,
2490 $self->full_url, $rev)) {
2491 print STDERR "Trees match:\n",
2492 " $new_url\@$r0\n",
2493 " ${\$self->full_url}\@$rev\n",
2494 "Following parent with no changes\n";
2495 $self->tmp_index_do(sub {
2496 command_noisy('read-tree', $parent);
2498 $self->{last_commit} = $parent;
2499 } else {
2500 print STDERR "Following parent with do_update\n";
2501 $ed = SVN::Git::Fetcher->new($self);
2502 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2503 or die "SVN connection failed somewhere...\n";
2505 print STDERR "Successfully followed parent\n";
2506 return $self->make_log_entry($rev, [$parent], $ed);
2508 return undef;
2511 sub do_fetch {
2512 my ($self, $paths, $rev) = @_;
2513 my $ed;
2514 my ($last_rev, @parents);
2515 if (my $lc = $self->last_commit) {
2516 # we can have a branch that was deleted, then re-added
2517 # under the same name but copied from another path, in
2518 # which case we'll have multiple parents (we don't
2519 # want to break the original ref, nor lose copypath info):
2520 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2521 push @{$log_entry->{parents}}, $lc;
2522 return $log_entry;
2524 $ed = SVN::Git::Fetcher->new($self);
2525 $last_rev = $self->{last_rev};
2526 $ed->{c} = $lc;
2527 @parents = ($lc);
2528 } else {
2529 $last_rev = $rev;
2530 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2531 return $log_entry;
2533 $ed = SVN::Git::Fetcher->new($self);
2535 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2536 die "SVN connection failed somewhere...\n";
2538 $self->make_log_entry($rev, \@parents, $ed);
2541 sub get_untracked {
2542 my ($self, $ed) = @_;
2543 my @out;
2544 my $h = $ed->{empty};
2545 foreach (sort keys %$h) {
2546 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2547 push @out, " $act: " . uri_encode($_);
2548 warn "W: $act: $_\n";
2550 foreach my $t (qw/dir_prop file_prop/) {
2551 $h = $ed->{$t} or next;
2552 foreach my $path (sort keys %$h) {
2553 my $ppath = $path eq '' ? '.' : $path;
2554 foreach my $prop (sort keys %{$h->{$path}}) {
2555 next if $SKIP_PROP{$prop};
2556 my $v = $h->{$path}->{$prop};
2557 my $t_ppath_prop = "$t: " .
2558 uri_encode($ppath) . ' ' .
2559 uri_encode($prop);
2560 if (defined $v) {
2561 push @out, " +$t_ppath_prop " .
2562 uri_encode($v);
2563 } else {
2564 push @out, " -$t_ppath_prop";
2569 foreach my $t (qw/absent_file absent_directory/) {
2570 $h = $ed->{$t} or next;
2571 foreach my $parent (sort keys %$h) {
2572 foreach my $path (sort @{$h->{$parent}}) {
2573 push @out, " $t: " .
2574 uri_encode("$parent/$path");
2575 warn "W: $t: $parent/$path ",
2576 "Insufficient permissions?\n";
2580 \@out;
2583 # parse_svn_date(DATE)
2584 # --------------------
2585 # Given a date (in UTC) from Subversion, return a string in the format
2586 # "<TZ Offset> <local date/time>" that Git will use.
2588 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2589 # is true we'll convert it to the local timezone instead.
2590 sub parse_svn_date {
2591 my $date = shift || return '+0000 1970-01-01 00:00:00';
2592 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2593 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2594 croak "Unable to parse date: $date\n";
2595 my $parsed_date; # Set next.
2597 if ($Git::SVN::_localtime) {
2598 # Translate the Subversion datetime to an epoch time.
2599 # Begin by switching ourselves to $date's timezone, UTC.
2600 my $old_env_TZ = $ENV{TZ};
2601 $ENV{TZ} = 'UTC';
2603 my $epoch_in_UTC =
2604 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2606 # Determine our local timezone (including DST) at the
2607 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2608 # value of TZ, if any, at the time we were run.
2609 if (defined $Git::SVN::Log::TZ) {
2610 $ENV{TZ} = $Git::SVN::Log::TZ;
2611 } else {
2612 delete $ENV{TZ};
2615 my $our_TZ =
2616 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2618 # This converts $epoch_in_UTC into our local timezone.
2619 my ($sec, $min, $hour, $mday, $mon, $year,
2620 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2622 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2623 $our_TZ, $year + 1900, $mon + 1,
2624 $mday, $hour, $min, $sec);
2626 # Reset us to the timezone in effect when we entered
2627 # this routine.
2628 if (defined $old_env_TZ) {
2629 $ENV{TZ} = $old_env_TZ;
2630 } else {
2631 delete $ENV{TZ};
2633 } else {
2634 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2637 return $parsed_date;
2640 sub other_gs {
2641 my ($self, $new_url, $url, $repos_root,
2642 $branch_from, $r, $old_ref_id) = @_;
2643 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2644 unless ($gs) {
2645 my $ref_id = $old_ref_id;
2646 $ref_id =~ s/\@\d+$//;
2647 $ref_id .= "\@$r";
2648 # just grow a tail if we're not unique enough :x
2649 $ref_id .= '-' while find_ref($ref_id);
2650 print STDERR "Initializing parent: $ref_id\n";
2651 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2652 if ($u =~ s#^\Q$url\E(/|$)##) {
2653 $p = $u;
2654 $u = $url;
2655 $repo_id = $self->{repo_id};
2657 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2662 sub check_author {
2663 my ($author) = @_;
2664 if (!defined $author || length $author == 0) {
2665 $author = '(no author)';
2666 } elsif (defined $::_authors && ! defined $::users{$author}) {
2667 die "Author: $author not defined in $::_authors file\n";
2669 $author;
2672 sub make_log_entry {
2673 my ($self, $rev, $parents, $ed) = @_;
2674 my $untracked = $self->get_untracked($ed);
2676 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2677 print $un "r$rev\n" or croak $!;
2678 print $un $_, "\n" foreach @$untracked;
2679 my %log_entry = ( parents => $parents || [], revision => $rev,
2680 log => '');
2682 my $headrev;
2683 my $logged = delete $self->{logged_rev_props};
2684 if (!$logged || $self->{-want_revprops}) {
2685 my $rp = $self->ra->rev_proplist($rev);
2686 foreach (sort keys %$rp) {
2687 my $v = $rp->{$_};
2688 if (/^svn:(author|date|log)$/) {
2689 $log_entry{$1} = $v;
2690 } elsif ($_ eq 'svm:headrev') {
2691 $headrev = $v;
2692 } else {
2693 print $un " rev_prop: ", uri_encode($_), ' ',
2694 uri_encode($v), "\n";
2697 } else {
2698 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2700 close $un or croak $!;
2702 $log_entry{date} = parse_svn_date($log_entry{date});
2703 $log_entry{log} .= "\n";
2704 my $author = $log_entry{author} = check_author($log_entry{author});
2705 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2706 : ($author, undef);
2708 my ($commit_name, $commit_email) = ($name, $email);
2709 if ($_use_log_author) {
2710 my $name_field;
2711 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2712 $name_field = $1;
2713 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2714 $name_field = $1;
2716 if (!defined $name_field) {
2717 if (!defined $email) {
2718 $email = $name;
2720 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2721 ($name, $email) = ($1, $2);
2722 } elsif ($name_field =~ /(.*)@/) {
2723 ($name, $email) = ($1, $name_field);
2724 } else {
2725 ($name, $email) = ($name_field, $name_field);
2728 if (defined $headrev && $self->use_svm_props) {
2729 if ($self->rewrite_root) {
2730 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2731 "options set!\n";
2733 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2734 # we don't want "SVM: initializing mirror for junk" ...
2735 return undef if $r == 0;
2736 my $svm = $self->svm;
2737 if ($uuid ne $svm->{uuid}) {
2738 die "UUID mismatch on SVM path:\n",
2739 "expected: $svm->{uuid}\n",
2740 " got: $uuid\n";
2742 my $full_url = $self->full_url;
2743 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2744 die "Failed to replace '$svm->{replace}' with ",
2745 "'$svm->{source}' in $full_url\n";
2746 # throw away username for storing in records
2747 remove_username($full_url);
2748 $log_entry{metadata} = "$full_url\@$r $uuid";
2749 $log_entry{svm_revision} = $r;
2750 $email ||= "$author\@$uuid";
2751 $commit_email ||= "$author\@$uuid";
2752 } elsif ($self->use_svnsync_props) {
2753 my $full_url = $self->svnsync->{url};
2754 $full_url .= "/$self->{path}" if length $self->{path};
2755 remove_username($full_url);
2756 my $uuid = $self->svnsync->{uuid};
2757 $log_entry{metadata} = "$full_url\@$rev $uuid";
2758 $email ||= "$author\@$uuid";
2759 $commit_email ||= "$author\@$uuid";
2760 } else {
2761 my $url = $self->metadata_url;
2762 remove_username($url);
2763 $log_entry{metadata} = "$url\@$rev " .
2764 $self->ra->get_uuid;
2765 $email ||= "$author\@" . $self->ra->get_uuid;
2766 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2768 $log_entry{name} = $name;
2769 $log_entry{email} = $email;
2770 $log_entry{commit_name} = $commit_name;
2771 $log_entry{commit_email} = $commit_email;
2772 \%log_entry;
2775 sub fetch {
2776 my ($self, $min_rev, $max_rev, @parents) = @_;
2777 my ($last_rev, $last_commit) = $self->last_rev_commit;
2778 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2779 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2782 sub set_tree_cb {
2783 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2784 $self->{inject_parents} = { $rev => $tree };
2785 $self->fetch(undef, undef);
2788 sub set_tree {
2789 my ($self, $tree) = (shift, shift);
2790 my $log_entry = ::get_commit_entry($tree);
2791 unless ($self->{last_rev}) {
2792 ::fatal("Must have an existing revision to commit");
2794 my %ed_opts = ( r => $self->{last_rev},
2795 log => $log_entry->{log},
2796 ra => $self->ra,
2797 tree_a => $self->{last_commit},
2798 tree_b => $tree,
2799 editor_cb => sub {
2800 $self->set_tree_cb($log_entry, $tree, @_) },
2801 svn_path => $self->{path} );
2802 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2803 print "No changes\nr$self->{last_rev} = $tree\n";
2807 sub rebuild_from_rev_db {
2808 my ($self, $path) = @_;
2809 my $r = -1;
2810 open my $fh, '<', $path or croak "open: $!";
2811 binmode $fh or croak "binmode: $!";
2812 while (<$fh>) {
2813 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2814 chomp($_);
2815 ++$r;
2816 next if $_ eq ('0' x 40);
2817 $self->rev_map_set($r, $_);
2818 print "r$r = $_\n";
2820 close $fh or croak "close: $!";
2821 unlink $path or croak "unlink: $!";
2824 sub rebuild {
2825 my ($self) = @_;
2826 my $map_path = $self->map_path;
2827 my $partial = (-e $map_path && ! -z $map_path);
2828 return unless ::verify_ref($self->refname.'^0');
2829 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2830 my $rev_db = $self->rev_db_path;
2831 $self->rebuild_from_rev_db($rev_db);
2832 if ($self->use_svm_props) {
2833 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2834 $self->rebuild_from_rev_db($svm_rev_db);
2836 $self->unlink_rev_db_symlink;
2837 return;
2839 print "Rebuilding $map_path ...\n" if (!$partial);
2840 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2841 (undef, undef));
2842 my ($log, $ctx) =
2843 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2844 ($head ? "$head.." : "") . $self->refname,
2845 '--');
2846 my $metadata_url = $self->metadata_url;
2847 remove_username($metadata_url);
2848 my $svn_uuid = $self->ra_uuid;
2849 my $c;
2850 while (<$log>) {
2851 if ( m{^commit ($::sha1)$} ) {
2852 $c = $1;
2853 next;
2855 next unless s{^\s*(git-svn-id:)}{$1};
2856 my ($url, $rev, $uuid) = ::extract_metadata($_);
2857 remove_username($url);
2859 # ignore merges (from set-tree)
2860 next if (!defined $rev || !$uuid);
2862 # if we merged or otherwise started elsewhere, this is
2863 # how we break out of it
2864 if (($uuid ne $svn_uuid) ||
2865 ($metadata_url && $url && ($url ne $metadata_url))) {
2866 next;
2868 if ($partial && $head) {
2869 print "Partial-rebuilding $map_path ...\n";
2870 print "Currently at $base_rev = $head\n";
2871 $head = undef;
2874 $self->rev_map_set($rev, $c);
2875 print "r$rev = $c\n";
2877 command_close_pipe($log, $ctx);
2878 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2879 my $rev_db_path = $self->rev_db_path;
2880 if (-f $self->rev_db_path) {
2881 unlink $self->rev_db_path or croak "unlink: $!";
2883 $self->unlink_rev_db_symlink;
2886 # rev_map:
2887 # Tie::File seems to be prone to offset errors if revisions get sparse,
2888 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2889 # one of my favorite modules is out :< Next up would be one of the DBM
2890 # modules, but I'm not sure which is most portable...
2892 # This is the replacement for the rev_db format, which was too big
2893 # and inefficient for large repositories with a lot of sparse history
2894 # (mainly tags)
2896 # The format is this:
2897 # - 24 bytes for every record,
2898 # * 4 bytes for the integer representing an SVN revision number
2899 # * 20 bytes representing the sha1 of a git commit
2900 # - No empty padding records like the old format
2901 # (except the last record, which can be overwritten)
2902 # - new records are written append-only since SVN revision numbers
2903 # increase monotonically
2904 # - lookups on SVN revision number are done via a binary search
2905 # - Piping the file to xxd -c24 is a good way of dumping it for
2906 # viewing or editing (piped back through xxd -r), should the need
2907 # ever arise.
2908 # - The last record can be padding revision with an all-zero sha1
2909 # This is used to optimize fetch performance when using multiple
2910 # "fetch" directives in .git/config
2912 # These files are disposable unless noMetadata or useSvmProps is set
2914 sub _rev_map_set {
2915 my ($fh, $rev, $commit) = @_;
2917 binmode $fh or croak "binmode: $!";
2918 my $size = (stat($fh))[7];
2919 ($size % 24) == 0 or croak "inconsistent size: $size";
2921 my $wr_offset = 0;
2922 if ($size > 0) {
2923 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2924 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2925 $read == 24 or croak "read only $read bytes (!= 24)";
2926 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2927 if ($last_commit eq ('0' x40)) {
2928 if ($size >= 48) {
2929 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2930 $read = sysread($fh, $buf, 24) or
2931 croak "read: $!";
2932 $read == 24 or
2933 croak "read only $read bytes (!= 24)";
2934 ($last_rev, $last_commit) =
2935 unpack(rev_map_fmt, $buf);
2936 if ($last_commit eq ('0' x40)) {
2937 croak "inconsistent .rev_map\n";
2940 if ($last_rev >= $rev) {
2941 croak "last_rev is higher!: $last_rev >= $rev";
2943 $wr_offset = -24;
2946 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2947 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2948 croak "write: $!";
2951 sub mkfile {
2952 my ($path) = @_;
2953 unless (-e $path) {
2954 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2955 mkpath([$dir]) unless -d $dir;
2956 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2957 close $fh or die "Couldn't close (create) $path: $!\n";
2961 sub rev_map_set {
2962 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2963 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2964 my $db = $self->map_path($uuid);
2965 my $db_lock = "$db.lock";
2966 my $sig;
2967 if ($update_ref) {
2968 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2969 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2971 mkfile($db);
2973 $LOCKFILES{$db_lock} = 1;
2974 my $sync;
2975 # both of these options make our .rev_db file very, very important
2976 # and we can't afford to lose it because rebuild() won't work
2977 if ($self->use_svm_props || $self->no_metadata) {
2978 $sync = 1;
2979 copy($db, $db_lock) or die "rev_map_set(@_): ",
2980 "Failed to copy: ",
2981 "$db => $db_lock ($!)\n";
2982 } else {
2983 rename $db, $db_lock or die "rev_map_set(@_): ",
2984 "Failed to rename: ",
2985 "$db => $db_lock ($!)\n";
2988 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2989 or croak "Couldn't open $db_lock: $!\n";
2990 _rev_map_set($fh, $rev, $commit);
2991 if ($sync) {
2992 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2993 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2995 close $fh or croak $!;
2996 if ($update_ref) {
2997 $_head = $self;
2998 command_noisy('update-ref', '-m', "r$rev",
2999 $self->refname, $commit);
3001 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3002 "$db_lock => $db ($!)\n";
3003 delete $LOCKFILES{$db_lock};
3004 if ($update_ref) {
3005 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3006 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3007 kill $sig, $$ if defined $sig;
3011 # If want_commit, this will return an array of (rev, commit) where
3012 # commit _must_ be a valid commit in the archive.
3013 # Otherwise, it'll return the max revision (whether or not the
3014 # commit is valid or just a 0x40 placeholder).
3015 sub rev_map_max {
3016 my ($self, $want_commit) = @_;
3017 $self->rebuild;
3018 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3019 $want_commit ? ($r, $c) : $r;
3022 sub rev_map_max_norebuild {
3023 my ($self, $want_commit) = @_;
3024 my $map_path = $self->map_path;
3025 stat $map_path or return $want_commit ? (0, undef) : 0;
3026 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3027 binmode $fh or croak "binmode: $!";
3028 my $size = (stat($fh))[7];
3029 ($size % 24) == 0 or croak "inconsistent size: $size";
3031 if ($size == 0) {
3032 close $fh or croak "close: $!";
3033 return $want_commit ? (0, undef) : 0;
3036 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3037 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3038 my ($r, $c) = unpack(rev_map_fmt, $buf);
3039 if ($want_commit && $c eq ('0' x40)) {
3040 if ($size < 48) {
3041 return $want_commit ? (0, undef) : 0;
3043 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3044 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3045 ($r, $c) = unpack(rev_map_fmt, $buf);
3046 if ($c eq ('0'x40)) {
3047 croak "Penultimate record is all-zeroes in $map_path";
3050 close $fh or croak "close: $!";
3051 $want_commit ? ($r, $c) : $r;
3054 sub rev_map_get {
3055 my ($self, $rev, $uuid) = @_;
3056 my $map_path = $self->map_path($uuid);
3057 return undef unless -e $map_path;
3059 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3060 binmode $fh or croak "binmode: $!";
3061 my $size = (stat($fh))[7];
3062 ($size % 24) == 0 or croak "inconsistent size: $size";
3064 if ($size == 0) {
3065 close $fh or croak "close: $fh";
3066 return undef;
3069 my ($l, $u) = (0, $size - 24);
3070 my ($r, $c, $buf);
3072 while ($l <= $u) {
3073 my $i = int(($l/24 + $u/24) / 2) * 24;
3074 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3075 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3076 my ($r, $c) = unpack('NH40', $buf);
3078 if ($r < $rev) {
3079 $l = $i + 24;
3080 } elsif ($r > $rev) {
3081 $u = $i - 24;
3082 } else { # $r == $rev
3083 close($fh) or croak "close: $!";
3084 return $c eq ('0' x 40) ? undef : $c;
3087 close($fh) or croak "close: $!";
3088 undef;
3091 # Finds the first svn revision that exists on (if $eq_ok is true) or
3092 # before $rev for the current branch. It will not search any lower
3093 # than $min_rev. Returns the git commit hash and svn revision number
3094 # if found, else (undef, undef).
3095 sub find_rev_before {
3096 my ($self, $rev, $eq_ok, $min_rev) = @_;
3097 --$rev unless $eq_ok;
3098 $min_rev ||= 1;
3099 while ($rev >= $min_rev) {
3100 if (my $c = $self->rev_map_get($rev)) {
3101 return ($rev, $c);
3103 --$rev;
3105 return (undef, undef);
3108 # Finds the first svn revision that exists on (if $eq_ok is true) or
3109 # after $rev for the current branch. It will not search any higher
3110 # than $max_rev. Returns the git commit hash and svn revision number
3111 # if found, else (undef, undef).
3112 sub find_rev_after {
3113 my ($self, $rev, $eq_ok, $max_rev) = @_;
3114 ++$rev unless $eq_ok;
3115 $max_rev ||= $self->rev_map_max;
3116 while ($rev <= $max_rev) {
3117 if (my $c = $self->rev_map_get($rev)) {
3118 return ($rev, $c);
3120 ++$rev;
3122 return (undef, undef);
3125 sub _new {
3126 my ($class, $repo_id, $ref_id, $path) = @_;
3127 unless (defined $repo_id && length $repo_id) {
3128 $repo_id = $Git::SVN::default_repo_id;
3130 unless (defined $ref_id && length $ref_id) {
3131 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3133 $_[1] = $repo_id;
3134 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3135 $_[3] = $path = '' unless (defined $path);
3136 mkpath(["$ENV{GIT_DIR}/svn"]);
3137 bless {
3138 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3139 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3140 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3143 # for read-only access of old .rev_db formats
3144 sub unlink_rev_db_symlink {
3145 my ($self) = @_;
3146 my $link = $self->rev_db_path;
3147 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3148 if (-l $link) {
3149 unlink $link or croak "unlink: $link failed!";
3153 sub rev_db_path {
3154 my ($self, $uuid) = @_;
3155 my $db_path = $self->map_path($uuid);
3156 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3157 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3158 $db_path;
3161 # the new replacement for .rev_db
3162 sub map_path {
3163 my ($self, $uuid) = @_;
3164 $uuid ||= $self->ra_uuid;
3165 "$self->{map_root}.$uuid";
3168 sub uri_encode {
3169 my ($f) = @_;
3170 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3174 sub remove_username {
3175 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3178 package Git::SVN::Prompt;
3179 use strict;
3180 use warnings;
3181 require SVN::Core;
3182 use vars qw/$_no_auth_cache $_username/;
3184 sub simple {
3185 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3186 $may_save = undef if $_no_auth_cache;
3187 $default_username = $_username if defined $_username;
3188 if (defined $default_username && length $default_username) {
3189 if (defined $realm && length $realm) {
3190 print STDERR "Authentication realm: $realm\n";
3191 STDERR->flush;
3193 $cred->username($default_username);
3194 } else {
3195 username($cred, $realm, $may_save, $pool);
3197 $cred->password(_read_password("Password for '" .
3198 $cred->username . "': ", $realm));
3199 $cred->may_save($may_save);
3200 $SVN::_Core::SVN_NO_ERROR;
3203 sub ssl_server_trust {
3204 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3205 $may_save = undef if $_no_auth_cache;
3206 print STDERR "Error validating server certificate for '$realm':\n";
3208 no warnings 'once';
3209 # All variables SVN::Auth::SSL::* are used only once,
3210 # so we're shutting up Perl warnings about this.
3211 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3212 print STDERR " - The certificate is not issued ",
3213 "by a trusted authority. Use the\n",
3214 " fingerprint to validate ",
3215 "the certificate manually!\n";
3217 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3218 print STDERR " - The certificate hostname ",
3219 "does not match.\n";
3221 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3222 print STDERR " - The certificate is not yet valid.\n";
3224 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3225 print STDERR " - The certificate has expired.\n";
3227 if ($failures & $SVN::Auth::SSL::OTHER) {
3228 print STDERR " - The certificate has ",
3229 "an unknown error.\n";
3231 } # no warnings 'once'
3232 printf STDERR
3233 "Certificate information:\n".
3234 " - Hostname: %s\n".
3235 " - Valid: from %s until %s\n".
3236 " - Issuer: %s\n".
3237 " - Fingerprint: %s\n",
3238 map $cert_info->$_, qw(hostname valid_from valid_until
3239 issuer_dname fingerprint);
3240 my $choice;
3241 prompt:
3242 print STDERR $may_save ?
3243 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3244 "(R)eject or accept (t)emporarily? ";
3245 STDERR->flush;
3246 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3247 if ($choice =~ /^t$/i) {
3248 $cred->may_save(undef);
3249 } elsif ($choice =~ /^r$/i) {
3250 return -1;
3251 } elsif ($may_save && $choice =~ /^p$/i) {
3252 $cred->may_save($may_save);
3253 } else {
3254 goto prompt;
3256 $cred->accepted_failures($failures);
3257 $SVN::_Core::SVN_NO_ERROR;
3260 sub ssl_client_cert {
3261 my ($cred, $realm, $may_save, $pool) = @_;
3262 $may_save = undef if $_no_auth_cache;
3263 print STDERR "Client certificate filename: ";
3264 STDERR->flush;
3265 chomp(my $filename = <STDIN>);
3266 $cred->cert_file($filename);
3267 $cred->may_save($may_save);
3268 $SVN::_Core::SVN_NO_ERROR;
3271 sub ssl_client_cert_pw {
3272 my ($cred, $realm, $may_save, $pool) = @_;
3273 $may_save = undef if $_no_auth_cache;
3274 $cred->password(_read_password("Password: ", $realm));
3275 $cred->may_save($may_save);
3276 $SVN::_Core::SVN_NO_ERROR;
3279 sub username {
3280 my ($cred, $realm, $may_save, $pool) = @_;
3281 $may_save = undef if $_no_auth_cache;
3282 if (defined $realm && length $realm) {
3283 print STDERR "Authentication realm: $realm\n";
3285 my $username;
3286 if (defined $_username) {
3287 $username = $_username;
3288 } else {
3289 print STDERR "Username: ";
3290 STDERR->flush;
3291 chomp($username = <STDIN>);
3293 $cred->username($username);
3294 $cred->may_save($may_save);
3295 $SVN::_Core::SVN_NO_ERROR;
3298 sub _read_password {
3299 my ($prompt, $realm) = @_;
3300 print STDERR $prompt;
3301 STDERR->flush;
3302 require Term::ReadKey;
3303 Term::ReadKey::ReadMode('noecho');
3304 my $password = '';
3305 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3306 last if $key =~ /[\012\015]/; # \n\r
3307 $password .= $key;
3309 Term::ReadKey::ReadMode('restore');
3310 print STDERR "\n";
3311 STDERR->flush;
3312 $password;
3315 package SVN::Git::Fetcher;
3316 use vars qw/@ISA/;
3317 use strict;
3318 use warnings;
3319 use Carp qw/croak/;
3320 use File::Temp qw/tempfile/;
3321 use IO::File qw//;
3322 use vars qw/$_ignore_regex/;
3324 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3325 sub new {
3326 my ($class, $git_svn, $switch_path) = @_;
3327 my $self = SVN::Delta::Editor->new;
3328 bless $self, $class;
3329 if (exists $git_svn->{last_commit}) {
3330 $self->{c} = $git_svn->{last_commit};
3331 $self->{empty_symlinks} =
3332 _mark_empty_symlinks($git_svn, $switch_path);
3334 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3335 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3336 $self->{empty} = {};
3337 $self->{dir_prop} = {};
3338 $self->{file_prop} = {};
3339 $self->{absent_dir} = {};
3340 $self->{absent_file} = {};
3341 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3342 $self;
3345 # this uses the Ra object, so it must be called before do_{switch,update},
3346 # not inside them (when the Git::SVN::Fetcher object is passed) to
3347 # do_{switch,update}
3348 sub _mark_empty_symlinks {
3349 my ($git_svn, $switch_path) = @_;
3350 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3351 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3353 my %ret;
3354 my ($rev, $cmt) = $git_svn->last_rev_commit;
3355 return {} unless ($rev && $cmt);
3357 # allow the warning to be printed for each revision we fetch to
3358 # ensure the user sees it. The user can also disable the workaround
3359 # on the repository even while git svn is running and the next
3360 # revision fetched will skip this expensive function.
3361 my $printed_warning;
3362 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3363 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3364 local $/ = "\0";
3365 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3366 $pfx .= '/' if length($pfx);
3367 while (<$ls>) {
3368 chomp;
3369 s/\A100644 blob $empty_blob\t//o or next;
3370 unless ($printed_warning) {
3371 print STDERR "Scanning for empty symlinks, ",
3372 "this may take a while if you have ",
3373 "many empty files\n",
3374 "You may disable this with `",
3375 "git config svn.brokenSymlinkWorkaround ",
3376 "false'.\n",
3377 "This may be done in a different ",
3378 "terminal without restarting ",
3379 "git svn\n";
3380 $printed_warning = 1;
3382 my $path = $_;
3383 my (undef, $props) =
3384 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3385 if ($props->{'svn:special'}) {
3386 $ret{$path} = 1;
3389 command_close_pipe($ls, $ctx);
3390 \%ret;
3393 # returns true if a given path is inside a ".git" directory
3394 sub in_dot_git {
3395 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3398 # return value: 0 -- don't ignore, 1 -- ignore
3399 sub is_path_ignored {
3400 my ($self, $path) = @_;
3401 return 1 if in_dot_git($path);
3402 return 1 if defined($self->{ignore_regex}) &&
3403 $path =~ m!$self->{ignore_regex}!;
3404 return 0 unless defined($_ignore_regex);
3405 return 1 if $path =~ m!$_ignore_regex!o;
3406 return 0;
3409 sub set_path_strip {
3410 my ($self, $path) = @_;
3411 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3414 sub open_root {
3415 { path => '' };
3418 sub open_directory {
3419 my ($self, $path, $pb, $rev) = @_;
3420 { path => $path };
3423 sub git_path {
3424 my ($self, $path) = @_;
3425 if ($self->{path_strip}) {
3426 $path =~ s!$self->{path_strip}!! or
3427 die "Failed to strip path '$path' ($self->{path_strip})\n";
3429 $path;
3432 sub delete_entry {
3433 my ($self, $path, $rev, $pb) = @_;
3434 return undef if $self->is_path_ignored($path);
3436 my $gpath = $self->git_path($path);
3437 return undef if ($gpath eq '');
3439 # remove entire directories.
3440 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3441 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3442 if ($tree) {
3443 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3444 -r --name-only -z/,
3445 $tree);
3446 local $/ = "\0";
3447 while (<$ls>) {
3448 chomp;
3449 my $rmpath = "$gpath/$_";
3450 $self->{gii}->remove($rmpath);
3451 print "\tD\t$rmpath\n" unless $::_q;
3453 print "\tD\t$gpath/\n" unless $::_q;
3454 command_close_pipe($ls, $ctx);
3455 $self->{empty}->{$path} = 0
3456 } else {
3457 $self->{gii}->remove($gpath);
3458 print "\tD\t$gpath\n" unless $::_q;
3460 undef;
3463 sub open_file {
3464 my ($self, $path, $pb, $rev) = @_;
3465 my ($mode, $blob);
3467 goto out if $self->is_path_ignored($path);
3469 my $gpath = $self->git_path($path);
3470 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3471 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3472 unless (defined $mode && defined $blob) {
3473 die "$path was not found in commit $self->{c} (r$rev)\n";
3475 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3476 $mode = '120000';
3478 out:
3479 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3480 pool => SVN::Pool->new, action => 'M' };
3483 sub add_file {
3484 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3485 my $mode;
3487 if (!$self->is_path_ignored($path)) {
3488 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3489 delete $self->{empty}->{$dir};
3490 $mode = '100644';
3492 { path => $path, mode_a => $mode, mode_b => $mode,
3493 pool => SVN::Pool->new, action => 'A' };
3496 sub add_directory {
3497 my ($self, $path, $cp_path, $cp_rev) = @_;
3498 goto out if $self->is_path_ignored($path);
3499 my $gpath = $self->git_path($path);
3500 if ($gpath eq '') {
3501 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3502 -r --name-only -z/,
3503 $self->{c});
3504 local $/ = "\0";
3505 while (<$ls>) {
3506 chomp;
3507 $self->{gii}->remove($_);
3508 print "\tD\t$_\n" unless $::_q;
3510 command_close_pipe($ls, $ctx);
3511 $self->{empty}->{$path} = 0;
3513 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3514 delete $self->{empty}->{$dir};
3515 $self->{empty}->{$path} = 1;
3516 out:
3517 { path => $path };
3520 sub change_dir_prop {
3521 my ($self, $db, $prop, $value) = @_;
3522 return undef if $self->is_path_ignored($db->{path});
3523 $self->{dir_prop}->{$db->{path}} ||= {};
3524 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3525 undef;
3528 sub absent_directory {
3529 my ($self, $path, $pb) = @_;
3530 return undef if $self->is_path_ignored($path);
3531 $self->{absent_dir}->{$pb->{path}} ||= [];
3532 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3533 undef;
3536 sub absent_file {
3537 my ($self, $path, $pb) = @_;
3538 return undef if $self->is_path_ignored($path);
3539 $self->{absent_file}->{$pb->{path}} ||= [];
3540 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3541 undef;
3544 sub change_file_prop {
3545 my ($self, $fb, $prop, $value) = @_;
3546 return undef if $self->is_path_ignored($fb->{path});
3547 if ($prop eq 'svn:executable') {
3548 if ($fb->{mode_b} != 120000) {
3549 $fb->{mode_b} = defined $value ? 100755 : 100644;
3551 } elsif ($prop eq 'svn:special') {
3552 $fb->{mode_b} = defined $value ? 120000 : 100644;
3553 } else {
3554 $self->{file_prop}->{$fb->{path}} ||= {};
3555 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3557 undef;
3560 sub apply_textdelta {
3561 my ($self, $fb, $exp) = @_;
3562 return undef if $self->is_path_ignored($fb->{path});
3563 my $fh = $::_repository->temp_acquire('svn_delta');
3564 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3565 # (but $base does not,) so dup() it for reading in close_file
3566 open my $dup, '<&', $fh or croak $!;
3567 my $base = $::_repository->temp_acquire('git_blob');
3569 if ($fb->{blob}) {
3570 my ($base_is_link, $size);
3572 if ($fb->{mode_a} eq '120000' &&
3573 ! $self->{empty_symlinks}->{$fb->{path}}) {
3574 print $base 'link ' or die "print $!\n";
3575 $base_is_link = 1;
3577 retry:
3578 $size = $::_repository->cat_blob($fb->{blob}, $base);
3579 die "Failed to read object $fb->{blob}" if ($size < 0);
3581 if (defined $exp) {
3582 seek $base, 0, 0 or croak $!;
3583 my $got = ::md5sum($base);
3584 if ($got ne $exp) {
3585 my $err = "Checksum mismatch: ".
3586 "$fb->{path} $fb->{blob}\n" .
3587 "expected: $exp\n" .
3588 " got: $got\n";
3589 if ($base_is_link) {
3590 warn $err,
3591 "Retrying... (possibly ",
3592 "a bad symlink from SVN)\n";
3593 $::_repository->temp_reset($base);
3594 $base_is_link = 0;
3595 goto retry;
3597 die $err;
3601 seek $base, 0, 0 or croak $!;
3602 $fb->{fh} = $fh;
3603 $fb->{base} = $base;
3604 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3607 sub close_file {
3608 my ($self, $fb, $exp) = @_;
3609 return undef if $self->is_path_ignored($fb->{path});
3611 my $hash;
3612 my $path = $self->git_path($fb->{path});
3613 if (my $fh = $fb->{fh}) {
3614 if (defined $exp) {
3615 seek($fh, 0, 0) or croak $!;
3616 my $got = ::md5sum($fh);
3617 if ($got ne $exp) {
3618 die "Checksum mismatch: $path\n",
3619 "expected: $exp\n got: $got\n";
3622 if ($fb->{mode_b} == 120000) {
3623 sysseek($fh, 0, 0) or croak $!;
3624 my $rd = sysread($fh, my $buf, 5);
3626 if (!defined $rd) {
3627 croak "sysread: $!\n";
3628 } elsif ($rd == 0) {
3629 warn "$path has mode 120000",
3630 " but it points to nothing\n",
3631 "converting to an empty file with mode",
3632 " 100644\n";
3633 $fb->{mode_b} = '100644';
3634 } elsif ($buf ne 'link ') {
3635 warn "$path has mode 120000",
3636 " but is not a link\n";
3637 } else {
3638 my $tmp_fh = $::_repository->temp_acquire(
3639 'svn_hash');
3640 my $res;
3641 while ($res = sysread($fh, my $str, 1024)) {
3642 my $out = syswrite($tmp_fh, $str, $res);
3643 defined($out) && $out == $res
3644 or croak("write ",
3645 Git::temp_path($tmp_fh),
3646 ": $!\n");
3648 defined $res or croak $!;
3650 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3651 Git::temp_release($tmp_fh, 1);
3655 $hash = $::_repository->hash_and_insert_object(
3656 Git::temp_path($fh));
3657 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3659 Git::temp_release($fb->{base}, 1);
3660 Git::temp_release($fh, 1);
3661 } else {
3662 $hash = $fb->{blob} or die "no blob information\n";
3664 $fb->{pool}->clear;
3665 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3666 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3667 undef;
3670 sub abort_edit {
3671 my $self = shift;
3672 $self->{nr} = $self->{gii}->{nr};
3673 delete $self->{gii};
3674 $self->SUPER::abort_edit(@_);
3677 sub close_edit {
3678 my $self = shift;
3679 $self->{git_commit_ok} = 1;
3680 $self->{nr} = $self->{gii}->{nr};
3681 delete $self->{gii};
3682 $self->SUPER::close_edit(@_);
3685 package SVN::Git::Editor;
3686 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3687 use strict;
3688 use warnings;
3689 use Carp qw/croak/;
3690 use IO::File;
3692 sub new {
3693 my ($class, $opts) = @_;
3694 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3695 die "$_ required!\n" unless (defined $opts->{$_});
3698 my $pool = SVN::Pool->new;
3699 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3700 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3701 $opts->{r}, $mods);
3703 # $opts->{ra} functions should not be used after this:
3704 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3705 $opts->{editor_cb}, $pool);
3706 my $self = SVN::Delta::Editor->new(@ce, $pool);
3707 bless $self, $class;
3708 foreach (qw/svn_path r tree_a tree_b/) {
3709 $self->{$_} = $opts->{$_};
3711 $self->{url} = $opts->{ra}->{url};
3712 $self->{mods} = $mods;
3713 $self->{types} = $types;
3714 $self->{pool} = $pool;
3715 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3716 $self->{rm} = { };
3717 $self->{path_prefix} = length $self->{svn_path} ?
3718 "$self->{svn_path}/" : '';
3719 $self->{config} = $opts->{config};
3720 return $self;
3723 sub generate_diff {
3724 my ($tree_a, $tree_b) = @_;
3725 my @diff_tree = qw(diff-tree -z -r);
3726 if ($_cp_similarity) {
3727 push @diff_tree, "-C$_cp_similarity";
3728 } else {
3729 push @diff_tree, '-C';
3731 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3732 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3733 push @diff_tree, $tree_a, $tree_b;
3734 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3735 local $/ = "\0";
3736 my $state = 'meta';
3737 my @mods;
3738 while (<$diff_fh>) {
3739 chomp $_; # this gets rid of the trailing "\0"
3740 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3741 ($::sha1)\s($::sha1)\s
3742 ([MTCRAD])\d*$/xo) {
3743 push @mods, { mode_a => $1, mode_b => $2,
3744 sha1_a => $3, sha1_b => $4,
3745 chg => $5 };
3746 if ($5 =~ /^(?:C|R)$/) {
3747 $state = 'file_a';
3748 } else {
3749 $state = 'file_b';
3751 } elsif ($state eq 'file_a') {
3752 my $x = $mods[$#mods] or croak "Empty array\n";
3753 if ($x->{chg} !~ /^(?:C|R)$/) {
3754 croak "Error parsing $_, $x->{chg}\n";
3756 $x->{file_a} = $_;
3757 $state = 'file_b';
3758 } elsif ($state eq 'file_b') {
3759 my $x = $mods[$#mods] or croak "Empty array\n";
3760 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3761 croak "Error parsing $_, $x->{chg}\n";
3763 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3764 croak "Error parsing $_, $x->{chg}\n";
3766 $x->{file_b} = $_;
3767 $state = 'meta';
3768 } else {
3769 croak "Error parsing $_\n";
3772 command_close_pipe($diff_fh, $ctx);
3773 \@mods;
3776 sub check_diff_paths {
3777 my ($ra, $pfx, $rev, $mods) = @_;
3778 my %types;
3779 $pfx .= '/' if length $pfx;
3781 sub type_diff_paths {
3782 my ($ra, $types, $path, $rev) = @_;
3783 my @p = split m#/+#, $path;
3784 my $c = shift @p;
3785 unless (defined $types->{$c}) {
3786 $types->{$c} = $ra->check_path($c, $rev);
3788 while (@p) {
3789 $c .= '/' . shift @p;
3790 next if defined $types->{$c};
3791 $types->{$c} = $ra->check_path($c, $rev);
3795 foreach my $m (@$mods) {
3796 foreach my $f (qw/file_a file_b/) {
3797 next unless defined $m->{$f};
3798 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3799 if (length $pfx.$dir && ! defined $types{$dir}) {
3800 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3804 \%types;
3807 sub split_path {
3808 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3811 sub repo_path {
3812 my ($self, $path) = @_;
3813 $self->{path_prefix}.(defined $path ? $path : '');
3816 sub url_path {
3817 my ($self, $path) = @_;
3818 if ($self->{url} =~ m#^https?://#) {
3819 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3821 $self->{url} . '/' . $self->repo_path($path);
3824 sub rmdirs {
3825 my ($self) = @_;
3826 my $rm = $self->{rm};
3827 delete $rm->{''}; # we never delete the url we're tracking
3828 return unless %$rm;
3830 foreach (keys %$rm) {
3831 my @d = split m#/#, $_;
3832 my $c = shift @d;
3833 $rm->{$c} = 1;
3834 while (@d) {
3835 $c .= '/' . shift @d;
3836 $rm->{$c} = 1;
3839 delete $rm->{$self->{svn_path}};
3840 delete $rm->{''}; # we never delete the url we're tracking
3841 return unless %$rm;
3843 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3844 $self->{tree_b});
3845 local $/ = "\0";
3846 while (<$fh>) {
3847 chomp;
3848 my @dn = split m#/#, $_;
3849 while (pop @dn) {
3850 delete $rm->{join '/', @dn};
3852 unless (%$rm) {
3853 close $fh;
3854 return;
3857 command_close_pipe($fh, $ctx);
3859 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3860 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3861 $self->close_directory($bat->{$d}, $p);
3862 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3863 print "\tD+\t$d/\n" unless $::_q;
3864 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3865 delete $bat->{$d};
3869 sub open_or_add_dir {
3870 my ($self, $full_path, $baton) = @_;
3871 my $t = $self->{types}->{$full_path};
3872 if (!defined $t) {
3873 die "$full_path not known in r$self->{r} or we have a bug!\n";
3876 no warnings 'once';
3877 # SVN::Node::none and SVN::Node::file are used only once,
3878 # so we're shutting up Perl's warnings about them.
3879 if ($t == $SVN::Node::none) {
3880 return $self->add_directory($full_path, $baton,
3881 undef, -1, $self->{pool});
3882 } elsif ($t == $SVN::Node::dir) {
3883 return $self->open_directory($full_path, $baton,
3884 $self->{r}, $self->{pool});
3885 } # no warnings 'once'
3886 print STDERR "$full_path already exists in repository at ",
3887 "r$self->{r} and it is not a directory (",
3888 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3889 } # no warnings 'once'
3890 exit 1;
3893 sub ensure_path {
3894 my ($self, $path) = @_;
3895 my $bat = $self->{bat};
3896 my $repo_path = $self->repo_path($path);
3897 return $bat->{''} unless (length $repo_path);
3898 my @p = split m#/+#, $repo_path;
3899 my $c = shift @p;
3900 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3901 while (@p) {
3902 my $c0 = $c;
3903 $c .= '/' . shift @p;
3904 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3906 return $bat->{$c};
3909 # Subroutine to convert a globbing pattern to a regular expression.
3910 # From perl cookbook.
3911 sub glob2pat {
3912 my $globstr = shift;
3913 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3914 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3915 return '^' . $globstr . '$';
3918 sub check_autoprop {
3919 my ($self, $pattern, $properties, $file, $fbat) = @_;
3920 # Convert the globbing pattern to a regular expression.
3921 my $regex = glob2pat($pattern);
3922 # Check if the pattern matches the file name.
3923 if($file =~ m/($regex)/) {
3924 # Parse the list of properties to set.
3925 my @props = split(/;/, $properties);
3926 foreach my $prop (@props) {
3927 # Parse 'name=value' syntax and set the property.
3928 if ($prop =~ /([^=]+)=(.*)/) {
3929 my ($n,$v) = ($1,$2);
3930 for ($n, $v) {
3931 s/^\s+//; s/\s+$//;
3933 $self->change_file_prop($fbat, $n, $v);
3939 sub apply_autoprops {
3940 my ($self, $file, $fbat) = @_;
3941 my $conf_t = ${$self->{config}}{'config'};
3942 no warnings 'once';
3943 # Check [miscellany]/enable-auto-props in svn configuration.
3944 if (SVN::_Core::svn_config_get_bool(
3945 $conf_t,
3946 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3947 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3948 0)) {
3949 # Auto-props are enabled. Enumerate them to look for matches.
3950 my $callback = sub {
3951 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3953 SVN::_Core::svn_config_enumerate(
3954 $conf_t,
3955 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3956 $callback);
3960 sub A {
3961 my ($self, $m) = @_;
3962 my ($dir, $file) = split_path($m->{file_b});
3963 my $pbat = $self->ensure_path($dir);
3964 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3965 undef, -1);
3966 print "\tA\t$m->{file_b}\n" unless $::_q;
3967 $self->apply_autoprops($file, $fbat);
3968 $self->chg_file($fbat, $m);
3969 $self->close_file($fbat,undef,$self->{pool});
3972 sub C {
3973 my ($self, $m) = @_;
3974 my ($dir, $file) = split_path($m->{file_b});
3975 my $pbat = $self->ensure_path($dir);
3976 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3977 $self->url_path($m->{file_a}), $self->{r});
3978 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3979 $self->chg_file($fbat, $m);
3980 $self->close_file($fbat,undef,$self->{pool});
3983 sub delete_entry {
3984 my ($self, $path, $pbat) = @_;
3985 my $rpath = $self->repo_path($path);
3986 my ($dir, $file) = split_path($rpath);
3987 $self->{rm}->{$dir} = 1;
3988 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3991 sub R {
3992 my ($self, $m) = @_;
3993 my ($dir, $file) = split_path($m->{file_b});
3994 my $pbat = $self->ensure_path($dir);
3995 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3996 $self->url_path($m->{file_a}), $self->{r});
3997 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3998 $self->apply_autoprops($file, $fbat);
3999 $self->chg_file($fbat, $m);
4000 $self->close_file($fbat,undef,$self->{pool});
4002 ($dir, $file) = split_path($m->{file_a});
4003 $pbat = $self->ensure_path($dir);
4004 $self->delete_entry($m->{file_a}, $pbat);
4007 sub M {
4008 my ($self, $m) = @_;
4009 my ($dir, $file) = split_path($m->{file_b});
4010 my $pbat = $self->ensure_path($dir);
4011 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4012 $pbat,$self->{r},$self->{pool});
4013 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4014 $self->chg_file($fbat, $m);
4015 $self->close_file($fbat,undef,$self->{pool});
4018 sub T { shift->M(@_) }
4020 sub change_file_prop {
4021 my ($self, $fbat, $pname, $pval) = @_;
4022 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4025 sub _chg_file_get_blob ($$$$) {
4026 my ($self, $fbat, $m, $which) = @_;
4027 my $fh = $::_repository->temp_acquire("git_blob_$which");
4028 if ($m->{"mode_$which"} =~ /^120/) {
4029 print $fh 'link ' or croak $!;
4030 $self->change_file_prop($fbat,'svn:special','*');
4031 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4032 $self->change_file_prop($fbat,'svn:special',undef);
4034 my $blob = $m->{"sha1_$which"};
4035 return ($fh,) if ($blob =~ /^0{40}$/);
4036 my $size = $::_repository->cat_blob($blob, $fh);
4037 croak "Failed to read object $blob" if ($size < 0);
4038 $fh->flush == 0 or croak $!;
4039 seek $fh, 0, 0 or croak $!;
4041 my $exp = ::md5sum($fh);
4042 seek $fh, 0, 0 or croak $!;
4043 return ($fh, $exp);
4046 sub chg_file {
4047 my ($self, $fbat, $m) = @_;
4048 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4049 $self->change_file_prop($fbat,'svn:executable','*');
4050 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4051 $self->change_file_prop($fbat,'svn:executable',undef);
4053 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4054 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4055 my $pool = SVN::Pool->new;
4056 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4057 if (-s $fh_a) {
4058 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4059 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4060 if (defined $res) {
4061 die "Unexpected result from send_txstream: $res\n",
4062 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4064 } else {
4065 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4066 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4067 if ($got ne $exp_b);
4069 Git::temp_release($fh_b, 1);
4070 Git::temp_release($fh_a, 1);
4071 $pool->clear;
4074 sub D {
4075 my ($self, $m) = @_;
4076 my ($dir, $file) = split_path($m->{file_b});
4077 my $pbat = $self->ensure_path($dir);
4078 print "\tD\t$m->{file_b}\n" unless $::_q;
4079 $self->delete_entry($m->{file_b}, $pbat);
4082 sub close_edit {
4083 my ($self) = @_;
4084 my ($p,$bat) = ($self->{pool}, $self->{bat});
4085 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4086 next if $_ eq '';
4087 $self->close_directory($bat->{$_}, $p);
4089 $self->close_directory($bat->{''}, $p);
4090 $self->SUPER::close_edit($p);
4091 $p->clear;
4094 sub abort_edit {
4095 my ($self) = @_;
4096 $self->SUPER::abort_edit($self->{pool});
4099 sub DESTROY {
4100 my $self = shift;
4101 $self->SUPER::DESTROY(@_);
4102 $self->{pool}->clear;
4105 # this drives the editor
4106 sub apply_diff {
4107 my ($self) = @_;
4108 my $mods = $self->{mods};
4109 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4110 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4111 my $f = $m->{chg};
4112 if (defined $o{$f}) {
4113 $self->$f($m);
4114 } else {
4115 fatal("Invalid change type: $f");
4118 $self->rmdirs if $_rmdir;
4119 if (@$mods == 0) {
4120 $self->abort_edit;
4121 } else {
4122 $self->close_edit;
4124 return scalar @$mods;
4127 package Git::SVN::Ra;
4128 use vars qw/@ISA $config_dir $_log_window_size/;
4129 use strict;
4130 use warnings;
4131 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4133 BEGIN {
4134 # enforce temporary pool usage for some simple functions
4135 no strict 'refs';
4136 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4137 get_file/) {
4138 my $SUPER = "SUPER::$f";
4139 *$f = sub {
4140 my $self = shift;
4141 my $pool = SVN::Pool->new;
4142 my @ret = $self->$SUPER(@_,$pool);
4143 $pool->clear;
4144 wantarray ? @ret : $ret[0];
4149 sub _auth_providers () {
4151 SVN::Client::get_simple_provider(),
4152 SVN::Client::get_ssl_server_trust_file_provider(),
4153 SVN::Client::get_simple_prompt_provider(
4154 \&Git::SVN::Prompt::simple, 2),
4155 SVN::Client::get_ssl_client_cert_file_provider(),
4156 SVN::Client::get_ssl_client_cert_prompt_provider(
4157 \&Git::SVN::Prompt::ssl_client_cert, 2),
4158 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4159 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4160 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4161 SVN::Client::get_username_provider(),
4162 SVN::Client::get_ssl_server_trust_prompt_provider(
4163 \&Git::SVN::Prompt::ssl_server_trust),
4164 SVN::Client::get_username_prompt_provider(
4165 \&Git::SVN::Prompt::username, 2)
4169 sub escape_uri_only {
4170 my ($uri) = @_;
4171 my @tmp;
4172 foreach (split m{/}, $uri) {
4173 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4174 push @tmp, $_;
4176 join('/', @tmp);
4179 sub escape_url {
4180 my ($url) = @_;
4181 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4182 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4183 $url = "$scheme://$domain$uri";
4185 $url;
4188 sub new {
4189 my ($class, $url) = @_;
4190 $url =~ s!/+$!!;
4191 return $RA if ($RA && $RA->{url} eq $url);
4193 SVN::_Core::svn_config_ensure($config_dir, undef);
4194 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4195 my $config = SVN::Core::config_get_config($config_dir);
4196 $RA = undef;
4197 my $dont_store_passwords = 1;
4198 my $conf_t = ${$config}{'config'};
4200 no warnings 'once';
4201 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4202 # produces warnings that variables are used only once.
4203 # I had not found the better way to shut them up, so
4204 # the warnings of type 'once' are disabled in this block.
4205 if (SVN::_Core::svn_config_get_bool($conf_t,
4206 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4207 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4208 1) == 0) {
4209 SVN::_Core::svn_auth_set_parameter($baton,
4210 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4211 bless (\$dont_store_passwords, "_p_void"));
4213 if (SVN::_Core::svn_config_get_bool($conf_t,
4214 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4215 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4216 1) == 0) {
4217 $Git::SVN::Prompt::_no_auth_cache = 1;
4219 } # no warnings 'once'
4220 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4221 config => $config,
4222 pool => SVN::Pool->new,
4223 auth_provider_callbacks => $callbacks);
4224 $self->{url} = $url;
4225 $self->{svn_path} = $url;
4226 $self->{repos_root} = $self->get_repos_root;
4227 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4228 $self->{cache} = { check_path => { r => 0, data => {} },
4229 get_dir => { r => 0, data => {} } };
4230 $RA = bless $self, $class;
4233 sub check_path {
4234 my ($self, $path, $r) = @_;
4235 my $cache = $self->{cache}->{check_path};
4236 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4237 return $cache->{data}->{$path};
4239 my $pool = SVN::Pool->new;
4240 my $t = $self->SUPER::check_path($path, $r, $pool);
4241 $pool->clear;
4242 if ($r != $cache->{r}) {
4243 %{$cache->{data}} = ();
4244 $cache->{r} = $r;
4246 $cache->{data}->{$path} = $t;
4249 sub get_dir {
4250 my ($self, $dir, $r) = @_;
4251 my $cache = $self->{cache}->{get_dir};
4252 if ($r == $cache->{r}) {
4253 if (my $x = $cache->{data}->{$dir}) {
4254 return wantarray ? @$x : $x->[0];
4257 my $pool = SVN::Pool->new;
4258 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4259 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4260 $pool->clear;
4261 if ($r != $cache->{r}) {
4262 %{$cache->{data}} = ();
4263 $cache->{r} = $r;
4265 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4266 wantarray ? (\%dirents, $r, $props) : \%dirents;
4269 sub DESTROY {
4270 # do not call the real DESTROY since we store ourselves in $RA
4273 # get_log(paths, start, end, limit,
4274 # discover_changed_paths, strict_node_history, receiver)
4275 sub get_log {
4276 my ($self, @args) = @_;
4277 my $pool = SVN::Pool->new;
4279 # the limit parameter was not supported in SVN 1.1.x, so we
4280 # drop it. Therefore, the receiver callback passed to it
4281 # is made aware of this limitation by being wrapped if
4282 # the limit passed to is being wrapped.
4283 if ($SVN::Core::VERSION le '1.2.0') {
4284 my $limit = splice(@args, 3, 1);
4285 if ($limit > 0) {
4286 my $receiver = pop @args;
4287 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4290 my $ret = $self->SUPER::get_log(@args, $pool);
4291 $pool->clear;
4292 $ret;
4295 sub trees_match {
4296 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4297 my $ctx = SVN::Client->new(auth => _auth_providers);
4298 my $out = IO::File->new_tmpfile;
4300 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4301 # $ctx->diff(), so we'll create a default one
4302 my $pool = SVN::Pool->new_default_sub;
4304 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4305 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4306 $out->flush;
4307 my $ret = (($out->stat)[7] == 0);
4308 close $out or croak $!;
4310 $ret;
4313 sub get_commit_editor {
4314 my ($self, $log, $cb, $pool) = @_;
4315 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4316 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4319 sub gs_do_update {
4320 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4321 my $new = ($rev_a == $rev_b);
4322 my $path = $gs->{path};
4324 if ($new && -e $gs->{index}) {
4325 unlink $gs->{index} or die
4326 "Couldn't unlink index: $gs->{index}: $!\n";
4328 my $pool = SVN::Pool->new;
4329 $editor->set_path_strip($path);
4330 my (@pc) = split m#/#, $path;
4331 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4332 1, $editor, $pool);
4333 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4335 # Since we can't rely on svn_ra_reparent being available, we'll
4336 # just have to do some magic with set_path to make it so
4337 # we only want a partial path.
4338 my $sp = '';
4339 my $final = join('/', @pc);
4340 while (@pc) {
4341 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4342 $sp .= '/' if length $sp;
4343 $sp .= shift @pc;
4345 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4347 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4349 $reporter->finish_report($pool);
4350 $pool->clear;
4351 $editor->{git_commit_ok};
4354 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4355 # svn_ra_reparent didn't work before 1.4)
4356 sub gs_do_switch {
4357 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4358 my $path = $gs->{path};
4359 my $pool = SVN::Pool->new;
4361 my $full_url = $self->{url};
4362 my $old_url = $full_url;
4363 $full_url .= '/' . escape_uri_only($path) if length $path;
4364 my ($ra, $reparented);
4366 if ($old_url =~ m#^svn(\+ssh)?://#) {
4367 $_[0] = undef;
4368 $self = undef;
4369 $RA = undef;
4370 $ra = Git::SVN::Ra->new($full_url);
4371 $ra_invalid = 1;
4372 } elsif ($old_url ne $full_url) {
4373 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4374 $self->{url} = $full_url;
4375 $reparented = 1;
4378 $ra ||= $self;
4379 $url_b = escape_url($url_b);
4380 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4381 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4382 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4383 $reporter->finish_report($pool);
4385 if ($reparented) {
4386 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4387 $self->{url} = $old_url;
4390 $pool->clear;
4391 $editor->{git_commit_ok};
4394 sub longest_common_path {
4395 my ($gsv, $globs) = @_;
4396 my %common;
4397 my $common_max = scalar @$gsv;
4399 foreach my $gs (@$gsv) {
4400 my @tmp = split m#/#, $gs->{path};
4401 my $p = '';
4402 foreach (@tmp) {
4403 $p .= length($p) ? "/$_" : $_;
4404 $common{$p} ||= 0;
4405 $common{$p}++;
4408 $globs ||= [];
4409 $common_max += scalar @$globs;
4410 foreach my $glob (@$globs) {
4411 my @tmp = split m#/#, $glob->{path}->{left};
4412 my $p = '';
4413 foreach (@tmp) {
4414 $p .= length($p) ? "/$_" : $_;
4415 $common{$p} ||= 0;
4416 $common{$p}++;
4420 my $longest_path = '';
4421 foreach (sort {length $b <=> length $a} keys %common) {
4422 if ($common{$_} == $common_max) {
4423 $longest_path = $_;
4424 last;
4427 $longest_path;
4430 sub gs_fetch_loop_common {
4431 my ($self, $base, $head, $gsv, $globs) = @_;
4432 return if ($base > $head);
4433 my $inc = $_log_window_size;
4434 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4435 my $longest_path = longest_common_path($gsv, $globs);
4436 my $ra_url = $self->{url};
4437 while (1) {
4438 my %revs;
4439 my $err;
4440 my $err_handler = $SVN::Error::handler;
4441 $SVN::Error::handler = sub {
4442 ($err) = @_;
4443 skip_unknown_revs($err);
4445 sub _cb {
4446 my ($paths, $r, $author, $date, $log) = @_;
4447 [ dup_changed_paths($paths),
4448 { author => $author, date => $date, log => $log } ];
4450 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4451 sub { $revs{$_[1]} = _cb(@_) });
4452 if ($err) {
4453 print "Checked through r$max\r";
4455 if ($err && $max >= $head) {
4456 print STDERR "Path '$longest_path' ",
4457 "was probably deleted:\n",
4458 $err->expanded_message,
4459 "\nWill attempt to follow ",
4460 "revisions r$min .. r$max ",
4461 "committed before the deletion\n";
4462 my $hi = $max;
4463 while (--$hi >= $min) {
4464 my $ok;
4465 $self->get_log([$longest_path], $min, $hi,
4466 0, 1, 1, sub {
4467 $ok ||= $_[1];
4468 $revs{$_[1]} = _cb(@_) });
4469 if ($ok) {
4470 print STDERR "r$min .. r$ok OK\n";
4471 last;
4475 $SVN::Error::handler = $err_handler;
4477 my %exists = map { $_->{path} => $_ } @$gsv;
4478 foreach my $r (sort {$a <=> $b} keys %revs) {
4479 my ($paths, $logged) = @{$revs{$r}};
4481 foreach my $gs ($self->match_globs(\%exists, $paths,
4482 $globs, $r)) {
4483 if ($gs->rev_map_max >= $r) {
4484 next;
4486 next unless $gs->match_paths($paths, $r);
4487 $gs->{logged_rev_props} = $logged;
4488 if (my $last_commit = $gs->last_commit) {
4489 $gs->assert_index_clean($last_commit);
4491 my $log_entry = $gs->do_fetch($paths, $r);
4492 if ($log_entry) {
4493 $gs->do_git_commit($log_entry);
4495 $INDEX_FILES{$gs->{index}} = 1;
4497 foreach my $g (@$globs) {
4498 my $k = "svn-remote.$g->{remote}." .
4499 "$g->{t}-maxRev";
4500 Git::SVN::tmp_config($k, $r);
4502 if ($ra_invalid) {
4503 $_[0] = undef;
4504 $self = undef;
4505 $RA = undef;
4506 $self = Git::SVN::Ra->new($ra_url);
4507 $ra_invalid = undef;
4510 # pre-fill the .rev_db since it'll eventually get filled in
4511 # with '0' x40 if something new gets committed
4512 foreach my $gs (@$gsv) {
4513 next if $gs->rev_map_max >= $max;
4514 next if defined $gs->rev_map_get($max);
4515 $gs->rev_map_set($max, 0 x40);
4517 foreach my $g (@$globs) {
4518 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4519 Git::SVN::tmp_config($k, $max);
4521 last if $max >= $head;
4522 $min = $max + 1;
4523 $max += $inc;
4524 $max = $head if ($max > $head);
4526 Git::SVN::gc();
4529 sub get_dir_globbed {
4530 my ($self, $left, $depth, $r) = @_;
4532 my @x = eval { $self->get_dir($left, $r) };
4533 return unless scalar @x == 3;
4534 my $dirents = $x[0];
4535 my @finalents;
4536 foreach my $de (keys %$dirents) {
4537 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4538 if ($depth > 1) {
4539 my @args = ("$left/$de", $depth - 1, $r);
4540 foreach my $dir ($self->get_dir_globbed(@args)) {
4541 push @finalents, "$de/$dir";
4543 } else {
4544 push @finalents, $de;
4547 @finalents;
4550 sub match_globs {
4551 my ($self, $exists, $paths, $globs, $r) = @_;
4553 sub get_dir_check {
4554 my ($self, $exists, $g, $r) = @_;
4556 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4557 $g->{path}->{depth},
4558 $r);
4560 foreach my $de (@dirs) {
4561 my $p = $g->{path}->full_path($de);
4562 next if $exists->{$p};
4563 next if (length $g->{path}->{right} &&
4564 ($self->check_path($p, $r) !=
4565 $SVN::Node::dir));
4566 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4567 $g->{ref}->full_path($de), 1);
4570 foreach my $g (@$globs) {
4571 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4572 if ($path->{action} =~ /^[AR]$/) {
4573 get_dir_check($self, $exists, $g, $r);
4576 foreach (keys %$paths) {
4577 if (/$g->{path}->{left_regex}/ &&
4578 !/$g->{path}->{regex}/) {
4579 next if $paths->{$_}->{action} !~ /^[AR]$/;
4580 get_dir_check($self, $exists, $g, $r);
4582 next unless /$g->{path}->{regex}/;
4583 my $p = $1;
4584 my $pathname = $g->{path}->full_path($p);
4585 next if $exists->{$pathname};
4586 next if ($self->check_path($pathname, $r) !=
4587 $SVN::Node::dir);
4588 $exists->{$pathname} = Git::SVN->init(
4589 $self->{url}, $pathname, undef,
4590 $g->{ref}->full_path($p), 1);
4592 my $c = '';
4593 foreach (split m#/#, $g->{path}->{left}) {
4594 $c .= "/$_";
4595 next unless ($paths->{$c} &&
4596 ($paths->{$c}->{action} =~ /^[AR]$/));
4597 get_dir_check($self, $exists, $g, $r);
4600 values %$exists;
4603 sub minimize_url {
4604 my ($self) = @_;
4605 return $self->{url} if ($self->{url} eq $self->{repos_root});
4606 my $url = $self->{repos_root};
4607 my @components = split(m!/!, $self->{svn_path});
4608 my $c = '';
4609 do {
4610 $url .= "/$c" if length $c;
4611 eval { (ref $self)->new($url)->get_latest_revnum };
4612 } while ($@ && ($c = shift @components));
4613 $url;
4616 sub can_do_switch {
4617 my $self = shift;
4618 unless (defined $can_do_switch) {
4619 my $pool = SVN::Pool->new;
4620 my $rep = eval {
4621 $self->do_switch(1, '', 0, $self->{url},
4622 SVN::Delta::Editor->new, $pool);
4624 if ($@) {
4625 $can_do_switch = 0;
4626 } else {
4627 $rep->abort_report($pool);
4628 $can_do_switch = 1;
4630 $pool->clear;
4632 $can_do_switch;
4635 sub skip_unknown_revs {
4636 my ($err) = @_;
4637 my $errno = $err->apr_err();
4638 # Maybe the branch we're tracking didn't
4639 # exist when the repo started, so it's
4640 # not an error if it doesn't, just continue
4642 # Wonderfully consistent library, eh?
4643 # 160013 - svn:// and file://
4644 # 175002 - http(s)://
4645 # 175007 - http(s):// (this repo required authorization, too...)
4646 # More codes may be discovered later...
4647 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4648 my $err_key = $err->expanded_message;
4649 # revision numbers change every time, filter them out
4650 $err_key =~ s/\d+/\0/g;
4651 $err_key = "$errno\0$err_key";
4652 unless ($ignored_err{$err_key}) {
4653 warn "W: Ignoring error from SVN, path probably ",
4654 "does not exist: ($errno): ",
4655 $err->expanded_message,"\n";
4656 warn "W: Do not be alarmed at the above message ",
4657 "git-svn is just searching aggressively for ",
4658 "old history.\n",
4659 "This may take a while on large repositories\n";
4660 $ignored_err{$err_key} = 1;
4662 return;
4664 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4667 # svn_log_changed_path_t objects passed to get_log are likely to be
4668 # overwritten even if only the refs are copied to an external variable,
4669 # so we should dup the structures in their entirety. Using an externally
4670 # passed pool (instead of our temporary and quickly cleared pool in
4671 # Git::SVN::Ra) does not help matters at all...
4672 sub dup_changed_paths {
4673 my ($paths) = @_;
4674 return undef unless $paths;
4675 my %ret;
4676 foreach my $p (keys %$paths) {
4677 my $i = $paths->{$p};
4678 my %s = map { $_ => $i->$_ }
4679 qw/copyfrom_path copyfrom_rev action/;
4680 $ret{$p} = \%s;
4682 \%ret;
4685 package Git::SVN::Log;
4686 use strict;
4687 use warnings;
4688 use POSIX qw/strftime/;
4689 use Time::Local;
4690 use constant commit_log_separator => ('-' x 72) . "\n";
4691 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4692 %rusers $show_commit $incremental/;
4693 my $l_fmt;
4695 sub cmt_showable {
4696 my ($c) = @_;
4697 return 1 if defined $c->{r};
4699 # big commit message got truncated by the 16k pretty buffer in rev-list
4700 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4701 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4702 @{$c->{l}} = ();
4703 my @log = command(qw/cat-file commit/, $c->{c});
4705 # shift off the headers
4706 shift @log while ($log[0] ne '');
4707 shift @log;
4709 # TODO: make $c->{l} not have a trailing newline in the future
4710 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4712 (undef, $c->{r}, undef) = ::extract_metadata(
4713 (grep(/^git-svn-id: /, @log))[-1]);
4715 return defined $c->{r};
4718 sub log_use_color {
4719 return $color || Git->repository->get_colorbool('color.diff');
4722 sub git_svn_log_cmd {
4723 my ($r_min, $r_max, @args) = @_;
4724 my $head = 'HEAD';
4725 my (@files, @log_opts);
4726 foreach my $x (@args) {
4727 if ($x eq '--' || @files) {
4728 push @files, $x;
4729 } else {
4730 if (::verify_ref("$x^0")) {
4731 $head = $x;
4732 } else {
4733 push @log_opts, $x;
4738 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4739 $gs ||= Git::SVN->_new;
4740 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4741 $gs->refname);
4742 push @cmd, '-r' unless $non_recursive;
4743 push @cmd, qw/--raw --name-status/ if $verbose;
4744 push @cmd, '--color' if log_use_color();
4745 push @cmd, @log_opts;
4746 if (defined $r_max && $r_max == $r_min) {
4747 push @cmd, '--max-count=1';
4748 if (my $c = $gs->rev_map_get($r_max)) {
4749 push @cmd, $c;
4751 } elsif (defined $r_max) {
4752 if ($r_max < $r_min) {
4753 ($r_min, $r_max) = ($r_max, $r_min);
4755 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4756 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4757 # If there are no commits in the range, both $c_max and $c_min
4758 # will be undefined. If there is at least 1 commit in the
4759 # range, both will be defined.
4760 return () if !defined $c_min || !defined $c_max;
4761 if ($c_min eq $c_max) {
4762 push @cmd, '--max-count=1', $c_min;
4763 } else {
4764 push @cmd, '--boundary', "$c_min..$c_max";
4767 return (@cmd, @files);
4770 # adapted from pager.c
4771 sub config_pager {
4772 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4773 if (!defined $pager) {
4774 $pager = 'less';
4775 } elsif (length $pager == 0 || $pager eq 'cat') {
4776 $pager = undef;
4778 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4781 sub run_pager {
4782 return unless -t *STDOUT && defined $pager;
4783 pipe my ($rfd, $wfd) or return;
4784 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4785 if (!$pid) {
4786 open STDOUT, '>&', $wfd or
4787 ::fatal "Can't redirect to stdout: $!";
4788 return;
4790 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4791 $ENV{LESS} ||= 'FRSX';
4792 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4795 sub format_svn_date {
4796 # some systmes don't handle or mishandle %z, so be creative.
4797 my $t = shift || time;
4798 my $gm = timelocal(gmtime($t));
4799 my $sign = qw( + + - )[ $t <=> $gm ];
4800 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4801 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4804 sub parse_git_date {
4805 my ($t, $tz) = @_;
4806 # Date::Parse isn't in the standard Perl distro :(
4807 if ($tz =~ s/^\+//) {
4808 $t += tz_to_s_offset($tz);
4809 } elsif ($tz =~ s/^\-//) {
4810 $t -= tz_to_s_offset($tz);
4812 return $t;
4815 sub set_local_timezone {
4816 if (defined $TZ) {
4817 $ENV{TZ} = $TZ;
4818 } else {
4819 delete $ENV{TZ};
4823 sub tz_to_s_offset {
4824 my ($tz) = @_;
4825 $tz =~ s/(\d\d)$//;
4826 return ($1 * 60) + ($tz * 3600);
4829 sub get_author_info {
4830 my ($dest, $author, $t, $tz) = @_;
4831 $author =~ s/(?:^\s*|\s*$)//g;
4832 $dest->{a_raw} = $author;
4833 my $au;
4834 if ($::_authors) {
4835 $au = $rusers{$author} || undef;
4837 if (!$au) {
4838 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4840 $dest->{t} = $t;
4841 $dest->{tz} = $tz;
4842 $dest->{a} = $au;
4843 $dest->{t_utc} = parse_git_date($t, $tz);
4846 sub process_commit {
4847 my ($c, $r_min, $r_max, $defer) = @_;
4848 if (defined $r_min && defined $r_max) {
4849 if ($r_min == $c->{r} && $r_min == $r_max) {
4850 show_commit($c);
4851 return 0;
4853 return 1 if $r_min == $r_max;
4854 if ($r_min < $r_max) {
4855 # we need to reverse the print order
4856 return 0 if (defined $limit && --$limit < 0);
4857 push @$defer, $c;
4858 return 1;
4860 if ($r_min != $r_max) {
4861 return 1 if ($r_min < $c->{r});
4862 return 1 if ($r_max > $c->{r});
4865 return 0 if (defined $limit && --$limit < 0);
4866 show_commit($c);
4867 return 1;
4870 sub show_commit {
4871 my $c = shift;
4872 if ($oneline) {
4873 my $x = "\n";
4874 if (my $l = $c->{l}) {
4875 while ($l->[0] =~ /^\s*$/) { shift @$l }
4876 $x = $l->[0];
4878 $l_fmt ||= 'A' . length($c->{r});
4879 print 'r',pack($l_fmt, $c->{r}),' | ';
4880 print "$c->{c} | " if $show_commit;
4881 print $x;
4882 } else {
4883 show_commit_normal($c);
4887 sub show_commit_changed_paths {
4888 my ($c) = @_;
4889 return unless $c->{changed};
4890 print "Changed paths:\n", @{$c->{changed}};
4893 sub show_commit_normal {
4894 my ($c) = @_;
4895 print commit_log_separator, "r$c->{r} | ";
4896 print "$c->{c} | " if $show_commit;
4897 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4898 my $nr_line = 0;
4900 if (my $l = $c->{l}) {
4901 while ($l->[$#$l] eq "\n" && $#$l > 0
4902 && $l->[($#$l - 1)] eq "\n") {
4903 pop @$l;
4905 $nr_line = scalar @$l;
4906 if (!$nr_line) {
4907 print "1 line\n\n\n";
4908 } else {
4909 if ($nr_line == 1) {
4910 $nr_line = '1 line';
4911 } else {
4912 $nr_line .= ' lines';
4914 print $nr_line, "\n";
4915 show_commit_changed_paths($c);
4916 print "\n";
4917 print $_ foreach @$l;
4919 } else {
4920 print "1 line\n";
4921 show_commit_changed_paths($c);
4922 print "\n";
4925 foreach my $x (qw/raw stat diff/) {
4926 if ($c->{$x}) {
4927 print "\n";
4928 print $_ foreach @{$c->{$x}}
4933 sub cmd_show_log {
4934 my (@args) = @_;
4935 my ($r_min, $r_max);
4936 my $r_last = -1; # prevent dupes
4937 set_local_timezone();
4938 if (defined $::_revision) {
4939 if ($::_revision =~ /^(\d+):(\d+)$/) {
4940 ($r_min, $r_max) = ($1, $2);
4941 } elsif ($::_revision =~ /^\d+$/) {
4942 $r_min = $r_max = $::_revision;
4943 } else {
4944 ::fatal "-r$::_revision is not supported, use ",
4945 "standard 'git log' arguments instead";
4949 config_pager();
4950 @args = git_svn_log_cmd($r_min, $r_max, @args);
4951 if (!@args) {
4952 print commit_log_separator unless $incremental || $oneline;
4953 return;
4955 my $log = command_output_pipe(@args);
4956 run_pager();
4957 my (@k, $c, $d, $stat);
4958 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4959 while (<$log>) {
4960 if (/^${esc_color}commit -?($::sha1_short)/o) {
4961 my $cmt = $1;
4962 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4963 $r_last = $c->{r};
4964 process_commit($c, $r_min, $r_max, \@k) or
4965 goto out;
4967 $d = undef;
4968 $c = { c => $cmt };
4969 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4970 get_author_info($c, $1, $2, $3);
4971 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4972 # ignore
4973 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4974 push @{$c->{raw}}, $_;
4975 } elsif (/^${esc_color}[ACRMDT]\t/) {
4976 # we could add $SVN->{svn_path} here, but that requires
4977 # remote access at the moment (repo_path_split)...
4978 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4979 push @{$c->{changed}}, $_;
4980 } elsif (/^${esc_color}diff /o) {
4981 $d = 1;
4982 push @{$c->{diff}}, $_;
4983 } elsif ($d) {
4984 push @{$c->{diff}}, $_;
4985 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4986 $esc_color*[\+\-]*$esc_color$/x) {
4987 $stat = 1;
4988 push @{$c->{stat}}, $_;
4989 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4990 push @{$c->{stat}}, $_;
4991 $stat = undef;
4992 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4993 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4994 } elsif (s/^${esc_color} //o) {
4995 push @{$c->{l}}, $_;
4998 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4999 $r_last = $c->{r};
5000 process_commit($c, $r_min, $r_max, \@k);
5002 if (@k) {
5003 ($r_min, $r_max) = ($r_max, $r_min);
5004 process_commit($_, $r_min, $r_max) foreach reverse @k;
5006 out:
5007 close $log;
5008 print commit_log_separator unless $incremental || $oneline;
5011 sub cmd_blame {
5012 my $path = pop;
5014 config_pager();
5015 run_pager();
5017 my ($fh, $ctx, $rev);
5019 if ($_git_format) {
5020 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5021 while (my $line = <$fh>) {
5022 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5023 # Uncommitted edits show up as a rev ID of
5024 # all zeros, which we can't look up with
5025 # cmt_metadata
5026 if ($1 !~ /^0+$/) {
5027 (undef, $rev, undef) =
5028 ::cmt_metadata($1);
5029 $rev = '0' if (!$rev);
5030 } else {
5031 $rev = '0';
5033 $rev = sprintf('%-10s', $rev);
5034 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5036 print $line;
5038 } else {
5039 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5040 '--', $path);
5041 my ($sha1);
5042 my %authors;
5043 my @buffer;
5044 my %dsha; #distinct sha keys
5046 while (my $line = <$fh>) {
5047 push @buffer, $line;
5048 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5049 $dsha{$1} = 1;
5053 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5055 foreach my $line (@buffer) {
5056 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5057 $rev = $s2r->{$1};
5058 $rev = '0' if (!$rev)
5060 elsif ($line =~ /^author (.*)/) {
5061 $authors{$rev} = $1;
5062 $authors{$rev} =~ s/\s/_/g;
5064 elsif ($line =~ /^\t(.*)$/) {
5065 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5069 command_close_pipe($fh, $ctx);
5072 package Git::SVN::Migration;
5073 # these version numbers do NOT correspond to actual version numbers
5074 # of git nor git-svn. They are just relative.
5076 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5078 # v1 layout: .git/$id/info/url, refs/remotes/$id
5080 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5082 # v3 layout: .git/svn/$id, refs/remotes/$id
5083 # - info/url may remain for backwards compatibility
5084 # - this is what we migrate up to this layout automatically,
5085 # - this will be used by git svn init on single branches
5086 # v3.1 layout (auto migrated):
5087 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5088 # for backwards compatibility
5090 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5091 # - this is only created for newly multi-init-ed
5092 # repositories. Similar in spirit to the
5093 # --use-separate-remotes option in git-clone (now default)
5094 # - we do not automatically migrate to this (following
5095 # the example set by core git)
5097 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5098 # - newer, more-efficient format that uses 24-bytes per record
5099 # with no filler space.
5100 # - use xxd -c24 < .rev_map.$UUID to view and debug
5101 # - This is a one-way migration, repositories updated to the
5102 # new format will not be able to use old git-svn without
5103 # rebuilding the .rev_db. Rebuilding the rev_db is not
5104 # possible if noMetadata or useSvmProps are set; but should
5105 # be no problem for users that use the (sensible) defaults.
5106 use strict;
5107 use warnings;
5108 use Carp qw/croak/;
5109 use File::Path qw/mkpath/;
5110 use File::Basename qw/dirname basename/;
5111 use vars qw/$_minimize/;
5113 sub migrate_from_v0 {
5114 my $git_dir = $ENV{GIT_DIR};
5115 return undef unless -d $git_dir;
5116 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5117 my $migrated = 0;
5118 while (<$fh>) {
5119 chomp;
5120 my ($id, $orig_ref) = ($_, $_);
5121 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5122 next unless -f "$git_dir/$id/info/url";
5123 my $new_ref = "refs/remotes/$id";
5124 if (::verify_ref("$new_ref^0")) {
5125 print STDERR "W: $orig_ref is probably an old ",
5126 "branch used by an ancient version of ",
5127 "git-svn.\n",
5128 "However, $new_ref also exists.\n",
5129 "We will not be able ",
5130 "to use this branch until this ",
5131 "ambiguity is resolved.\n";
5132 next;
5134 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5135 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5136 command_noisy('update-ref', $new_ref, $orig_ref);
5137 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5138 $migrated++;
5140 command_close_pipe($fh, $ctx);
5141 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5142 $migrated;
5145 sub migrate_from_v1 {
5146 my $git_dir = $ENV{GIT_DIR};
5147 my $migrated = 0;
5148 return $migrated unless -d $git_dir;
5149 my $svn_dir = "$git_dir/svn";
5151 # just in case somebody used 'svn' as their $id at some point...
5152 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5154 print STDERR "Migrating from a git-svn v1 layout...\n";
5155 mkpath([$svn_dir]);
5156 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5157 "$svn_dir\n\t(required for this version ",
5158 "($::VERSION) of git-svn) does not exist.\n";
5159 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5160 while (<$fh>) {
5161 my $x = $_;
5162 next unless $x =~ s#^refs/remotes/##;
5163 chomp $x;
5164 next unless -f "$git_dir/$x/info/url";
5165 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5166 next unless $u;
5167 my $dn = dirname("$git_dir/svn/$x");
5168 mkpath([$dn]) unless -d $dn;
5169 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5170 mkpath(["$git_dir/svn/svn"]);
5171 print STDERR " - $git_dir/$x/info => ",
5172 "$git_dir/svn/$x/info\n";
5173 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5174 croak "$!: $x";
5175 # don't worry too much about these, they probably
5176 # don't exist with repos this old (save for index,
5177 # and we can easily regenerate that)
5178 foreach my $f (qw/unhandled.log index .rev_db/) {
5179 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5181 } else {
5182 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5183 rename "$git_dir/$x", "$git_dir/svn/$x" or
5184 croak "$!: $x";
5186 $migrated++;
5188 command_close_pipe($fh, $ctx);
5189 print STDERR "Done migrating from a git-svn v1 layout\n";
5190 $migrated;
5193 sub read_old_urls {
5194 my ($l_map, $pfx, $path) = @_;
5195 my @dir;
5196 foreach (<$path/*>) {
5197 if (-r "$_/info/url") {
5198 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5199 my $ref_id = $pfx . basename $_;
5200 my $url = ::file_to_s("$_/info/url");
5201 $l_map->{$ref_id} = $url;
5202 } elsif (-d $_) {
5203 push @dir, $_;
5206 foreach (@dir) {
5207 my $x = $_;
5208 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5209 read_old_urls($l_map, $x, $_);
5213 sub migrate_from_v2 {
5214 my @cfg = command(qw/config -l/);
5215 return if grep /^svn-remote\..+\.url=/, @cfg;
5216 my %l_map;
5217 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5218 my $migrated = 0;
5220 foreach my $ref_id (sort keys %l_map) {
5221 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5222 if ($@) {
5223 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5225 $migrated++;
5227 $migrated;
5230 sub minimize_connections {
5231 my $r = Git::SVN::read_all_remotes();
5232 my $new_urls = {};
5233 my $root_repos = {};
5234 foreach my $repo_id (keys %$r) {
5235 my $url = $r->{$repo_id}->{url} or next;
5236 my $fetch = $r->{$repo_id}->{fetch} or next;
5237 my $ra = Git::SVN::Ra->new($url);
5239 # skip existing cases where we already connect to the root
5240 if (($ra->{url} eq $ra->{repos_root}) ||
5241 ($ra->{repos_root} eq $repo_id)) {
5242 $root_repos->{$ra->{url}} = $repo_id;
5243 next;
5246 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5247 my $root_path = $ra->{url};
5248 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5249 foreach my $path (keys %$fetch) {
5250 my $ref_id = $fetch->{$path};
5251 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5253 # make sure we can read when connecting to
5254 # a higher level of a repository
5255 my ($last_rev, undef) = $gs->last_rev_commit;
5256 if (!defined $last_rev) {
5257 $last_rev = eval {
5258 $root_ra->get_latest_revnum;
5260 next if $@;
5262 my $new = $root_path;
5263 $new .= length $path ? "/$path" : '';
5264 eval {
5265 $root_ra->get_log([$new], $last_rev, $last_rev,
5266 0, 0, 1, sub { });
5268 next if $@;
5269 $new_urls->{$ra->{repos_root}}->{$new} =
5270 { ref_id => $ref_id,
5271 old_repo_id => $repo_id,
5272 old_path => $path };
5276 my @emptied;
5277 foreach my $url (keys %$new_urls) {
5278 # see if we can re-use an existing [svn-remote "repo_id"]
5279 # instead of creating a(n ugly) new section:
5280 my $repo_id = $root_repos->{$url} || $url;
5282 my $fetch = $new_urls->{$url};
5283 foreach my $path (keys %$fetch) {
5284 my $x = $fetch->{$path};
5285 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5286 my $pfx = "svn-remote.$x->{old_repo_id}";
5288 my $old_fetch = quotemeta("$x->{old_path}:".
5289 "refs/remotes/$x->{ref_id}");
5290 command_noisy(qw/config --unset/,
5291 "$pfx.fetch", '^'. $old_fetch . '$');
5292 delete $r->{$x->{old_repo_id}}->
5293 {fetch}->{$x->{old_path}};
5294 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5295 command_noisy(qw/config --unset/,
5296 "$pfx.url");
5297 push @emptied, $x->{old_repo_id}
5301 if (@emptied) {
5302 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5303 print STDERR <<EOF;
5304 The following [svn-remote] sections in your config file ($file) are empty
5305 and can be safely removed:
5307 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5311 sub migration_check {
5312 migrate_from_v0();
5313 migrate_from_v1();
5314 migrate_from_v2();
5315 minimize_connections() if $_minimize;
5318 package Git::IndexInfo;
5319 use strict;
5320 use warnings;
5321 use Git qw/command_input_pipe command_close_pipe/;
5323 sub new {
5324 my ($class) = @_;
5325 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5326 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5329 sub remove {
5330 my ($self, $path) = @_;
5331 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5332 return ++$self->{nr};
5334 undef;
5337 sub update {
5338 my ($self, $mode, $hash, $path) = @_;
5339 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5340 return ++$self->{nr};
5342 undef;
5345 sub DESTROY {
5346 my ($self) = @_;
5347 command_close_pipe($self->{gui}, $self->{ctx});
5350 package Git::SVN::GlobSpec;
5351 use strict;
5352 use warnings;
5354 sub new {
5355 my ($class, $glob) = @_;
5356 my $re = $glob;
5357 $re =~ s!/+$!!g; # no need for trailing slashes
5358 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5359 my $temp = $re;
5360 my ($left, $right) = ($1, $3);
5361 $re = $2;
5362 my $depth = $re =~ tr/*/*/;
5363 if ($depth != $temp =~ tr/*/*/) {
5364 die "Only one set of wildcard directories " .
5365 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5367 if ($depth == 0) {
5368 die "One '*' is needed for glob: '$glob'\n";
5370 $re =~ s!\*!\[^/\]*!g;
5371 $re = quotemeta($left) . "($re)" . quotemeta($right);
5372 if (length $left && !($left =~ s!/+$!!g)) {
5373 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5375 if (length $right && !($right =~ s!^/+!!g)) {
5376 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5378 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5379 bless { left => $left, right => $right, left_regex => $left_re,
5380 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5383 sub full_path {
5384 my ($self, $path) = @_;
5385 return (length $self->{left} ? "$self->{left}/" : '') .
5386 $path . (length $self->{right} ? "/$self->{right}" : '');
5389 __END__
5391 Data structures:
5394 $remotes = { # returned by read_all_remotes()
5395 'svn' => {
5396 # svn-remote.svn.url=https://svn.musicpd.org
5397 url => 'https://svn.musicpd.org',
5398 # svn-remote.svn.fetch=mpd/trunk:trunk
5399 fetch => {
5400 'mpd/trunk' => 'trunk',
5402 # svn-remote.svn.tags=mpd/tags/*:tags/*
5403 tags => {
5404 path => {
5405 left => 'mpd/tags',
5406 right => '',
5407 regex => qr!mpd/tags/([^/]+)$!,
5408 glob => 'tags/*',
5410 ref => {
5411 left => 'tags',
5412 right => '',
5413 regex => qr!tags/([^/]+)$!,
5414 glob => 'tags/*',
5420 $log_entry hashref as returned by libsvn_log_entry()
5422 log => 'whitespace-formatted log entry
5423 ', # trailing newline is preserved
5424 revision => '8', # integer
5425 date => '2004-02-24T17:01:44.108345Z', # commit date
5426 author => 'committer name'
5430 # this is generated by generate_diff();
5431 @mods = array of diff-index line hashes, each element represents one line
5432 of diff-index output
5434 diff-index line ($m hash)
5436 mode_a => first column of diff-index output, no leading ':',
5437 mode_b => second column of diff-index output,
5438 sha1_b => sha1sum of the final blob,
5439 chg => change type [MCRADT],
5440 file_a => original file name of a file (iff chg is 'C' or 'R')
5441 file_b => new/current file name of a file (any chg)
5445 # retval of read_url_paths{,_all}();
5446 $l_map = {
5447 # repository root url
5448 'https://svn.musicpd.org' => {
5449 # repository path # GIT_SVN_ID
5450 'mpd/trunk' => 'trunk',
5451 'mpd/tags/0.11.5' => 'tags/0.11.5',
5455 Notes:
5456 I don't trust the each() function on unless I created %hash myself
5457 because the internal iterator may not have started at base.