2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %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)
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;
22 $Git::SVN::_minimize_url = 'unset';
24 $Git::SVN::Log::TZ = $ENV{TZ};
26 $| = 1; # unbuffer STDOUT
28 sub fatal (@) { print STDERR "@_\n"; exit 1 }
29 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
32 if ($SVN::Core::VERSION lt '1.1.0') {
33 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
35 my $can_compress = eval { require Compress::Zlib; 1};
36 push @Git::SVN::Ra::ISA, 'SVN::Ra';
37 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
38 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
42 use File::Basename qw/dirname basename/;
43 use File::Path qw/mkpath/;
46 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
51 # import functions from Git into our packages, en masse
53 foreach (qw/command command_oneline command_noisy command_output_pipe
54 command_input_pipe command_close_pipe
55 command_bidi_pipe command_close_bidi_pipe/) {
56 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
57 Git::SVN::Migration Git::SVN::Log Git::SVN),
59 *{"${package}::$_"} = \&{"Git::$_"};
66 $sha1 = qr/[a-f\d]{40}/;
67 $sha1_short = qr/[a-f\d]{4,40}/;
68 my ($_stdin, $_help, $_edit,
69 $_message, $_file, $_branch_dest,
71 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
72 $_merge, $_strategy, $_dry_run, $_local,
73 $_prefix, $_no_checkout, $_url, $_verbose,
74 $_git_format, $_commit_url, $_tag);
75 $Git::SVN::_follow_parent = 1;
77 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
78 'config-dir=s' => \$Git::SVN::Ra::config_dir,
79 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
80 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
81 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
82 'authors-file|A=s' => \$_authors,
83 'authors-prog=s' => \$_authors_prog,
84 'repack:i' => \$Git::SVN::_repack,
85 'noMetadata' => \$Git::SVN::_no_metadata,
86 'useSvmProps' => \$Git::SVN::_use_svm_props,
87 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
88 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
89 'no-checkout' => \$_no_checkout,
91 'repack-flags|repack-args|repack-opts=s' =>
92 \$Git::SVN::_repack_flags,
93 'use-log-author' => \$Git::SVN::_use_log_author,
94 'add-author-from' => \$Git::SVN::_add_author_from,
95 'localtime' => \$Git::SVN::_localtime,
98 my ($_trunk, @_tags, @_branches, $_stdlayout);
100 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
101 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
102 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
103 'stdlayout|s' => \$_stdlayout,
104 'minimize-url|m!' => \$Git::SVN::_minimize_url,
105 'no-metadata' => sub { $icv{noMetadata} = 1 },
106 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
107 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
108 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
110 my %cmt_opts = ( 'edit|e' => \$_edit,
111 'rmdir' => \$SVN::Git::Editor::_rmdir,
112 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
113 'l=i' => \$SVN::Git::Editor::_rename_limit,
114 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
118 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
119 { 'revision|r=s' => \$_revision,
120 'fetch-all|all' => \$_fetch_all,
121 'parent|p' => \$_fetch_parent,
123 clone => [ \&cmd_clone, "Initialize and fetch revisions",
124 { 'revision|r=s' => \$_revision,
125 %fc_opts, %init_opts } ],
126 init => [ \&cmd_init, "Initialize a repo for tracking" .
127 " (requires URL argument)",
129 'multi-init' => [ \&cmd_multi_init,
130 "Deprecated alias for ".
131 "'$0 init -T<trunk> -b<branches> -t<tags>'",
133 dcommit => [ \&cmd_dcommit,
134 'Commit several diffs to merge with upstream',
135 { 'merge|m|M' => \$_merge,
136 'strategy|s=s' => \$_strategy,
137 'verbose|v' => \$_verbose,
138 'dry-run|n' => \$_dry_run,
139 'fetch-all|all' => \$_fetch_all,
140 'commit-url=s' => \$_commit_url,
141 'revision|r=i' => \$_revision,
142 'no-rebase' => \$_no_rebase,
143 %cmt_opts, %fc_opts } ],
144 branch => [ \&cmd_branch,
145 'Create a branch in the SVN repository',
146 { 'message|m=s' => \$_message,
147 'destination|d=s' => \$_branch_dest,
148 'dry-run|n' => \$_dry_run,
149 'tag|t' => \$_tag } ],
150 tag => [ sub { $_tag = 1; cmd_branch(@_) },
151 'Create a tag in the SVN repository',
152 { 'message|m=s' => \$_message,
153 'destination|d=s' => \$_branch_dest,
154 'dry-run|n' => \$_dry_run } ],
155 'set-tree' => [ \&cmd_set_tree,
156 "Set an SVN repository to a git tree-ish",
157 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
158 'create-ignore' => [ \&cmd_create_ignore,
159 'Create a .gitignore per svn:ignore',
160 { 'revision|r=i' => \$_revision
162 'propget' => [ \&cmd_propget,
163 'Print the value of a property on a file or directory',
164 { 'revision|r=i' => \$_revision } ],
165 'proplist' => [ \&cmd_proplist,
166 'List all properties of a file or directory',
167 { 'revision|r=i' => \$_revision } ],
168 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
169 { 'revision|r=i' => \$_revision
171 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
172 { 'revision|r=i' => \$_revision
174 'multi-fetch' => [ \&cmd_multi_fetch,
175 "Deprecated alias for $0 fetch --all",
176 { 'revision|r=s' => \$_revision, %fc_opts } ],
177 'migrate' => [ sub { },
178 # no-op, we automatically run this anyways,
179 'Migrate configuration/metadata/layout from
180 previous versions of git-svn',
181 { 'minimize' => \$Git::SVN::Migration::_minimize,
183 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
184 { 'limit=i' => \$Git::SVN::Log::limit,
185 'revision|r=s' => \$_revision,
186 'verbose|v' => \$Git::SVN::Log::verbose,
187 'incremental' => \$Git::SVN::Log::incremental,
188 'oneline' => \$Git::SVN::Log::oneline,
189 'show-commit' => \$Git::SVN::Log::show_commit,
190 'non-recursive' => \$Git::SVN::Log::non_recursive,
191 'authors-file|A=s' => \$_authors,
192 'color' => \$Git::SVN::Log::color,
193 'pager=s' => \$Git::SVN::Log::pager
195 'find-rev' => [ \&cmd_find_rev,
196 "Translate between SVN revision numbers and tree-ish",
198 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
199 { 'merge|m|M' => \$_merge,
200 'verbose|v' => \$_verbose,
201 'strategy|s=s' => \$_strategy,
202 'local|l' => \$_local,
203 'fetch-all|all' => \$_fetch_all,
204 'dry-run|n' => \$_dry_run,
206 'commit-diff' => [ \&cmd_commit_diff,
207 'Commit a diff between two trees',
208 { 'message|m=s' => \$_message,
209 'file|F=s' => \$_file,
210 'revision|r=s' => \$_revision,
212 'info' => [ \&cmd_info,
213 "Show info about the latest SVN revision
214 on the current branch",
215 { 'url' => \$_url, } ],
216 'blame' => [ \&Git::SVN::Log::cmd_blame,
217 "Show what revision and author last modified each line of a file",
218 { 'git-format' => \$_git_format } ],
219 'reset' => [ \&cmd_reset,
220 "Undo fetches back to the specified SVN revision",
221 { 'revision|r=s' => \$_revision,
222 'parent|p' => \$_fetch_parent } ],
224 "Compress unhandled.log files in .git/svn and remove " .
225 "index files in .git/svn",
230 for (my $i = 0; $i < @ARGV; $i++) {
231 if (defined $cmd{$ARGV[$i]}) {
235 } elsif ($ARGV[$i] eq 'help') {
241 # make sure we're always running at the top-level working directory
242 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
243 unless (-d $ENV{GIT_DIR}) {
244 if ($git_dir_user_set) {
245 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
246 "but it is not a directory\n";
248 my $git_dir = delete $ENV{GIT_DIR};
251 $cdup = command_oneline(qw/rev-parse --show-cdup/);
252 $git_dir = '.' unless ($cdup);
253 chomp $cdup if ($cdup);
254 $cdup = "." unless ($cdup && length $cdup);
255 } "Already at toplevel, but $git_dir not found\n";
256 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
257 unless (-d $git_dir) {
258 die "$git_dir still not found after going to ",
261 $ENV{GIT_DIR} = $git_dir;
263 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
266 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
268 read_repo_config(\%opts);
269 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
270 Getopt::Long::Configure('pass_through');
272 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
273 'minimize-connections' => \$Git::SVN::Migration::_minimize,
274 'id|i=s' => \$Git::SVN::default_ref_id,
275 'svn-remote|remote|R=s' => sub {
276 $Git::SVN::no_reuse_existing = 1;
277 $Git::SVN::default_repo_id = $_[1] });
278 exit 1 if (!$rv && $cmd && $cmd ne 'log');
281 version() if $_version;
282 usage(1) unless defined $cmd;
283 load_authors() if $_authors;
284 if (defined $_authors_prog) {
285 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
288 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
289 Git::SVN::Migration::migration_check();
291 Git::SVN::init_vars();
293 Git::SVN::verify_remotes_sanity();
294 $cmd{$cmd}->[0]->(@ARGV);
297 post_fetch_checkout();
300 ####################### primary functions ######################
302 my $exit = shift || 0;
303 my $fd = $exit ? \*STDERR : \*STDOUT;
305 git-svn - bidirectional operations between a single Subversion tree and git
306 Usage: git svn <command> [options] [arguments]\n
308 print $fd "Available commands:\n" unless $cmd;
310 foreach (sort keys %cmd) {
311 next if $cmd && $cmd ne $_;
312 next if /^multi-/; # don't show deprecated commands
313 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
314 foreach (sort keys %{$cmd{$_}->[2]}) {
315 # mixed-case options are for .git/config only
316 next if /[A-Z]/ && /^[a-z]+$/i;
317 # prints out arguments as they should be passed:
318 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
319 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
321 split /\|/,$_)," $x\n";
325 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
326 arbitrary identifier if you're tracking multiple SVN branches/repositories in
327 one git repository and want to keep them separate. See git-svn(1) for more
334 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
339 unless (-d $ENV{GIT_DIR}) {
340 my @init_db = ('init');
341 push @init_db, "--template=$_template" if defined $_template;
342 if (defined $_shared) {
343 if ($_shared =~ /[a-z]/) {
344 push @init_db, "--shared=$_shared";
346 push @init_db, "--shared";
349 command_noisy(@init_db);
350 $_repository = Git->repository(Repository => ".git");
352 command_noisy('config', 'core.autocrlf', 'false');
354 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
355 foreach my $i (keys %icv) {
356 die "'$set' and '$i' cannot both be set\n" if $set;
357 next unless defined $icv{$i};
358 command_noisy('config', "$pfx.$i", $icv{$i});
361 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
362 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
363 if defined $$ignore_regex;
367 my $repo_path = shift or return;
368 mkpath([$repo_path]) unless -d $repo_path;
369 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
370 $ENV{GIT_DIR} = '.git';
371 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
375 my ($url, $path) = @_;
376 if (!defined $path &&
377 (defined $_trunk || @_branches || @_tags ||
378 defined $_stdlayout) &&
379 $url !~ m#^[a-z\+]+://#) {
382 $path = basename($url) if !defined $path || !length $path;
383 cmd_init($url, $path);
384 Git::SVN::fetch_all($Git::SVN::default_repo_id);
385 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
389 if (defined $_stdlayout) {
390 $_trunk = 'trunk' if (!defined $_trunk);
391 @_tags = 'tags' if (! @_tags);
392 @_branches = 'branches' if (! @_branches);
394 if (defined $_trunk || @_branches || @_tags) {
395 return cmd_multi_init(@_);
397 my $url = shift or die "SVN repository location required ",
398 "as a command-line argument\n";
399 $url = canonicalize_url($url);
403 if ($Git::SVN::_minimize_url eq 'unset') {
404 $Git::SVN::_minimize_url = 0;
407 Git::SVN->init($url);
411 if (grep /^\d+=./, @_) {
412 die "'<rev>=<commit>' fetch arguments are ",
413 "no longer supported.\n";
417 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
419 if ($_fetch_parent) {
420 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
422 die "Unable to determine upstream SVN information from ",
423 "working tree history\n";
425 # just fetch, don't checkout.
426 $_no_checkout = 'true';
427 $_fetch_all ? $gs->fetch_all : $gs->fetch;
428 } elsif ($_fetch_all) {
431 $remote ||= $Git::SVN::default_repo_id;
432 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
438 if ($_stdin || !@commits) {
439 print "Reading from stdin...\n";
442 if (/\b($sha1_short)\b/o) {
443 unshift @commits, $1;
448 foreach my $c (@commits) {
449 my @tmp = command('rev-parse',$c);
450 if (scalar @tmp == 1) {
452 } elsif (scalar @tmp > 1) {
453 push @revs, reverse(command('rev-list',@tmp));
455 fatal "Failed to rev-parse $c";
458 my $gs = Git::SVN->new;
459 my ($r_last, $cmt_last) = $gs->last_rev_commit;
461 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
462 fatal "There are new revisions that were fetched ",
463 "and need to be merged (or acknowledged) ",
464 "before committing.\nlast rev: $r_last\n",
465 " current: $gs->{last_rev}";
467 $gs->set_tree($_) foreach @revs;
468 print "Done committing ",scalar @revs," revisions to SVN\n";
474 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
475 'Cannot dcommit with a dirty index. Commit your changes first, '
476 . "or stash them with `git stash'.\n";
480 if ($head ne 'HEAD') {
482 command_oneline([qw/symbolic-ref -q HEAD/])
485 $old_head =~ s{^refs/heads/}{};
487 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
489 command(['checkout', $head], STDERR => 0);
493 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
495 die "Unable to determine upstream SVN information from ",
496 "$head history.\nPerhaps the repository is empty.";
499 if (defined $_commit_url) {
502 $url = eval { command_oneline('config', '--get',
503 "svn-remote.$gs->{repo_id}.commiturl") };
509 my $last_rev = $_revision if defined $_revision;
511 print "Committing to $url ...\n";
513 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
514 if ($_no_rebase && scalar(@$linear_refs) > 1) {
515 warn "Attempting to commit more than one change while ",
516 "--no-rebase is enabled.\n",
517 "If these changes depend on each other, re-running ",
518 "without --no-rebase may be required."
520 my $expect_url = $url;
521 Git::SVN::remove_username($expect_url);
523 my $d = shift @$linear_refs or last;
524 unless (defined $last_rev) {
525 (undef, $last_rev, undef) = cmt_metadata("$d~1");
526 unless (defined $last_rev) {
527 fatal "Unable to extract revision information ",
532 print "diff-tree $d~1 $d\n";
535 my %ed_opts = ( r => $last_rev,
536 log => get_commit_entry($d)->{log},
537 ra => Git::SVN::Ra->new($url),
538 config => SVN::Core::config_get_config(
539 $Git::SVN::Ra::config_dir
544 print "Committed r$_[0]\n";
548 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
549 print "No changes\n$d~1 == $d\n";
550 } elsif ($parents->{$d} && @{$parents->{$d}}) {
551 $gs->{inject_parents_dcommit}->{$cmt_rev} =
554 $_fetch_all ? $gs->fetch_all : $gs->fetch;
555 $last_rev = $cmt_rev;
558 # we always want to rebase against the current HEAD,
559 # not any head that was passed to us
560 my @diff = command('diff-tree', $d,
564 @finish = rebase_cmd();
565 print STDERR "W: $d and ", $gs->refname,
566 " differ, using @finish:\n",
567 join("\n", @diff), "\n";
569 print "No changes between current HEAD and ",
571 "\nResetting to the latest ",
573 @finish = qw/reset --mixed/;
575 command_noisy(@finish, $gs->refname);
578 my ($url_, $rev_, $uuid_, $gs_) =
579 working_head_info('HEAD', \@refs);
580 my ($linear_refs_, $parents_) =
581 linearize_history($gs_, \@refs);
582 if (scalar(@$linear_refs) !=
583 scalar(@$linear_refs_)) {
584 fatal "# of revisions changed ",
586 join("\n", @$linear_refs),
588 join("\n", @$linear_refs_), "\n",
589 'If you are attempting to commit ',
590 "merges, try running:\n\t",
591 'git rebase --interactive',
592 '--preserve-merges ',
594 "\nBefore dcommitting";
596 if ($url_ ne $expect_url) {
597 fatal "URL mismatch after rebase: ",
598 "$url_ != $expect_url";
600 if ($uuid_ ne $uuid) {
601 fatal "uuid mismatch after rebase: ",
606 for ($i = 0; $i < scalar @$linear_refs; $i++) {
607 my $new = $linear_refs_->[$i] or next;
609 $parents->{$linear_refs->[$i]};
619 my $new_head = command_oneline(qw/rev-parse HEAD/);
620 my $new_is_symbolic = eval {
621 command_oneline(qw/symbolic-ref -q HEAD/);
623 if ($new_is_symbolic) {
624 print "dcommitted the branch ", $head, "\n";
626 print "dcommitted on a detached HEAD because you gave ",
627 "a revision argument.\n",
628 "The rewritten commit is: ", $new_head, "\n";
630 command(['checkout', $old_head], STDERR => 0);
637 my ($branch_name, $head) = @_;
639 unless (defined $branch_name && length $branch_name) {
640 die(($_tag ? "tag" : "branch") . " name required\n");
644 my ($src, $rev, undef, $gs) = working_head_info($head);
646 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
647 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
649 if ($#{$allglobs} == 0) {
650 $glob = $allglobs->[0];
652 unless(defined $_branch_dest) {
654 $_tag ? "tag" : "branch",
655 " paths defined for Subversion repository.\n",
656 "You must specify where you want to create the ",
657 $_tag ? "tag" : "branch",
658 " with the --destination argument.\n";
660 foreach my $g (@{$allglobs}) {
661 # SVN::Git::Editor could probably be moved to Git.pm..
662 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
663 if ($_branch_dest =~ /$re/) {
668 unless (defined $glob) {
669 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
670 foreach my $g (@{$allglobs}) {
671 $g->{path}->{left} =~ /$dest_re/ or next;
673 die "Ambiguous destination: ",
674 $_branch_dest, "\nmatches both '",
675 $glob->{path}->{left}, "' and '",
676 $g->{path}->{left}, "'\n";
680 unless (defined $glob) {
682 $_tag ? "tag" : "branch",
683 " destination $_branch_dest\n";
687 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
688 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
690 my $ctx = SVN::Client->new(
691 auth => Git::SVN::Ra::_auth_providers(),
693 ${ $_[0] } = defined $_message
695 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
701 $ctx->ls($dst, 'HEAD', 0);
702 } and die "branch ${branch_name} already exists\n";
704 print "Copying ${src} at r${rev} to ${dst}...\n";
705 $ctx->copy($src, $rev, $dst)
712 my $revision_or_hash = shift or die "SVN or git revision required ",
713 "as a command-line argument\n";
715 if ($revision_or_hash =~ /^r\d+$/) {
719 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
721 die "Unable to determine upstream SVN information from ",
724 my $desired_revision = substr($revision_or_hash, 1);
725 $result = $gs->rev_map_get($desired_revision, $uuid);
727 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
730 print "$result\n" if $result;
734 command_noisy(qw/update-index --refresh/);
735 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
737 die "Unable to determine upstream SVN information from ",
738 "working tree history\n";
741 print "Remote Branch: " . $gs->refname . "\n";
742 print "SVN URL: " . $url . "\n";
745 if (command(qw/diff-index HEAD --/)) {
746 print STDERR "Cannot rebase with uncommited changes:\n";
747 command_noisy('status');
751 # rebase will checkout for us, so no need to do it explicitly
752 $_no_checkout = 'true';
753 $_fetch_all ? $gs->fetch_all : $gs->fetch;
755 command_noisy(rebase_cmd(), $gs->refname);
758 sub cmd_show_ignore {
759 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
760 $gs ||= Git::SVN->new;
761 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
762 $gs->prop_walk($gs->{path}, $r, sub {
763 my ($gs, $path, $props) = @_;
764 print STDOUT "\n# $path\n";
765 my $s = $props->{'svn:ignore'} or return;
766 $s =~ s/[\r\n]+/\n/g;
774 sub cmd_show_externals {
775 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
776 $gs ||= Git::SVN->new;
777 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
778 $gs->prop_walk($gs->{path}, $r, sub {
779 my ($gs, $path, $props) = @_;
780 print STDOUT "\n# $path\n";
781 my $s = $props->{'svn:externals'} or return;
782 $s =~ s/[\r\n]+/\n/g;
789 sub cmd_create_ignore {
790 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
791 $gs ||= Git::SVN->new;
792 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
793 $gs->prop_walk($gs->{path}, $r, sub {
794 my ($gs, $path, $props) = @_;
795 # $path is of the form /path/to/dir/
797 # SVN can have attributes on empty directories,
798 # which git won't track
799 mkpath([$path]) unless -d $path;
800 my $ignore = $path . '.gitignore';
801 my $s = $props->{'svn:ignore'} or return;
802 open(GITIGNORE, '>', $ignore)
803 or fatal("Failed to open `$ignore' for writing: $!");
804 $s =~ s/[\r\n]+/\n/g;
807 # Prefix all patterns so that the ignore doesn't apply
808 # to sub-directories.
810 print GITIGNORE "$s\n";
812 or fatal("Failed to close `$ignore': $!");
813 command_noisy('add', '-f', $ignore);
817 sub canonicalize_path {
819 my $dot_slash_added = 0;
820 if (substr($path, 0, 1) ne "/") {
821 $path = "./" . $path;
822 $dot_slash_added = 1;
824 # File::Spec->canonpath doesn't collapse x/../y into y (for a
825 # good reason), so let's do this manually.
827 $path =~ s#/\.(?:/|$)#/#g;
828 $path =~ s#/[^/]+/\.\.##g;
830 $path =~ s#^\./## if $dot_slash_added;
836 sub canonicalize_url {
838 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
844 # Helper for cmd_propget and cmd_proplist below.
847 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
848 $gs ||= Git::SVN->new;
850 # prefix THE PATH by the sub-directory from which the user
852 $path = $cmd_dir_prefix . $path;
853 fatal("No such file or directory: $path") unless -e $path;
854 my $is_dir = -d $path ? 1 : 0;
855 $path = $gs->{path} . '/' . $path;
857 # canonicalize the path (otherwise libsvn will abort or fail to
859 $path = canonicalize_path($path);
861 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
864 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
867 (undef, $props) = $gs->ra->get_file($path, $r, undef);
872 # cmd_propget (PROP, PATH)
873 # ------------------------
874 # Print the SVN property PROP for PATH.
876 my ($prop, $path) = @_;
877 $path = '.' if not defined $path;
878 usage(1) if not defined $prop;
879 my $props = get_svnprops($path);
880 if (not defined $props->{$prop}) {
881 fatal("`$path' does not have a `$prop' SVN property.");
883 print $props->{$prop} . "\n";
886 # cmd_proplist (PATH)
887 # -------------------
888 # Print the list of SVN properties for PATH.
891 $path = '.' if not defined $path;
892 my $props = get_svnprops($path);
893 print "Properties on '$path':\n";
894 foreach (sort keys %{$props}) {
901 unless (defined $_trunk || @_branches || @_tags) {
905 $_prefix = '' unless defined $_prefix;
907 $url = canonicalize_url($url);
911 if (defined $_trunk) {
912 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
913 # try both old-style and new-style lookups:
914 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
916 my ($trunk_url, $trunk_path) =
917 complete_svn_url($url, $_trunk);
918 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
922 return unless @_branches || @_tags;
923 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
924 foreach my $path (@_branches) {
925 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
927 foreach my $path (@_tags) {
928 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
932 sub cmd_multi_fetch {
933 my $remotes = Git::SVN::read_all_remotes();
934 foreach my $repo_id (sort keys %$remotes) {
935 if ($remotes->{$repo_id}->{url}) {
936 Git::SVN::fetch_all($repo_id, $remotes);
941 # this command is special because it requires no metadata
942 sub cmd_commit_diff {
943 my ($ta, $tb, $url) = @_;
944 my $usage = "Usage: $0 commit-diff -r<revision> ".
945 "<tree-ish> <tree-ish> [<URL>]";
946 fatal($usage) if (!defined $ta || !defined $tb);
949 my $gs = eval { Git::SVN->new };
951 fatal("Needed URL or usable git-svn --id in ",
952 "the command-line\n", $usage);
955 $svn_path = $gs->{path};
957 unless (defined $_revision) {
958 fatal("-r|--revision is a required argument\n", $usage);
960 if (defined $_message && defined $_file) {
961 fatal("Both --message/-m and --file/-F specified ",
962 "for the commit message.\n",
963 "I have no idea what you mean");
965 if (defined $_file) {
966 $_message = file_to_s($_file);
968 $_message ||= get_commit_entry($tb)->{log};
970 my $ra ||= Git::SVN::Ra->new($url);
973 $r = $ra->get_latest_revnum;
974 } elsif ($r !~ /^\d+$/) {
975 die "revision argument: $r not understood by git-svn\n";
977 my %ed_opts = ( r => $r,
982 editor_cb => sub { print "Committed r$_[0]\n" },
983 svn_path => $svn_path );
984 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
985 print "No changes\n$ta == $tb\n";
989 sub escape_uri_only {
992 foreach (split m{/}, $uri) {
993 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1001 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1002 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1003 $url = "$scheme://$domain$uri";
1009 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1010 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1012 die "Too many arguments specified\n";
1015 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1017 if (!$file_type && !$diff_status) {
1018 print STDERR "svn: '$path' is not under version control\n";
1022 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1024 die "Unable to determine upstream SVN information from ",
1025 "working tree history\n";
1028 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1029 $path = "." if $path eq "";
1031 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1034 print escape_url($full_url), "\n";
1038 my $result = "Path: $path\n";
1039 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1040 $result .= "URL: " . escape_url($full_url) . "\n";
1043 my $repos_root = $gs->repos_root;
1044 Git::SVN::remove_username($repos_root);
1045 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1048 $result .= "Repository Root: (offline)\n";
1050 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1051 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1052 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1054 $result .= "Node Kind: " .
1055 ($file_type eq "dir" ? "directory" : "file") . "\n";
1057 my $schedule = $diff_status eq "A"
1059 : ($diff_status eq "D" ? "delete" : "normal");
1060 $result .= "Schedule: $schedule\n";
1062 if ($diff_status eq "A") {
1063 print $result, "\n";
1067 my ($lc_author, $lc_rev, $lc_date_utc);
1068 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1069 my $log = command_output_pipe(@args);
1070 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1072 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1074 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1075 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1076 (undef, $lc_rev, undef) = ::extract_metadata($1);
1081 Git::SVN::Log::set_local_timezone();
1083 $result .= "Last Changed Author: $lc_author\n";
1084 $result .= "Last Changed Rev: $lc_rev\n";
1085 $result .= "Last Changed Date: " .
1086 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1088 if ($file_type ne "dir") {
1089 my $text_last_updated_date =
1090 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1092 "Text Last Updated: " .
1093 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1096 if ($diff_status eq "D") {
1098 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1099 if ($file_type eq "link") {
1100 my $file_name = <$fh>;
1101 $checksum = md5sum("link $file_name");
1103 $checksum = md5sum($fh);
1105 command_close_pipe($fh, $ctx);
1106 } elsif ($file_type eq "link") {
1108 command(qw(cat-file blob), "HEAD:$path");
1110 md5sum("link " . $file_name);
1112 open FILE, "<", $path or die $!;
1113 $checksum = md5sum(\*FILE);
1114 close FILE or die $!;
1116 $result .= "Checksum: " . $checksum . "\n";
1119 print $result, "\n";
1123 my $target = shift || $_revision or die "SVN revision required\n";
1124 $target = $1 if $target =~ /^r(\d+)$/;
1125 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1126 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1128 die "Unable to determine upstream SVN information from ".
1131 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1132 $gs->rev_map_set($r, $c, 'reset', $uuid);
1133 print "r$r = $c ($gs->{ref_id})\n";
1137 if (!$can_compress) {
1138 warn "Compress::Zlib could not be found; unhandled.log " .
1139 "files will not be compressed.\n";
1141 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1144 ########################### utility functions #########################
1147 my @cmd = qw/rebase/;
1148 push @cmd, '-v' if $_verbose;
1149 push @cmd, qw/--merge/ if $_merge;
1150 push @cmd, "--strategy=$_strategy" if $_strategy;
1154 sub post_fetch_checkout {
1155 return if $_no_checkout;
1156 my $gs = $Git::SVN::_head or return;
1157 return if verify_ref('refs/heads/master^0');
1159 # look for "trunk" ref if it exists
1160 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1161 my $fetch = $remote->{fetch};
1163 foreach my $p (keys %$fetch) {
1164 basename($fetch->{$p}) eq 'trunk' or next;
1165 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1170 my $valid_head = verify_ref('HEAD^0');
1171 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1172 return if ($valid_head || !verify_ref('HEAD^0'));
1174 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1175 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1176 return if -f $index;
1178 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1179 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1180 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1181 print STDERR "Checked out HEAD:\n ",
1182 $gs->full_url, " r", $gs->last_rev, "\n";
1185 sub complete_svn_url {
1186 my ($url, $path) = @_;
1188 if ($path !~ m#^[a-z\+]+://#) {
1189 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1190 fatal("E: '$path' is not a complete URL ",
1191 "and a separate URL is not specified");
1193 return ($url, $path);
1198 sub complete_url_ls_init {
1199 my ($ra, $repo_path, $switch, $pfx) = @_;
1200 unless ($repo_path) {
1201 print STDERR "W: $switch not specified\n";
1204 $repo_path =~ s#/+$##;
1205 if ($repo_path =~ m#^[a-z\+]+://#) {
1206 $ra = Git::SVN::Ra->new($repo_path);
1209 $repo_path =~ s#^/+##;
1211 fatal("E: '$repo_path' is not a complete URL ",
1212 "and a separate URL is not specified");
1215 my $url = $ra->{url};
1216 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1217 my $k = "svn-remote.$gs->{repo_id}.url";
1218 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1219 if ($orig_url && ($orig_url ne $gs->{url})) {
1220 die "$k already set: $orig_url\n",
1221 "wanted to set to: $gs->{url}\n";
1223 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1224 my $remote_path = "$gs->{path}/$repo_path";
1225 $remote_path =~ s#/+#/#g;
1226 $remote_path =~ s#^/##g;
1227 $remote_path .= "/*" if $remote_path !~ /\*/;
1228 my ($n) = ($switch =~ /^--(\w+)/);
1229 if (length $pfx && $pfx !~ m#/$#) {
1230 die "--prefix='$pfx' must have a trailing slash '/'\n";
1232 command_noisy('config',
1234 "svn-remote.$gs->{repo_id}.$n",
1235 "$remote_path:refs/remotes/$pfx*" .
1236 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1241 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1242 { STDERR => 0 }); };
1245 sub get_tree_from_treeish {
1247 # $treeish can be a symbolic ref, too:
1248 my $type = command_oneline(qw/cat-file -t/, $treeish);
1250 while ($type eq 'tag') {
1251 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1253 if ($type eq 'commit') {
1254 $expected = (grep /^tree /, command(qw/cat-file commit/,
1256 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1257 die "Unable to get tree from $treeish\n" unless $expected;
1258 } elsif ($type eq 'tree') {
1259 $expected = $treeish;
1261 die "$treeish is a $type, expected tree, tag or commit\n";
1266 sub get_commit_entry {
1267 my ($treeish) = shift;
1268 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1269 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1270 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1271 open my $log_fh, '>', $commit_editmsg or croak $!;
1273 my $type = command_oneline(qw/cat-file -t/, $treeish);
1274 if ($type eq 'commit' || $type eq 'tag') {
1275 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1283 $in_msg = 1 if (/^\s*$/);
1284 $author = $1 if (/^author (.*>)/);
1285 } elsif (/^git-svn-id: /) {
1286 # skip this for now, we regenerate the
1287 # correct one on re-fetch anyways
1288 # TODO: set *:merge properties or like...
1290 if (/^From:/ || /^Signed-off-by:/) {
1296 $msgbuf =~ s/\s+$//s;
1297 if ($Git::SVN::_add_author_from && defined($author)
1299 $msgbuf .= "\n\nFrom: $author";
1301 print $log_fh $msgbuf or croak $!;
1302 command_close_pipe($msg_fh, $ctx);
1304 close $log_fh or croak $!;
1306 if ($_edit || ($type eq 'tree')) {
1307 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1308 # TODO: strip out spaces, comments, like git-commit.sh
1309 system($editor, $commit_editmsg);
1311 rename $commit_editmsg, $commit_msg or croak $!;
1314 # SVN requires messages to be UTF-8 when entering the repo
1316 open $log_fh, '<', $commit_msg or croak $!;
1318 chomp($log_entry{log} = <$log_fh>);
1320 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1321 my $msg = $log_entry{log};
1323 eval { $msg = Encode::decode($enc, $msg, 1) };
1325 die "Could not decode as $enc:\n", $msg,
1326 "\nPerhaps you need to set i18n.commitencoding\n";
1329 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1330 die "Could not encode as UTF-8:\n$msg\n" if $@;
1332 $log_entry{log} = $msg;
1334 close $log_fh or croak $!;
1341 my ($str, $file, $mode) = @_;
1342 open my $fd,'>',$file or croak $!;
1343 print $fd $str,"\n" or croak $!;
1344 close $fd or croak $!;
1345 chmod ($mode &~ umask, $file) if (defined $mode);
1350 open my $fd,'<',$file or croak "$!: file: $file\n";
1353 close $fd or croak $!;
1358 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1360 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1361 my $log = $cmd eq 'log';
1362 while (<$authors>) {
1364 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1365 my ($user, $name, $email) = ($1, $2, $3);
1367 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1369 $users{$user} = [$name, $email];
1372 close $authors or croak $!;
1375 # convert GetOpt::Long specs for use by git-config
1376 sub read_repo_config {
1377 return unless -d $ENV{GIT_DIR};
1380 foreach my $o (keys %$opts) {
1381 # if we have mixedCase and a long option-only, then
1382 # it's a config-only variable that we don't need for
1384 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1385 my $v = $opts->{$o};
1386 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1388 my $arg = 'git config';
1389 $arg .= ' --int' if ($o =~ /[:=]i$/);
1390 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1391 if (ref $v eq 'ARRAY') {
1392 chomp(my @tmp = `$arg --get-all svn.$key`);
1395 chomp(my $tmp = `$arg --get svn.$key`);
1396 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1401 delete @$opts{@config_only} if @config_only;
1404 sub extract_metadata {
1405 my $id = shift or return (undef, undef, undef);
1406 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1407 \s([a-f\d\-]+)$/ix);
1408 if (!defined $rev || !$uuid || !$url) {
1409 # some of the original repositories I made had
1410 # identifiers like this:
1411 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1413 return ($url, $rev, $uuid);
1417 return extract_metadata((grep(/^git-svn-id: /,
1418 command(qw/cat-file commit/, shift)))[-1]);
1421 sub cmt_sha2rev_batch {
1423 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1426 foreach my $sha (@{$list}) {
1429 print $out $sha, "\n";
1431 while (my $line = <$in>) {
1432 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1435 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1439 } elsif ($line =~ /^(git-svn-id: )/) {
1440 my (undef, $rev, undef) =
1441 extract_metadata($line);
1445 $size -= length($line);
1446 last if ($size == 0);
1450 command_close_bidi_pipe($pid, $in, $out, $ctx);
1455 sub working_head_info {
1456 my ($head, $refs) = @_;
1457 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1458 my ($fh, $ctx) = command_output_pipe(@args, $head);
1462 if ( m{^commit ($::sha1)$} ) {
1463 unshift @$refs, $hash if $hash and $refs;
1467 next unless s{^\s*(git-svn-id:)}{$1};
1468 my ($url, $rev, $uuid) = extract_metadata($_);
1469 if (defined $url && defined $rev) {
1470 next if $max{$url} and $max{$url} < $rev;
1471 if (my $gs = Git::SVN->find_by_url($url)) {
1472 my $c = $gs->rev_map_get($rev, $uuid);
1473 if ($c && $c eq $hash) {
1474 close $fh; # break the pipe
1475 return ($url, $rev, $uuid, $gs);
1477 $max{$url} ||= $gs->rev_map_max;
1482 command_close_pipe($fh, $ctx);
1483 (undef, undef, undef, undef);
1486 sub read_commit_parents {
1487 my ($parents, $c) = @_;
1488 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1489 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1490 @{$parents->{$c}} = split(/ /, $p);
1493 sub linearize_history {
1494 my ($gs, $refs) = @_;
1496 foreach my $c (@$refs) {
1497 read_commit_parents(\%parents, $c);
1502 my $last_svn_commit = $gs->last_commit;
1503 foreach my $c (reverse @$refs) {
1504 next if $c eq $last_svn_commit;
1507 unshift @linear_refs, $c;
1510 # we only want the first parent to diff against for linear
1511 # history, we save the rest to inject when we finalize the
1513 my $fp_a = verify_ref("$c~1");
1514 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1515 if (!$fp_a || !$fp_b) {
1517 "has no parent commit, and therefore ",
1518 "nothing to diff against.\n",
1519 "You should be working from a repository ",
1520 "originally created by git-svn\n";
1522 if ($fp_a ne $fp_b) {
1523 die "$c~1 = $fp_a, however parsing commit $c ",
1524 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1527 foreach my $p (@{$parents{$c}}) {
1531 (\@linear_refs, \%parents);
1534 sub find_file_type_and_diff_status {
1536 return ('dir', '') if $path eq '';
1539 command_oneline(qw(diff --cached --name-status --), $path) || "";
1540 my $diff_status = (split(' ', $diff_output))[0] || "";
1542 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1544 return (undef, undef) if !$diff_status && !$ls_tree;
1546 if ($diff_status eq "A") {
1547 return ("link", $diff_status) if -l $path;
1548 return ("dir", $diff_status) if -d $path;
1549 return ("file", $diff_status);
1552 my $mode = (split(' ', $ls_tree))[0] || "";
1554 return ("link", $diff_status) if $mode eq "120000";
1555 return ("dir", $diff_status) if $mode eq "040000";
1556 return ("file", $diff_status);
1562 my $md5 = Digest::MD5->new();
1563 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1564 $md5->addfile($arg) or croak $!;
1565 } elsif ($ref eq 'SCALAR') {
1566 $md5->add($$arg) or croak $!;
1568 $md5->add($arg) or croak $!;
1570 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1572 return $md5->hexdigest();
1576 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1577 my $out_filename = $_ . ".gz";
1578 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1580 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1581 die "Unable to open $out_filename: $!\n";
1584 while ($res = sysread($in_fh, my $str, 1024)) {
1585 $gz->gzwrite($str) or
1586 die "Unable to write: ".$gz->gzerror()."!\n";
1588 unlink $_ or die "unlink $File::Find::name: $!\n";
1589 } elsif (-f $_ && basename($_) eq "index") {
1590 unlink $_ or die "unlink $_: $!\n";
1597 use Fcntl qw/:DEFAULT :seek/;
1598 use constant rev_map_fmt => 'NH40';
1599 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1600 $_repack $_repack_flags $_use_svm_props $_head
1601 $_use_svnsync_props $no_reuse_existing $_minimize_url
1602 $_use_log_author $_add_author_from $_localtime/;
1604 use File::Path qw/mkpath/;
1605 use File::Copy qw/copy/;
1608 my ($_gc_nr, $_gc_period);
1610 # properties that we do not log:
1613 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1614 svn:special svn:executable
1615 svn:entry:committed-rev
1616 svn:entry:last-author
1618 svn:entry:committed-date/;
1620 # some options are read globally, but can be overridden locally
1621 # per [svn-remote "..."] section. Command-line options will *NOT*
1622 # override options set in an [svn-remote "..."] section
1624 for my $option (qw/follow_parent no_metadata use_svm_props
1625 use_svnsync_props/) {
1628 my $prop = "-$option";
1631 return $self->{$prop} if exists $self->{$prop};
1632 my $k = "svn-remote.$self->{repo_id}.$key";
1633 eval { command_oneline(qw/config --get/, $k) };
1635 $self->{$prop} = ${"Git::SVN::_$option"};
1637 my $v = command_oneline(qw/config --bool/,$k);
1638 $self->{$prop} = $v eq 'false' ? 0 : 1;
1640 return $self->{$prop};
1646 my (%LOCKFILES, %INDEX_FILES);
1648 unlink keys %LOCKFILES if %LOCKFILES;
1649 unlink keys %INDEX_FILES if %INDEX_FILES;
1652 sub resolve_local_globs {
1653 my ($url, $fetch, $glob_spec) = @_;
1654 return unless defined $glob_spec;
1655 my $ref = $glob_spec->{ref};
1656 my $path = $glob_spec->{path};
1657 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1658 next unless m#^$ref->{regex}$#;
1660 my $pathname = desanitize_refname($path->full_path($p));
1661 my $refname = desanitize_refname($ref->full_path($p));
1662 if (my $existing = $fetch->{$pathname}) {
1663 if ($existing ne $refname) {
1664 die "Refspec conflict:\n",
1665 "existing: $existing\n",
1666 " globbed: $refname\n";
1668 my $u = (::cmt_metadata("$refname"))[0];
1669 $u =~ s!^\Q$url\E(/|$)!! or die
1670 "$refname: '$url' not found in '$u'\n";
1671 if ($pathname ne $u) {
1672 warn "W: Refspec glob conflict ",
1673 "(ref: $refname):\n",
1674 "expected path: $pathname\n",
1676 "Continuing ahead with $u\n";
1680 $fetch->{$pathname} = $refname;
1685 sub parse_revision_argument {
1686 my ($base, $head) = @_;
1687 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1688 return ($base, $head);
1690 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1691 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1692 return ($head, $head) if ($::_revision eq 'HEAD');
1693 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1694 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1695 die "revision argument: $::_revision not understood by git-svn\n";
1699 my ($repo_id, $remotes) = @_;
1703 $repo_id = $gs->{repo_id};
1705 $remotes ||= read_all_remotes();
1706 my $remote = $remotes->{$repo_id} or
1707 die "[svn-remote \"$repo_id\"] unknown\n";
1708 my $fetch = $remote->{fetch};
1709 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1711 my $ra = Git::SVN::Ra->new($url);
1712 my $uuid = $ra->get_uuid;
1713 my $head = $ra->get_latest_revnum;
1714 $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1715 my $base = defined $fetch ? $head : 0;
1717 # read the max revs for wildcard expansion (branches/*, tags/*)
1718 foreach my $t (qw/branches tags/) {
1719 defined $remote->{$t} or next;
1720 push @globs, @{$remote->{$t}};
1722 my $max_rev = eval { tmp_config(qw/--int --get/,
1723 "svn-remote.$repo_id.${t}-maxRev") };
1724 if (defined $max_rev && ($max_rev < $base)) {
1726 } elsif (!defined $max_rev) {
1732 foreach my $p (sort keys %$fetch) {
1733 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1734 my $lr = $gs->rev_map_max;
1736 $base = $lr if ($lr < $base);
1742 ($base, $head) = parse_revision_argument($base, $head);
1743 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1746 sub read_all_remotes {
1748 my $use_svm_props = eval { command_oneline(qw/config --bool
1749 svn.useSvmProps/) };
1750 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1751 my $svn_refspec = qr{\s*/?(.*?)\s*:\s*(.+?)\s*};
1752 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1753 if (m!^(.+)\.fetch=$svn_refspec$!) {
1754 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1755 die("svn-remote.$remote: remote ref '$remote_ref' "
1756 . "must start with 'refs/'\n")
1757 unless $remote_ref =~ m{^refs/};
1758 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1759 $r->{$remote}->{svm} = {} if $use_svm_props;
1760 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1761 $r->{$1}->{svm} = {};
1762 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1763 $r->{$1}->{url} = $2;
1764 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1765 my ($remote, $t, $local_ref, $remote_ref) =
1767 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1768 . "must start with 'refs/'\n")
1769 unless $remote_ref =~ m{^refs/};
1773 path => Git::SVN::GlobSpec->new($local_ref),
1774 ref => Git::SVN::GlobSpec->new($remote_ref) };
1775 if (length($rs->{ref}->{right}) != 0) {
1776 die "The '*' glob character must be the last ",
1777 "character of '$remote_ref'\n";
1779 push @{ $r->{$remote}->{$t} }, $rs;
1784 if (defined $r->{$_}->{svm}) {
1787 my $section = "svn-remote.$_";
1789 source => tmp_config('--get',
1790 "$section.svm-source"),
1791 replace => tmp_config('--get',
1792 "$section.svm-replace"),
1795 $r->{$_}->{svm} = $svm;
1803 $_gc_nr = $_gc_period = 1000;
1804 if (defined $_repack || defined $_repack_flags) {
1805 warn "Repack options are obsolete; they have no effect.\n";
1809 sub verify_remotes_sanity {
1810 return unless -d $ENV{GIT_DIR};
1812 foreach (command(qw/config -l/)) {
1813 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1815 die "Remote ref refs/remote/$1 is tracked by",
1816 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1817 "Please resolve this ambiguity in ",
1818 "your git configuration file before ",
1826 sub find_existing_remote {
1827 my ($url, $remotes) = @_;
1828 return undef if $no_reuse_existing;
1830 foreach my $repo_id (keys %$remotes) {
1831 my $u = $remotes->{$repo_id}->{url} or next;
1833 $existing = $repo_id;
1839 sub init_remote_config {
1840 my ($self, $url, $no_write) = @_;
1841 $url =~ s!/+$!!; # strip trailing slash
1842 my $r = read_all_remotes();
1843 my $existing = find_existing_remote($url, $r);
1845 unless ($no_write) {
1846 print STDERR "Using existing ",
1847 "[svn-remote \"$existing\"]\n";
1849 $self->{repo_id} = $existing;
1850 } elsif ($_minimize_url) {
1851 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1852 $existing = find_existing_remote($min_url, $r);
1854 unless ($no_write) {
1855 print STDERR "Using existing ",
1856 "[svn-remote \"$existing\"]\n";
1858 $self->{repo_id} = $existing;
1860 if ($min_url ne $url) {
1861 unless ($no_write) {
1862 print STDERR "Using higher level of URL: ",
1863 "$url => $min_url\n";
1865 my $old_path = $self->{path};
1866 $self->{path} = $url;
1867 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1868 if (length $old_path) {
1869 $self->{path} .= "/$old_path";
1876 # verify that we aren't overwriting anything:
1878 command_oneline('config', '--get',
1879 "svn-remote.$self->{repo_id}.url")
1881 if ($orig_url && ($orig_url ne $url)) {
1882 die "svn-remote.$self->{repo_id}.url already set: ",
1883 "$orig_url\nwanted to set to: $url\n";
1886 my ($xrepo_id, $xpath) = find_ref($self->refname);
1887 if (!$no_write && defined $xpath) {
1888 die "svn-remote.$xrepo_id.fetch already set to track ",
1889 "$xpath:", $self->refname, "\n";
1891 unless ($no_write) {
1892 command_noisy('config',
1893 "svn-remote.$self->{repo_id}.url", $url);
1894 $self->{path} =~ s{^/}{};
1895 command_noisy('config', '--add',
1896 "svn-remote.$self->{repo_id}.fetch",
1897 "$self->{path}:".$self->refname);
1899 $self->{url} = $url;
1902 sub find_by_url { # repos_root and, path are optional
1903 my ($class, $full_url, $repos_root, $path) = @_;
1905 return undef unless defined $full_url;
1906 remove_username($full_url);
1907 remove_username($repos_root) if defined $repos_root;
1908 my $remotes = read_all_remotes();
1909 if (defined $full_url && defined $repos_root && !defined $path) {
1911 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1913 foreach my $repo_id (keys %$remotes) {
1914 my $u = $remotes->{$repo_id}->{url} or next;
1915 remove_username($u);
1916 next if defined $repos_root && $repos_root ne $u;
1918 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1919 foreach my $t (qw/branches tags/) {
1920 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1921 resolve_local_globs($u, $fetch, $globspec);
1925 my $rwr = rewrite_root({repo_id => $repo_id});
1926 my $svm = $remotes->{$repo_id}->{svm}
1927 if defined $remotes->{$repo_id}->{svm};
1928 unless (defined $p) {
1934 remove_username($z);
1935 } elsif (defined $svm) {
1936 $z = $svm->{source};
1937 $prefix = $svm->{replace};
1938 $prefix =~ s#^\Q$u\E(?:/|$)##;
1941 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1943 foreach my $f (keys %$fetch) {
1945 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1952 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1953 my $self = _new($class, $repo_id, $ref_id, $path);
1955 $self->init_remote_config($url, $no_write);
1962 foreach (command(qw/config -l/)) {
1963 next unless m!^svn-remote\.(.+)\.fetch=
1964 \s*/?(.*?)\s*:\s*(.+?)\s*$!x;
1965 my ($repo_id, $path, $ref) = ($1, $2, $3);
1966 if ($ref eq $ref_id) {
1967 $path = '' if ($path =~ m#^\./?#);
1968 return ($repo_id, $path);
1971 (undef, undef, undef);
1975 my ($class, $ref_id, $repo_id, $path) = @_;
1976 if (defined $ref_id && !defined $repo_id && !defined $path) {
1977 ($repo_id, $path) = find_ref($ref_id);
1978 if (!defined $repo_id) {
1979 die "Could not find a \"svn-remote.*.fetch\" key ",
1980 "in the repository configuration matching: ",
1984 my $self = _new($class, $repo_id, $ref_id, $path);
1985 if (!defined $self->{path} || !length $self->{path}) {
1986 my $fetch = command_oneline('config', '--get',
1987 "svn-remote.$repo_id.fetch",
1989 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1990 "\":$ref_id\$\" in config\n";
1991 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1993 $self->{url} = command_oneline('config', '--get',
1994 "svn-remote.$repo_id.url") or
1995 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2001 my ($refname) = $_[0]->{ref_id} ;
2003 # It cannot end with a slash /, we'll throw up on this because
2004 # SVN can't have directories with a slash in their name, either:
2005 if ($refname =~ m{/$}) {
2006 die "ref: '$refname' ends with a trailing slash, this is ",
2007 "not permitted by git nor Subversion\n";
2010 # It cannot have ASCII control character space, tilde ~, caret ^,
2011 # colon :, question-mark ?, asterisk *, space, or open bracket [
2014 # Additionally, % must be escaped because it is used for escaping
2015 # and we want our escaped refname to be reversible
2016 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2018 # no slash-separated component can begin with a dot .
2020 $refname =~ s{/\.}{/%2E}g;
2022 # It cannot have two consecutive dots .. anywhere
2024 $refname =~ s{\.\.}{%2E%2E}g;
2029 sub desanitize_refname {
2031 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2037 return $self->{svm}->{uuid} if $self->svm;
2039 unless ($self->{svm}) {
2040 die "SVM UUID not cached, and reading remotely failed\n";
2042 $self->{svm}->{uuid};
2047 return $self->{svm} if $self->{svm};
2049 # see if we have it in our config, first:
2051 my $section = "svn-remote.$self->{repo_id}";
2053 source => tmp_config('--get', "$section.svm-source"),
2054 uuid => tmp_config('--get', "$section.svm-uuid"),
2055 replace => tmp_config('--get', "$section.svm-replace"),
2058 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2059 $self->{svm} = $svm;
2065 my ($self, $ra) = @_;
2066 return $ra if $self->svm;
2068 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2069 "(svm:source, svm:uuid) ",
2070 "from the following URLs:\n" );
2071 sub read_svm_props {
2072 my ($self, $ra, $path, $r) = @_;
2073 my $props = ($ra->get_dir($path, $r))[2];
2074 my $src = $props->{'svm:source'};
2075 my $uuid = $props->{'svm:uuid'};
2076 return undef if (!$src || !$uuid);
2080 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2081 or die "doesn't look right - svm:uuid is '$uuid'\n";
2083 # the '!' is used to mark the repos_root!/relative/path
2084 $src =~ s{/?!/?}{/};
2085 $src =~ s{/+$}{}; # no trailing slashes please
2086 # username is of no interest
2087 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2089 my $replace = $ra->{url};
2090 $replace .= "/$path" if length $path;
2092 my $section = "svn-remote.$self->{repo_id}";
2093 tmp_config("$section.svm-source", $src);
2094 tmp_config("$section.svm-replace", $replace);
2095 tmp_config("$section.svm-uuid", $uuid);
2103 my $r = $ra->get_latest_revnum;
2104 my $path = $self->{path};
2106 while (length $path) {
2107 unless ($tried{"$self->{url}/$path"}) {
2108 return $ra if $self->read_svm_props($ra, $path, $r);
2109 $tried{"$self->{url}/$path"} = 1;
2111 $path =~ s#/?[^/]+$##;
2113 die "Path: '$path' should be ''\n" if $path ne '';
2114 return $ra if $self->read_svm_props($ra, $path, $r);
2115 $tried{"$self->{url}/$path"} = 1;
2117 if ($ra->{repos_root} eq $self->{url}) {
2118 die @err, (map { " $_\n" } keys %tried), "\n";
2121 # nope, make sure we're connected to the repository root:
2124 $path = $ra->{svn_path};
2125 $ra = Git::SVN::Ra->new($ra->{repos_root});
2126 while (length $path) {
2127 unless ($tried{"$ra->{url}/$path"}) {
2128 $ok = $self->read_svm_props($ra, $path, $r);
2130 $tried{"$ra->{url}/$path"} = 1;
2132 $path =~ s#/?[^/]+$##;
2134 die "Path: '$path' should be ''\n" if $path ne '';
2135 $ok ||= $self->read_svm_props($ra, $path, $r);
2136 $tried{"$ra->{url}/$path"} = 1;
2138 die @err, (map { " $_\n" } keys %tried), "\n";
2140 Git::SVN::Ra->new($self->{url});
2145 return $self->{svnsync} if $self->{svnsync};
2147 if ($self->no_metadata) {
2148 die "Can't have both 'noMetadata' and ",
2149 "'useSvnsyncProps' options set!\n";
2151 if ($self->rewrite_root) {
2152 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2157 # see if we have it in our config, first:
2159 my $section = "svn-remote.$self->{repo_id}";
2161 my $url = tmp_config('--get', "$section.svnsync-url");
2162 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2163 die "doesn't look right - svn:sync-from-url is '$url'\n";
2165 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2166 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2167 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2169 $svnsync = { url => $url, uuid => $uuid }
2171 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2172 return $self->{svnsync} = $svnsync;
2175 my $err = "useSvnsyncProps set, but failed to read " .
2176 "svnsync property: svn:sync-from-";
2177 my $rp = $self->ra->rev_proplist(0);
2179 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2180 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2181 die "doesn't look right - svn:sync-from-url is '$url'\n";
2183 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2184 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2185 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2187 my $section = "svn-remote.$self->{repo_id}";
2188 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2189 tmp_config('--add', "$section.svnsync-url", $url);
2190 return $self->{svnsync} = { url => $url, uuid => $uuid };
2193 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2194 # remote lookup (useful for 'git svn log').
2197 unless ($self->{ra_uuid}) {
2198 my $key = "svn-remote.$self->{repo_id}.uuid";
2199 my $uuid = eval { tmp_config('--get', $key) };
2200 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2201 $self->{ra_uuid} = $uuid;
2203 die "ra_uuid called without URL\n" unless $self->{url};
2204 $self->{ra_uuid} = $self->ra->get_uuid;
2205 tmp_config('--add', $key, $self->{ra_uuid});
2211 sub _set_repos_root {
2212 my ($self, $repos_root) = @_;
2213 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2214 $repos_root ||= $self->ra->{repos_root};
2215 tmp_config($k, $repos_root);
2221 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2222 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2227 my $ra = Git::SVN::Ra->new($self->{url});
2228 $self->_set_repos_root($ra->{repos_root});
2229 if ($self->use_svm_props && !$self->{svm}) {
2230 if ($self->no_metadata) {
2231 die "Can't have both 'noMetadata' and ",
2232 "'useSvmProps' options set!\n";
2233 } elsif ($self->use_svnsync_props) {
2234 die "Can't have both 'useSvnsyncProps' and ",
2235 "'useSvmProps' options set!\n";
2237 $ra = $self->_set_svm_vars($ra);
2238 $self->{-want_revprops} = 1;
2243 # prop_walk(PATH, REV, SUB)
2244 # -------------------------
2245 # Recursively traverse PATH at revision REV and invoke SUB for each
2246 # directory that contains a SVN property. SUB will be invoked as
2247 # follows: &SUB(gs, path, props); where `gs' is this instance of
2248 # Git::SVN, `path' the path to the directory where the properties
2249 # `props' were found. The `path' will be relative to point of checkout,
2250 # that is, if url://repo/trunk is the current Git branch, and that
2251 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2252 # as `path' (note the trailing `/').
2254 my ($self, $path, $rev, $sub) = @_;
2257 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2260 # Strip the irrelevant part of the path.
2261 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2262 # Ensure the path is terminated by a `/'.
2265 # The properties contain all the internal SVN stuff nobody
2266 # (usually) cares about.
2267 my $interesting_props = 0;
2268 foreach (keys %{$props}) {
2269 # If it doesn't start with `svn:', it must be a
2270 # user-defined property.
2271 ++$interesting_props and next if $_ !~ /^svn:/;
2272 # FIXME: Fragile, if SVN adds new public properties,
2273 # this needs to be updated.
2274 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2275 |eol-style|mime-type
2276 |externals|needs-lock)$/x;
2278 &$sub($self, $p, $props) if $interesting_props;
2280 foreach (sort keys %$dirent) {
2281 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2282 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2286 sub last_rev { ($_[0]->last_rev_commit)[0] }
2287 sub last_commit { ($_[0]->last_rev_commit)[1] }
2289 # returns the newest SVN revision number and newest commit SHA1
2290 sub last_rev_commit {
2292 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2293 return ($self->{last_rev}, $self->{last_commit});
2295 my $c = ::verify_ref($self->refname.'^0');
2296 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2297 my $rev = (::cmt_metadata($c))[1];
2299 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2303 my $map_path = $self->map_path;
2304 unless (-e $map_path) {
2305 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2306 return (undef, undef);
2308 my ($rev, $commit) = $self->rev_map_max(1);
2309 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2310 return ($rev, $commit);
2313 sub get_fetch_range {
2314 my ($self, $min, $max) = @_;
2315 $max ||= $self->ra->get_latest_revnum;
2316 $min ||= $self->rev_map_max;
2322 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2323 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2324 if (! -f $config && -f $old_def_config) {
2325 rename $old_def_config, $config or
2326 die "Failed rename $old_def_config => $config: $!\n";
2328 my $old_config = $ENV{GIT_CONFIG};
2329 $ENV{GIT_CONFIG} = $config;
2332 unless (-f $config) {
2334 open my $fh, '>', $config or
2335 die "Can't open $config: $!\n";
2336 print $fh "; This file is used internally by ",
2338 "Couldn't write to $config: $!\n";
2339 print $fh "; You should not have to edit it\n" or
2340 die "Couldn't write to $config: $!\n";
2341 close $fh or die "Couldn't close $config: $!\n";
2343 command('config', @args);
2346 if (defined $old_config) {
2347 $ENV{GIT_CONFIG} = $old_config;
2349 delete $ENV{GIT_CONFIG};
2352 wantarray ? @ret : $ret[0];
2356 my ($self, $sub) = @_;
2357 my $old_index = $ENV{GIT_INDEX_FILE};
2358 $ENV{GIT_INDEX_FILE} = $self->{index};
2361 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2362 mkpath([$dir]) unless -d $dir;
2366 if (defined $old_index) {
2367 $ENV{GIT_INDEX_FILE} = $old_index;
2369 delete $ENV{GIT_INDEX_FILE};
2372 wantarray ? @ret : $ret[0];
2375 sub assert_index_clean {
2376 my ($self, $treeish) = @_;
2378 $self->tmp_index_do(sub {
2379 command_noisy('read-tree', $treeish) unless -e $self->{index};
2380 my $x = command_oneline('write-tree');
2381 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2382 /^tree ($::sha1)/mo);
2385 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2386 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2387 command_noisy('read-tree', $treeish);
2388 $x = command_oneline('write-tree');
2390 ::fatal "trees ($treeish) $y != $x\n",
2391 "Something is seriously wrong...";
2396 sub get_commit_parents {
2397 my ($self, $log_entry) = @_;
2398 my (%seen, @ret, @tmp);
2399 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2400 if (my $ip = $self->{inject_parents}) {
2401 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2405 if (my $cur = ::verify_ref($self->refname.'^0')) {
2408 if (my $ipd = $self->{inject_parents_dcommit}) {
2409 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2410 push @tmp, @$commit;
2413 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2414 while (my $p = shift @tmp) {
2418 # MAXPARENT is defined to 16 in commit-tree.c:
2422 die "r$log_entry->{revision}: No room for parents:\n\t",
2423 join("\n\t", @tmp), "\n";
2430 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2431 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2432 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2435 if ($rwr !~ m#^[a-z\+]+://#) {
2436 die "$rwr is not a valid URL (key: $k)\n";
2439 $self->{-rewrite_root} = $rwr;
2444 ($self->rewrite_root || $self->{url}) .
2445 (length $self->{path} ? '/' . $self->{path} : '');
2450 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2454 sub set_commit_header_env {
2455 my ($log_entry) = @_;
2457 foreach my $ned (qw/NAME EMAIL DATE/) {
2458 foreach my $ac (qw/AUTHOR COMMITTER/) {
2459 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2463 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2464 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2465 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2467 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2468 ? $log_entry->{commit_name}
2469 : $log_entry->{name};
2470 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2471 ? $log_entry->{commit_email}
2472 : $log_entry->{email};
2476 sub restore_commit_header_env {
2478 foreach my $ned (qw/NAME EMAIL DATE/) {
2479 foreach my $ac (qw/AUTHOR COMMITTER/) {
2480 my $k = "GIT_${ac}_${ned}";
2481 if (defined $env->{$k}) {
2482 $ENV{$k} = $env->{$k};
2491 command_noisy('gc', '--auto');
2495 my ($self, $log_entry) = @_;
2496 my $lr = $self->last_rev;
2497 if (defined $lr && $lr >= $log_entry->{revision}) {
2498 die "Last fetched revision of ", $self->refname,
2499 " was r$lr, but we are about to fetch: ",
2500 "r$log_entry->{revision}!\n";
2502 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2503 croak "$log_entry->{revision} = $c already exists! ",
2504 "Why are we refetching it?\n";
2506 my $old_env = set_commit_header_env($log_entry);
2507 my $tree = $log_entry->{tree};
2508 if (!defined $tree) {
2509 $tree = $self->tmp_index_do(sub {
2510 command_oneline('write-tree') });
2512 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2514 my @exec = ('git', 'commit-tree', $tree);
2515 foreach ($self->get_commit_parents($log_entry)) {
2516 push @exec, '-p', $_;
2518 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2522 # we always get UTF-8 from SVN, but we may want our commits in
2523 # a different encoding.
2524 if (my $enc = Git::config('i18n.commitencoding')) {
2526 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2528 print $msg_fh $log_entry->{log} or croak $!;
2529 restore_commit_header_env($old_env);
2530 unless ($self->no_metadata) {
2531 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2534 $msg_fh->flush == 0 or croak $!;
2535 close $msg_fh or croak $!;
2536 chomp(my $commit = do { local $/; <$out_fh> });
2537 close $out_fh or croak $!;
2540 if ($commit !~ /^$::sha1$/o) {
2541 die "Failed to commit, invalid sha1: $commit\n";
2544 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2546 $self->{last_rev} = $log_entry->{revision};
2547 $self->{last_commit} = $commit;
2548 print "r$log_entry->{revision}" unless $::_q > 1;
2549 if (defined $log_entry->{svm_revision}) {
2550 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2551 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2552 0, $self->svm_uuid);
2554 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2555 if (--$_gc_nr == 0) {
2556 $_gc_nr = $_gc_period;
2563 my ($self, $paths, $r) = @_;
2564 return 1 if $self->{path} eq '';
2565 if (my $path = $paths->{"/$self->{path}"}) {
2566 return ($path->{action} eq 'D') ? 0 : 1;
2568 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2569 if (grep /$self->{path_regex}/, keys %$paths) {
2573 foreach (split m#/#, $self->{path}) {
2575 next unless ($paths->{$c} &&
2576 ($paths->{$c}->{action} =~ /^[AR]$/));
2577 if ($self->ra->check_path($self->{path}, $r) ==
2585 sub find_parent_branch {
2586 my ($self, $paths, $rev) = @_;
2587 return undef unless $self->follow_parent;
2588 unless (defined $paths) {
2589 my $err_handler = $SVN::Error::handler;
2590 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2591 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2592 sub { $paths = $_[0] });
2593 $SVN::Error::handler = $err_handler;
2595 return undef unless defined $paths;
2597 # look for a parent from another branch:
2598 my @b_path_components = split m#/#, $self->{path};
2599 my @a_path_components;
2601 while (@b_path_components) {
2602 $i = $paths->{'/'.join('/', @b_path_components)};
2603 last if $i && defined $i->{copyfrom_path};
2604 unshift(@a_path_components, pop(@b_path_components));
2606 return undef unless defined $i && defined $i->{copyfrom_path};
2607 my $branch_from = $i->{copyfrom_path};
2608 if (@a_path_components) {
2609 print STDERR "branch_from: $branch_from => ";
2610 $branch_from .= '/'.join('/', @a_path_components);
2611 print STDERR $branch_from, "\n";
2613 my $r = $i->{copyfrom_rev};
2614 my $repos_root = $self->ra->{repos_root};
2615 my $url = $self->ra->{url};
2616 my $new_url = $url . $branch_from;
2617 print STDERR "Found possible branch point: ",
2618 "$new_url => ", $self->full_url, ", $r\n";
2619 $branch_from =~ s#^/##;
2620 my $gs = $self->other_gs($new_url, $url,
2621 $branch_from, $r, $self->{ref_id});
2622 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2625 if (!defined $r0 || !defined $parent) {
2626 ($base, $head) = parse_revision_argument(0, $r);
2629 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2630 0, 1, sub { $base = $_[1] - 1 });
2633 if (defined $base && $base <= $r) {
2634 $gs->fetch($base, $r);
2636 ($r0, $parent) = $gs->find_rev_before($r, 1);
2638 if (defined $r0 && defined $parent) {
2639 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2641 if ($self->ra->can_do_switch) {
2642 $self->assert_index_clean($parent);
2643 print STDERR "Following parent with do_switch\n";
2644 # do_switch works with svn/trunk >= r22312, but that
2645 # is not included with SVN 1.4.3 (the latest version
2646 # at the moment), so we can't rely on it
2647 $self->{last_rev} = $r0;
2648 $self->{last_commit} = $parent;
2649 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2650 $gs->ra->gs_do_switch($r0, $rev, $gs,
2651 $self->full_url, $ed)
2652 or die "SVN connection failed somewhere...\n";
2653 } elsif ($self->ra->trees_match($new_url, $r0,
2654 $self->full_url, $rev)) {
2655 print STDERR "Trees match:\n",
2657 " ${\$self->full_url}\@$rev\n",
2658 "Following parent with no changes\n";
2659 $self->tmp_index_do(sub {
2660 command_noisy('read-tree', $parent);
2662 $self->{last_commit} = $parent;
2664 print STDERR "Following parent with do_update\n";
2665 $ed = SVN::Git::Fetcher->new($self);
2666 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2667 or die "SVN connection failed somewhere...\n";
2669 print STDERR "Successfully followed parent\n";
2670 return $self->make_log_entry($rev, [$parent], $ed);
2676 my ($self, $paths, $rev) = @_;
2678 my ($last_rev, @parents);
2679 if (my $lc = $self->last_commit) {
2680 # we can have a branch that was deleted, then re-added
2681 # under the same name but copied from another path, in
2682 # which case we'll have multiple parents (we don't
2683 # want to break the original ref, nor lose copypath info):
2684 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2685 push @{$log_entry->{parents}}, $lc;
2688 $ed = SVN::Git::Fetcher->new($self);
2689 $last_rev = $self->{last_rev};
2694 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2697 $ed = SVN::Git::Fetcher->new($self);
2699 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2700 die "SVN connection failed somewhere...\n";
2702 $self->make_log_entry($rev, \@parents, $ed);
2706 my ($self, $ed) = @_;
2708 my $h = $ed->{empty};
2709 foreach (sort keys %$h) {
2710 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2711 push @out, " $act: " . uri_encode($_);
2712 warn "W: $act: $_\n";
2714 foreach my $t (qw/dir_prop file_prop/) {
2715 $h = $ed->{$t} or next;
2716 foreach my $path (sort keys %$h) {
2717 my $ppath = $path eq '' ? '.' : $path;
2718 foreach my $prop (sort keys %{$h->{$path}}) {
2719 next if $SKIP_PROP{$prop};
2720 my $v = $h->{$path}->{$prop};
2721 my $t_ppath_prop = "$t: " .
2722 uri_encode($ppath) . ' ' .
2725 push @out, " +$t_ppath_prop " .
2728 push @out, " -$t_ppath_prop";
2733 foreach my $t (qw/absent_file absent_directory/) {
2734 $h = $ed->{$t} or next;
2735 foreach my $parent (sort keys %$h) {
2736 foreach my $path (sort @{$h->{$parent}}) {
2737 push @out, " $t: " .
2738 uri_encode("$parent/$path");
2739 warn "W: $t: $parent/$path ",
2740 "Insufficient permissions?\n";
2747 # parse_svn_date(DATE)
2748 # --------------------
2749 # Given a date (in UTC) from Subversion, return a string in the format
2750 # "<TZ Offset> <local date/time>" that Git will use.
2752 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2753 # is true we'll convert it to the local timezone instead.
2754 sub parse_svn_date {
2755 my $date = shift || return '+0000 1970-01-01 00:00:00';
2756 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2757 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2758 croak "Unable to parse date: $date\n";
2759 my $parsed_date; # Set next.
2761 if ($Git::SVN::_localtime) {
2762 # Translate the Subversion datetime to an epoch time.
2763 # Begin by switching ourselves to $date's timezone, UTC.
2764 my $old_env_TZ = $ENV{TZ};
2768 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2770 # Determine our local timezone (including DST) at the
2771 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2772 # value of TZ, if any, at the time we were run.
2773 if (defined $Git::SVN::Log::TZ) {
2774 $ENV{TZ} = $Git::SVN::Log::TZ;
2780 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2782 # This converts $epoch_in_UTC into our local timezone.
2783 my ($sec, $min, $hour, $mday, $mon, $year,
2784 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2786 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2787 $our_TZ, $year + 1900, $mon + 1,
2788 $mday, $hour, $min, $sec);
2790 # Reset us to the timezone in effect when we entered
2792 if (defined $old_env_TZ) {
2793 $ENV{TZ} = $old_env_TZ;
2798 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2801 return $parsed_date;
2805 my ($self, $new_url, $url,
2806 $branch_from, $r, $old_ref_id) = @_;
2807 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2809 my $ref_id = $old_ref_id;
2810 $ref_id =~ s/\@\d+$//;
2812 # just grow a tail if we're not unique enough :x
2813 $ref_id .= '-' while find_ref($ref_id);
2814 print STDERR "Initializing parent: $ref_id\n";
2815 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2816 if ($u =~ s#^\Q$url\E(/|$)##) {
2819 $repo_id = $self->{repo_id};
2821 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2826 sub call_authors_prog {
2827 my ($orig_author) = @_;
2828 my $author = `$::_authors_prog $orig_author`;
2830 die "$::_authors_prog failed with exit code $?\n"
2832 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2833 my ($name, $email) = ($1, $2);
2834 $email = undef if length $2 == 0;
2835 return [$name, $email];
2837 die "Author: $orig_author: $::_authors_prog returned "
2838 . "invalid author format: $author\n";
2844 if (!defined $author || length $author == 0) {
2845 $author = '(no author)';
2847 if (!defined $::users{$author}) {
2848 if (defined $::_authors_prog) {
2849 $::users{$author} = call_authors_prog($author);
2850 } elsif (defined $::_authors) {
2851 die "Author: $author not defined in $::_authors file\n";
2857 sub make_log_entry {
2858 my ($self, $rev, $parents, $ed) = @_;
2859 my $untracked = $self->get_untracked($ed);
2861 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2862 print $un "r$rev\n" or croak $!;
2863 print $un $_, "\n" foreach @$untracked;
2864 my %log_entry = ( parents => $parents || [], revision => $rev,
2868 my $logged = delete $self->{logged_rev_props};
2869 if (!$logged || $self->{-want_revprops}) {
2870 my $rp = $self->ra->rev_proplist($rev);
2871 foreach (sort keys %$rp) {
2873 if (/^svn:(author|date|log)$/) {
2874 $log_entry{$1} = $v;
2875 } elsif ($_ eq 'svm:headrev') {
2878 print $un " rev_prop: ", uri_encode($_), ' ',
2879 uri_encode($v), "\n";
2883 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2885 close $un or croak $!;
2887 $log_entry{date} = parse_svn_date($log_entry{date});
2888 $log_entry{log} .= "\n";
2889 my $author = $log_entry{author} = check_author($log_entry{author});
2890 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2893 my ($commit_name, $commit_email) = ($name, $email);
2894 if ($_use_log_author) {
2896 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2898 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2901 if (!defined $name_field) {
2902 if (!defined $email) {
2905 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2906 ($name, $email) = ($1, $2);
2907 } elsif ($name_field =~ /(.*)@/) {
2908 ($name, $email) = ($1, $name_field);
2910 ($name, $email) = ($name_field, $name_field);
2913 if (defined $headrev && $self->use_svm_props) {
2914 if ($self->rewrite_root) {
2915 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2918 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
2919 # we don't want "SVM: initializing mirror for junk" ...
2920 return undef if $r == 0;
2921 my $svm = $self->svm;
2922 if ($uuid ne $svm->{uuid}) {
2923 die "UUID mismatch on SVM path:\n",
2924 "expected: $svm->{uuid}\n",
2927 my $full_url = $self->full_url;
2928 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2929 die "Failed to replace '$svm->{replace}' with ",
2930 "'$svm->{source}' in $full_url\n";
2931 # throw away username for storing in records
2932 remove_username($full_url);
2933 $log_entry{metadata} = "$full_url\@$r $uuid";
2934 $log_entry{svm_revision} = $r;
2935 $email ||= "$author\@$uuid";
2936 $commit_email ||= "$author\@$uuid";
2937 } elsif ($self->use_svnsync_props) {
2938 my $full_url = $self->svnsync->{url};
2939 $full_url .= "/$self->{path}" if length $self->{path};
2940 remove_username($full_url);
2941 my $uuid = $self->svnsync->{uuid};
2942 $log_entry{metadata} = "$full_url\@$rev $uuid";
2943 $email ||= "$author\@$uuid";
2944 $commit_email ||= "$author\@$uuid";
2946 my $url = $self->metadata_url;
2947 remove_username($url);
2948 $log_entry{metadata} = "$url\@$rev " .
2949 $self->ra->get_uuid;
2950 $email ||= "$author\@" . $self->ra->get_uuid;
2951 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2953 $log_entry{name} = $name;
2954 $log_entry{email} = $email;
2955 $log_entry{commit_name} = $commit_name;
2956 $log_entry{commit_email} = $commit_email;
2961 my ($self, $min_rev, $max_rev, @parents) = @_;
2962 my ($last_rev, $last_commit) = $self->last_rev_commit;
2963 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2964 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2968 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2969 $self->{inject_parents} = { $rev => $tree };
2970 $self->fetch(undef, undef);
2974 my ($self, $tree) = (shift, shift);
2975 my $log_entry = ::get_commit_entry($tree);
2976 unless ($self->{last_rev}) {
2977 ::fatal("Must have an existing revision to commit");
2979 my %ed_opts = ( r => $self->{last_rev},
2980 log => $log_entry->{log},
2982 tree_a => $self->{last_commit},
2985 $self->set_tree_cb($log_entry, $tree, @_) },
2986 svn_path => $self->{path} );
2987 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2988 print "No changes\nr$self->{last_rev} = $tree\n";
2992 sub rebuild_from_rev_db {
2993 my ($self, $path) = @_;
2995 open my $fh, '<', $path or croak "open: $!";
2996 binmode $fh or croak "binmode: $!";
2998 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3001 next if $_ eq ('0' x 40);
3002 $self->rev_map_set($r, $_);
3005 close $fh or croak "close: $!";
3006 unlink $path or croak "unlink: $!";
3011 my $map_path = $self->map_path;
3012 my $partial = (-e $map_path && ! -z $map_path);
3013 return unless ::verify_ref($self->refname.'^0');
3014 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3015 my $rev_db = $self->rev_db_path;
3016 $self->rebuild_from_rev_db($rev_db);
3017 if ($self->use_svm_props) {
3018 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3019 $self->rebuild_from_rev_db($svm_rev_db);
3021 $self->unlink_rev_db_symlink;
3024 print "Rebuilding $map_path ...\n" if (!$partial);
3025 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3028 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3029 ($head ? "$head.." : "") . $self->refname,
3031 my $metadata_url = $self->metadata_url;
3032 remove_username($metadata_url);
3033 my $svn_uuid = $self->ra_uuid;
3036 if ( m{^commit ($::sha1)$} ) {
3040 next unless s{^\s*(git-svn-id:)}{$1};
3041 my ($url, $rev, $uuid) = ::extract_metadata($_);
3042 remove_username($url);
3044 # ignore merges (from set-tree)
3045 next if (!defined $rev || !$uuid);
3047 # if we merged or otherwise started elsewhere, this is
3048 # how we break out of it
3049 if (($uuid ne $svn_uuid) ||
3050 ($metadata_url && $url && ($url ne $metadata_url))) {
3053 if ($partial && $head) {
3054 print "Partial-rebuilding $map_path ...\n";
3055 print "Currently at $base_rev = $head\n";
3059 $self->rev_map_set($rev, $c);
3060 print "r$rev = $c\n";
3062 command_close_pipe($log, $ctx);
3063 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3064 my $rev_db_path = $self->rev_db_path;
3065 if (-f $self->rev_db_path) {
3066 unlink $self->rev_db_path or croak "unlink: $!";
3068 $self->unlink_rev_db_symlink;
3072 # Tie::File seems to be prone to offset errors if revisions get sparse,
3073 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3074 # one of my favorite modules is out :< Next up would be one of the DBM
3075 # modules, but I'm not sure which is most portable...
3077 # This is the replacement for the rev_db format, which was too big
3078 # and inefficient for large repositories with a lot of sparse history
3081 # The format is this:
3082 # - 24 bytes for every record,
3083 # * 4 bytes for the integer representing an SVN revision number
3084 # * 20 bytes representing the sha1 of a git commit
3085 # - No empty padding records like the old format
3086 # (except the last record, which can be overwritten)
3087 # - new records are written append-only since SVN revision numbers
3088 # increase monotonically
3089 # - lookups on SVN revision number are done via a binary search
3090 # - Piping the file to xxd -c24 is a good way of dumping it for
3091 # viewing or editing (piped back through xxd -r), should the need
3093 # - The last record can be padding revision with an all-zero sha1
3094 # This is used to optimize fetch performance when using multiple
3095 # "fetch" directives in .git/config
3097 # These files are disposable unless noMetadata or useSvmProps is set
3100 my ($fh, $rev, $commit) = @_;
3102 binmode $fh or croak "binmode: $!";
3103 my $size = (stat($fh))[7];
3104 ($size % 24) == 0 or croak "inconsistent size: $size";
3108 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3109 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3110 $read == 24 or croak "read only $read bytes (!= 24)";
3111 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3112 if ($last_commit eq ('0' x40)) {
3114 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3115 $read = sysread($fh, $buf, 24) or
3118 croak "read only $read bytes (!= 24)";
3119 ($last_rev, $last_commit) =
3120 unpack(rev_map_fmt, $buf);
3121 if ($last_commit eq ('0' x40)) {
3122 croak "inconsistent .rev_map\n";
3125 if ($last_rev >= $rev) {
3126 croak "last_rev is higher!: $last_rev >= $rev";
3131 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3132 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3136 sub _rev_map_reset {
3137 my ($fh, $rev, $commit) = @_;
3138 my $c = _rev_map_get($fh, $rev);
3139 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3140 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3141 truncate $fh, $offset or croak "truncate: $!";
3147 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3148 mkpath([$dir]) unless -d $dir;
3149 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3150 close $fh or die "Couldn't close (create) $path: $!\n";
3155 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3156 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3157 my $db = $self->map_path($uuid);
3158 my $db_lock = "$db.lock";
3162 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3163 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3167 $LOCKFILES{$db_lock} = 1;
3169 # both of these options make our .rev_db file very, very important
3170 # and we can't afford to lose it because rebuild() won't work
3171 if ($self->use_svm_props || $self->no_metadata) {
3173 copy($db, $db_lock) or die "rev_map_set(@_): ",
3175 "$db => $db_lock ($!)\n";
3177 rename $db, $db_lock or die "rev_map_set(@_): ",
3178 "Failed to rename: ",
3179 "$db => $db_lock ($!)\n";
3182 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3183 or croak "Couldn't open $db_lock: $!\n";
3184 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3185 _rev_map_set($fh, $rev, $commit);
3187 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3188 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3190 close $fh or croak $!;
3194 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3195 command_noisy('update-ref', '-m', "r$rev$note",
3196 $self->refname, $commit);
3198 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3199 "$db_lock => $db ($!)\n";
3200 delete $LOCKFILES{$db_lock};
3202 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3203 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3204 kill $sig, $$ if defined $sig;
3208 # If want_commit, this will return an array of (rev, commit) where
3209 # commit _must_ be a valid commit in the archive.
3210 # Otherwise, it'll return the max revision (whether or not the
3211 # commit is valid or just a 0x40 placeholder).
3213 my ($self, $want_commit) = @_;
3215 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3216 $want_commit ? ($r, $c) : $r;
3219 sub rev_map_max_norebuild {
3220 my ($self, $want_commit) = @_;
3221 my $map_path = $self->map_path;
3222 stat $map_path or return $want_commit ? (0, undef) : 0;
3223 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3224 binmode $fh or croak "binmode: $!";
3225 my $size = (stat($fh))[7];
3226 ($size % 24) == 0 or croak "inconsistent size: $size";
3229 close $fh or croak "close: $!";
3230 return $want_commit ? (0, undef) : 0;
3233 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3234 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3235 my ($r, $c) = unpack(rev_map_fmt, $buf);
3236 if ($want_commit && $c eq ('0' x40)) {
3238 return $want_commit ? (0, undef) : 0;
3240 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3241 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3242 ($r, $c) = unpack(rev_map_fmt, $buf);
3243 if ($c eq ('0'x40)) {
3244 croak "Penultimate record is all-zeroes in $map_path";
3247 close $fh or croak "close: $!";
3248 $want_commit ? ($r, $c) : $r;
3252 my ($self, $rev, $uuid) = @_;
3253 my $map_path = $self->map_path($uuid);
3254 return undef unless -e $map_path;
3256 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3257 my $c = _rev_map_get($fh, $rev);
3258 close($fh) or croak "close: $!";
3263 my ($fh, $rev) = @_;
3265 binmode $fh or croak "binmode: $!";
3266 my $size = (stat($fh))[7];
3267 ($size % 24) == 0 or croak "inconsistent size: $size";
3273 my ($l, $u) = (0, $size - 24);
3277 my $i = int(($l/24 + $u/24) / 2) * 24;
3278 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3279 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3280 my ($r, $c) = unpack(rev_map_fmt, $buf);
3284 } elsif ($r > $rev) {
3286 } else { # $r == $rev
3287 return $c eq ('0' x 40) ? undef : $c;
3293 # Finds the first svn revision that exists on (if $eq_ok is true) or
3294 # before $rev for the current branch. It will not search any lower
3295 # than $min_rev. Returns the git commit hash and svn revision number
3296 # if found, else (undef, undef).
3297 sub find_rev_before {
3298 my ($self, $rev, $eq_ok, $min_rev) = @_;
3299 --$rev unless $eq_ok;
3301 my $max_rev = $self->rev_map_max;
3302 $rev = $max_rev if ($rev > $max_rev);
3303 while ($rev >= $min_rev) {
3304 if (my $c = $self->rev_map_get($rev)) {
3309 return (undef, undef);
3312 # Finds the first svn revision that exists on (if $eq_ok is true) or
3313 # after $rev for the current branch. It will not search any higher
3314 # than $max_rev. Returns the git commit hash and svn revision number
3315 # if found, else (undef, undef).
3316 sub find_rev_after {
3317 my ($self, $rev, $eq_ok, $max_rev) = @_;
3318 ++$rev unless $eq_ok;
3319 $max_rev ||= $self->rev_map_max;
3320 while ($rev <= $max_rev) {
3321 if (my $c = $self->rev_map_get($rev)) {
3326 return (undef, undef);
3330 my ($class, $repo_id, $ref_id, $path) = @_;
3331 unless (defined $repo_id && length $repo_id) {
3332 $repo_id = $Git::SVN::default_repo_id;
3334 unless (defined $ref_id && length $ref_id) {
3335 $_prefix = '' unless defined($_prefix);
3337 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3340 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3342 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3343 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3344 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3345 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3346 if (-d $old_dir && ! -d $dir) {
3351 $_[3] = $path = '' unless (defined $path);
3354 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3355 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3356 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3359 # for read-only access of old .rev_db formats
3360 sub unlink_rev_db_symlink {
3362 my $link = $self->rev_db_path;
3363 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3365 unlink $link or croak "unlink: $link failed!";
3370 my ($self, $uuid) = @_;
3371 my $db_path = $self->map_path($uuid);
3372 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3373 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3377 # the new replacement for .rev_db
3379 my ($self, $uuid) = @_;
3380 $uuid ||= $self->ra_uuid;
3381 "$self->{map_root}.$uuid";
3386 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3390 sub remove_username {
3391 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3394 package Git::SVN::Prompt;
3398 use vars qw/$_no_auth_cache $_username/;
3401 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3402 $may_save = undef if $_no_auth_cache;
3403 $default_username = $_username if defined $_username;
3404 if (defined $default_username && length $default_username) {
3405 if (defined $realm && length $realm) {
3406 print STDERR "Authentication realm: $realm\n";
3409 $cred->username($default_username);
3411 username($cred, $realm, $may_save, $pool);
3413 $cred->password(_read_password("Password for '" .
3414 $cred->username . "': ", $realm));
3415 $cred->may_save($may_save);
3416 $SVN::_Core::SVN_NO_ERROR;
3419 sub ssl_server_trust {
3420 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3421 $may_save = undef if $_no_auth_cache;
3422 print STDERR "Error validating server certificate for '$realm':\n";
3425 # All variables SVN::Auth::SSL::* are used only once,
3426 # so we're shutting up Perl warnings about this.
3427 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3428 print STDERR " - The certificate is not issued ",
3429 "by a trusted authority. Use the\n",
3430 " fingerprint to validate ",
3431 "the certificate manually!\n";
3433 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3434 print STDERR " - The certificate hostname ",
3435 "does not match.\n";
3437 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3438 print STDERR " - The certificate is not yet valid.\n";
3440 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3441 print STDERR " - The certificate has expired.\n";
3443 if ($failures & $SVN::Auth::SSL::OTHER) {
3444 print STDERR " - The certificate has ",
3445 "an unknown error.\n";
3447 } # no warnings 'once'
3449 "Certificate information:\n".
3450 " - Hostname: %s\n".
3451 " - Valid: from %s until %s\n".
3453 " - Fingerprint: %s\n",
3454 map $cert_info->$_, qw(hostname valid_from valid_until
3455 issuer_dname fingerprint);
3458 print STDERR $may_save ?
3459 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3460 "(R)eject or accept (t)emporarily? ";
3462 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3463 if ($choice =~ /^t$/i) {
3464 $cred->may_save(undef);
3465 } elsif ($choice =~ /^r$/i) {
3467 } elsif ($may_save && $choice =~ /^p$/i) {
3468 $cred->may_save($may_save);
3472 $cred->accepted_failures($failures);
3473 $SVN::_Core::SVN_NO_ERROR;
3476 sub ssl_client_cert {
3477 my ($cred, $realm, $may_save, $pool) = @_;
3478 $may_save = undef if $_no_auth_cache;
3479 print STDERR "Client certificate filename: ";
3481 chomp(my $filename = <STDIN>);
3482 $cred->cert_file($filename);
3483 $cred->may_save($may_save);
3484 $SVN::_Core::SVN_NO_ERROR;
3487 sub ssl_client_cert_pw {
3488 my ($cred, $realm, $may_save, $pool) = @_;
3489 $may_save = undef if $_no_auth_cache;
3490 $cred->password(_read_password("Password: ", $realm));
3491 $cred->may_save($may_save);
3492 $SVN::_Core::SVN_NO_ERROR;
3496 my ($cred, $realm, $may_save, $pool) = @_;
3497 $may_save = undef if $_no_auth_cache;
3498 if (defined $realm && length $realm) {
3499 print STDERR "Authentication realm: $realm\n";
3502 if (defined $_username) {
3503 $username = $_username;
3505 print STDERR "Username: ";
3507 chomp($username = <STDIN>);
3509 $cred->username($username);
3510 $cred->may_save($may_save);
3511 $SVN::_Core::SVN_NO_ERROR;
3514 sub _read_password {
3515 my ($prompt, $realm) = @_;
3516 print STDERR $prompt;
3518 require Term::ReadKey;
3519 Term::ReadKey::ReadMode('noecho');
3521 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3522 last if $key =~ /[\012\015]/; # \n\r
3525 Term::ReadKey::ReadMode('restore');
3531 package SVN::Git::Fetcher;
3536 use File::Temp qw/tempfile/;
3538 use vars qw/$_ignore_regex/;
3540 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3542 my ($class, $git_svn, $switch_path) = @_;
3543 my $self = SVN::Delta::Editor->new;
3544 bless $self, $class;
3545 if (exists $git_svn->{last_commit}) {
3546 $self->{c} = $git_svn->{last_commit};
3547 $self->{empty_symlinks} =
3548 _mark_empty_symlinks($git_svn, $switch_path);
3550 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3551 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3552 $self->{empty} = {};
3553 $self->{dir_prop} = {};
3554 $self->{file_prop} = {};
3555 $self->{absent_dir} = {};
3556 $self->{absent_file} = {};
3557 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3561 # this uses the Ra object, so it must be called before do_{switch,update},
3562 # not inside them (when the Git::SVN::Fetcher object is passed) to
3563 # do_{switch,update}
3564 sub _mark_empty_symlinks {
3565 my ($git_svn, $switch_path) = @_;
3566 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3567 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3570 my ($rev, $cmt) = $git_svn->last_rev_commit;
3571 return {} unless ($rev && $cmt);
3573 # allow the warning to be printed for each revision we fetch to
3574 # ensure the user sees it. The user can also disable the workaround
3575 # on the repository even while git svn is running and the next
3576 # revision fetched will skip this expensive function.
3577 my $printed_warning;
3578 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3579 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3581 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3582 $pfx .= '/' if length($pfx);
3585 s/\A100644 blob $empty_blob\t//o or next;
3586 unless ($printed_warning) {
3587 print STDERR "Scanning for empty symlinks, ",
3588 "this may take a while if you have ",
3589 "many empty files\n",
3590 "You may disable this with `",
3591 "git config svn.brokenSymlinkWorkaround ",
3593 "This may be done in a different ",
3594 "terminal without restarting ",
3596 $printed_warning = 1;
3599 my (undef, $props) =
3600 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3601 if ($props->{'svn:special'}) {
3605 command_close_pipe($ls, $ctx);
3609 # returns true if a given path is inside a ".git" directory
3611 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3614 # return value: 0 -- don't ignore, 1 -- ignore
3615 sub is_path_ignored {
3616 my ($self, $path) = @_;
3617 return 1 if in_dot_git($path);
3618 return 1 if defined($self->{ignore_regex}) &&
3619 $path =~ m!$self->{ignore_regex}!;
3620 return 0 unless defined($_ignore_regex);
3621 return 1 if $path =~ m!$_ignore_regex!o;
3625 sub set_path_strip {
3626 my ($self, $path) = @_;
3627 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3634 sub open_directory {
3635 my ($self, $path, $pb, $rev) = @_;
3640 my ($self, $path) = @_;
3641 if ($self->{path_strip}) {
3642 $path =~ s!$self->{path_strip}!! or
3643 die "Failed to strip path '$path' ($self->{path_strip})\n";
3649 my ($self, $path, $rev, $pb) = @_;
3650 return undef if $self->is_path_ignored($path);
3652 my $gpath = $self->git_path($path);
3653 return undef if ($gpath eq '');
3655 # remove entire directories.
3656 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3657 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3659 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3665 my $rmpath = "$gpath/$_";
3666 $self->{gii}->remove($rmpath);
3667 print "\tD\t$rmpath\n" unless $::_q;
3669 print "\tD\t$gpath/\n" unless $::_q;
3670 command_close_pipe($ls, $ctx);
3671 $self->{empty}->{$path} = 0
3673 $self->{gii}->remove($gpath);
3674 print "\tD\t$gpath\n" unless $::_q;
3680 my ($self, $path, $pb, $rev) = @_;
3683 goto out if $self->is_path_ignored($path);
3685 my $gpath = $self->git_path($path);
3686 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3687 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3688 unless (defined $mode && defined $blob) {
3689 die "$path was not found in commit $self->{c} (r$rev)\n";
3691 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3695 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3696 pool => SVN::Pool->new, action => 'M' };
3700 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3703 if (!$self->is_path_ignored($path)) {
3704 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3705 delete $self->{empty}->{$dir};
3708 { path => $path, mode_a => $mode, mode_b => $mode,
3709 pool => SVN::Pool->new, action => 'A' };
3713 my ($self, $path, $cp_path, $cp_rev) = @_;
3714 goto out if $self->is_path_ignored($path);
3715 my $gpath = $self->git_path($path);
3717 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3723 $self->{gii}->remove($_);
3724 print "\tD\t$_\n" unless $::_q;
3726 command_close_pipe($ls, $ctx);
3727 $self->{empty}->{$path} = 0;
3729 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3730 delete $self->{empty}->{$dir};
3731 $self->{empty}->{$path} = 1;
3736 sub change_dir_prop {
3737 my ($self, $db, $prop, $value) = @_;
3738 return undef if $self->is_path_ignored($db->{path});
3739 $self->{dir_prop}->{$db->{path}} ||= {};
3740 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3744 sub absent_directory {
3745 my ($self, $path, $pb) = @_;
3746 return undef if $self->is_path_ignored($path);
3747 $self->{absent_dir}->{$pb->{path}} ||= [];
3748 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3753 my ($self, $path, $pb) = @_;
3754 return undef if $self->is_path_ignored($path);
3755 $self->{absent_file}->{$pb->{path}} ||= [];
3756 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3760 sub change_file_prop {
3761 my ($self, $fb, $prop, $value) = @_;
3762 return undef if $self->is_path_ignored($fb->{path});
3763 if ($prop eq 'svn:executable') {
3764 if ($fb->{mode_b} != 120000) {
3765 $fb->{mode_b} = defined $value ? 100755 : 100644;
3767 } elsif ($prop eq 'svn:special') {
3768 $fb->{mode_b} = defined $value ? 120000 : 100644;
3770 $self->{file_prop}->{$fb->{path}} ||= {};
3771 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3776 sub apply_textdelta {
3777 my ($self, $fb, $exp) = @_;
3778 return undef if $self->is_path_ignored($fb->{path});
3779 my $fh = $::_repository->temp_acquire('svn_delta');
3780 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3781 # (but $base does not,) so dup() it for reading in close_file
3782 open my $dup, '<&', $fh or croak $!;
3783 my $base = $::_repository->temp_acquire('git_blob');
3786 my ($base_is_link, $size);
3788 if ($fb->{mode_a} eq '120000' &&
3789 ! $self->{empty_symlinks}->{$fb->{path}}) {
3790 print $base 'link ' or die "print $!\n";
3794 $size = $::_repository->cat_blob($fb->{blob}, $base);
3795 die "Failed to read object $fb->{blob}" if ($size < 0);
3798 seek $base, 0, 0 or croak $!;
3799 my $got = ::md5sum($base);
3801 my $err = "Checksum mismatch: ".
3802 "$fb->{path} $fb->{blob}\n" .
3803 "expected: $exp\n" .
3805 if ($base_is_link) {
3807 "Retrying... (possibly ",
3808 "a bad symlink from SVN)\n";
3809 $::_repository->temp_reset($base);
3817 seek $base, 0, 0 or croak $!;
3819 $fb->{base} = $base;
3820 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3824 my ($self, $fb, $exp) = @_;
3825 return undef if $self->is_path_ignored($fb->{path});
3828 my $path = $self->git_path($fb->{path});
3829 if (my $fh = $fb->{fh}) {
3831 seek($fh, 0, 0) or croak $!;
3832 my $got = ::md5sum($fh);
3834 die "Checksum mismatch: $path\n",
3835 "expected: $exp\n got: $got\n";
3838 if ($fb->{mode_b} == 120000) {
3839 sysseek($fh, 0, 0) or croak $!;
3840 my $rd = sysread($fh, my $buf, 5);
3843 croak "sysread: $!\n";
3844 } elsif ($rd == 0) {
3845 warn "$path has mode 120000",
3846 " but it points to nothing\n",
3847 "converting to an empty file with mode",
3849 $fb->{mode_b} = '100644';
3850 } elsif ($buf ne 'link ') {
3851 warn "$path has mode 120000",
3852 " but is not a link\n";
3854 my $tmp_fh = $::_repository->temp_acquire(
3857 while ($res = sysread($fh, my $str, 1024)) {
3858 my $out = syswrite($tmp_fh, $str, $res);
3859 defined($out) && $out == $res
3861 Git::temp_path($tmp_fh),
3864 defined $res or croak $!;
3866 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3867 Git::temp_release($tmp_fh, 1);
3871 $hash = $::_repository->hash_and_insert_object(
3872 Git::temp_path($fh));
3873 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3875 Git::temp_release($fb->{base}, 1);
3876 Git::temp_release($fh, 1);
3878 $hash = $fb->{blob} or die "no blob information\n";
3881 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3882 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3888 $self->{nr} = $self->{gii}->{nr};
3889 delete $self->{gii};
3890 $self->SUPER::abort_edit(@_);
3895 $self->{git_commit_ok} = 1;
3896 $self->{nr} = $self->{gii}->{nr};
3897 delete $self->{gii};
3898 $self->SUPER::close_edit(@_);
3901 package SVN::Git::Editor;
3902 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3909 my ($class, $opts) = @_;
3910 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3911 die "$_ required!\n" unless (defined $opts->{$_});
3914 my $pool = SVN::Pool->new;
3915 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3916 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3919 # $opts->{ra} functions should not be used after this:
3920 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3921 $opts->{editor_cb}, $pool);
3922 my $self = SVN::Delta::Editor->new(@ce, $pool);
3923 bless $self, $class;
3924 foreach (qw/svn_path r tree_a tree_b/) {
3925 $self->{$_} = $opts->{$_};
3927 $self->{url} = $opts->{ra}->{url};
3928 $self->{mods} = $mods;
3929 $self->{types} = $types;
3930 $self->{pool} = $pool;
3931 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3933 $self->{path_prefix} = length $self->{svn_path} ?
3934 "$self->{svn_path}/" : '';
3935 $self->{config} = $opts->{config};
3940 my ($tree_a, $tree_b) = @_;
3941 my @diff_tree = qw(diff-tree -z -r);
3942 if ($_cp_similarity) {
3943 push @diff_tree, "-C$_cp_similarity";
3945 push @diff_tree, '-C';
3947 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3948 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3949 push @diff_tree, $tree_a, $tree_b;
3950 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3954 while (<$diff_fh>) {
3955 chomp $_; # this gets rid of the trailing "\0"
3956 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3957 ($::sha1)\s($::sha1)\s
3958 ([MTCRAD])\d*$/xo) {
3959 push @mods, { mode_a => $1, mode_b => $2,
3960 sha1_a => $3, sha1_b => $4,
3962 if ($5 =~ /^(?:C|R)$/) {
3967 } elsif ($state eq 'file_a') {
3968 my $x = $mods[$#mods] or croak "Empty array\n";
3969 if ($x->{chg} !~ /^(?:C|R)$/) {
3970 croak "Error parsing $_, $x->{chg}\n";
3974 } elsif ($state eq 'file_b') {
3975 my $x = $mods[$#mods] or croak "Empty array\n";
3976 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3977 croak "Error parsing $_, $x->{chg}\n";
3979 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3980 croak "Error parsing $_, $x->{chg}\n";
3985 croak "Error parsing $_\n";
3988 command_close_pipe($diff_fh, $ctx);
3992 sub check_diff_paths {
3993 my ($ra, $pfx, $rev, $mods) = @_;
3995 $pfx .= '/' if length $pfx;
3997 sub type_diff_paths {
3998 my ($ra, $types, $path, $rev) = @_;
3999 my @p = split m#/+#, $path;
4001 unless (defined $types->{$c}) {
4002 $types->{$c} = $ra->check_path($c, $rev);
4005 $c .= '/' . shift @p;
4006 next if defined $types->{$c};
4007 $types->{$c} = $ra->check_path($c, $rev);
4011 foreach my $m (@$mods) {
4012 foreach my $f (qw/file_a file_b/) {
4013 next unless defined $m->{$f};
4014 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4015 if (length $pfx.$dir && ! defined $types{$dir}) {
4016 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4024 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4028 my ($self, $path) = @_;
4029 $self->{path_prefix}.(defined $path ? $path : '');
4033 my ($self, $path) = @_;
4034 if ($self->{url} =~ m#^https?://#) {
4035 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4037 $self->{url} . '/' . $self->repo_path($path);
4042 my $rm = $self->{rm};
4043 delete $rm->{''}; # we never delete the url we're tracking
4046 foreach (keys %$rm) {
4047 my @d = split m#/#, $_;
4051 $c .= '/' . shift @d;
4055 delete $rm->{$self->{svn_path}};
4056 delete $rm->{''}; # we never delete the url we're tracking
4059 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4064 my @dn = split m#/#, $_;
4066 delete $rm->{join '/', @dn};
4073 command_close_pipe($fh, $ctx);
4075 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4076 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4077 $self->close_directory($bat->{$d}, $p);
4078 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4079 print "\tD+\t$d/\n" unless $::_q;
4080 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4085 sub open_or_add_dir {
4086 my ($self, $full_path, $baton) = @_;
4087 my $t = $self->{types}->{$full_path};
4089 die "$full_path not known in r$self->{r} or we have a bug!\n";
4093 # SVN::Node::none and SVN::Node::file are used only once,
4094 # so we're shutting up Perl's warnings about them.
4095 if ($t == $SVN::Node::none) {
4096 return $self->add_directory($full_path, $baton,
4097 undef, -1, $self->{pool});
4098 } elsif ($t == $SVN::Node::dir) {
4099 return $self->open_directory($full_path, $baton,
4100 $self->{r}, $self->{pool});
4101 } # no warnings 'once'
4102 print STDERR "$full_path already exists in repository at ",
4103 "r$self->{r} and it is not a directory (",
4104 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4105 } # no warnings 'once'
4110 my ($self, $path) = @_;
4111 my $bat = $self->{bat};
4112 my $repo_path = $self->repo_path($path);
4113 return $bat->{''} unless (length $repo_path);
4114 my @p = split m#/+#, $repo_path;
4116 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4119 $c .= '/' . shift @p;
4120 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4125 # Subroutine to convert a globbing pattern to a regular expression.
4126 # From perl cookbook.
4128 my $globstr = shift;
4129 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4130 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4131 return '^' . $globstr . '$';
4134 sub check_autoprop {
4135 my ($self, $pattern, $properties, $file, $fbat) = @_;
4136 # Convert the globbing pattern to a regular expression.
4137 my $regex = glob2pat($pattern);
4138 # Check if the pattern matches the file name.
4139 if($file =~ m/($regex)/) {
4140 # Parse the list of properties to set.
4141 my @props = split(/;/, $properties);
4142 foreach my $prop (@props) {
4143 # Parse 'name=value' syntax and set the property.
4144 if ($prop =~ /([^=]+)=(.*)/) {
4145 my ($n,$v) = ($1,$2);
4149 $self->change_file_prop($fbat, $n, $v);
4155 sub apply_autoprops {
4156 my ($self, $file, $fbat) = @_;
4157 my $conf_t = ${$self->{config}}{'config'};
4159 # Check [miscellany]/enable-auto-props in svn configuration.
4160 if (SVN::_Core::svn_config_get_bool(
4162 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4163 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4165 # Auto-props are enabled. Enumerate them to look for matches.
4166 my $callback = sub {
4167 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4169 SVN::_Core::svn_config_enumerate(
4171 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4177 my ($self, $m) = @_;
4178 my ($dir, $file) = split_path($m->{file_b});
4179 my $pbat = $self->ensure_path($dir);
4180 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4182 print "\tA\t$m->{file_b}\n" unless $::_q;
4183 $self->apply_autoprops($file, $fbat);
4184 $self->chg_file($fbat, $m);
4185 $self->close_file($fbat,undef,$self->{pool});
4189 my ($self, $m) = @_;
4190 my ($dir, $file) = split_path($m->{file_b});
4191 my $pbat = $self->ensure_path($dir);
4192 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4193 $self->url_path($m->{file_a}), $self->{r});
4194 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4195 $self->chg_file($fbat, $m);
4196 $self->close_file($fbat,undef,$self->{pool});
4200 my ($self, $path, $pbat) = @_;
4201 my $rpath = $self->repo_path($path);
4202 my ($dir, $file) = split_path($rpath);
4203 $self->{rm}->{$dir} = 1;
4204 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4208 my ($self, $m) = @_;
4209 my ($dir, $file) = split_path($m->{file_b});
4210 my $pbat = $self->ensure_path($dir);
4211 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4212 $self->url_path($m->{file_a}), $self->{r});
4213 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4214 $self->apply_autoprops($file, $fbat);
4215 $self->chg_file($fbat, $m);
4216 $self->close_file($fbat,undef,$self->{pool});
4218 ($dir, $file) = split_path($m->{file_a});
4219 $pbat = $self->ensure_path($dir);
4220 $self->delete_entry($m->{file_a}, $pbat);
4224 my ($self, $m) = @_;
4225 my ($dir, $file) = split_path($m->{file_b});
4226 my $pbat = $self->ensure_path($dir);
4227 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4228 $pbat,$self->{r},$self->{pool});
4229 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4230 $self->chg_file($fbat, $m);
4231 $self->close_file($fbat,undef,$self->{pool});
4234 sub T { shift->M(@_) }
4236 sub change_file_prop {
4237 my ($self, $fbat, $pname, $pval) = @_;
4238 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4241 sub _chg_file_get_blob ($$$$) {
4242 my ($self, $fbat, $m, $which) = @_;
4243 my $fh = $::_repository->temp_acquire("git_blob_$which");
4244 if ($m->{"mode_$which"} =~ /^120/) {
4245 print $fh 'link ' or croak $!;
4246 $self->change_file_prop($fbat,'svn:special','*');
4247 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4248 $self->change_file_prop($fbat,'svn:special',undef);
4250 my $blob = $m->{"sha1_$which"};
4251 return ($fh,) if ($blob =~ /^0{40}$/);
4252 my $size = $::_repository->cat_blob($blob, $fh);
4253 croak "Failed to read object $blob" if ($size < 0);
4254 $fh->flush == 0 or croak $!;
4255 seek $fh, 0, 0 or croak $!;
4257 my $exp = ::md5sum($fh);
4258 seek $fh, 0, 0 or croak $!;
4263 my ($self, $fbat, $m) = @_;
4264 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4265 $self->change_file_prop($fbat,'svn:executable','*');
4266 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4267 $self->change_file_prop($fbat,'svn:executable',undef);
4269 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4270 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4271 my $pool = SVN::Pool->new;
4272 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4274 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4275 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4277 die "Unexpected result from send_txstream: $res\n",
4278 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4281 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4282 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4283 if ($got ne $exp_b);
4285 Git::temp_release($fh_b, 1);
4286 Git::temp_release($fh_a, 1);
4291 my ($self, $m) = @_;
4292 my ($dir, $file) = split_path($m->{file_b});
4293 my $pbat = $self->ensure_path($dir);
4294 print "\tD\t$m->{file_b}\n" unless $::_q;
4295 $self->delete_entry($m->{file_b}, $pbat);
4300 my ($p,$bat) = ($self->{pool}, $self->{bat});
4301 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4303 $self->close_directory($bat->{$_}, $p);
4305 $self->close_directory($bat->{''}, $p);
4306 $self->SUPER::close_edit($p);
4312 $self->SUPER::abort_edit($self->{pool});
4317 $self->SUPER::DESTROY(@_);
4318 $self->{pool}->clear;
4321 # this drives the editor
4324 my $mods = $self->{mods};
4325 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4326 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4328 if (defined $o{$f}) {
4331 fatal("Invalid change type: $f");
4334 $self->rmdirs if $_rmdir;
4340 return scalar @$mods;
4343 package Git::SVN::Ra;
4344 use vars qw/@ISA $config_dir $_log_window_size/;
4347 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4350 # enforce temporary pool usage for some simple functions
4352 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4354 my $SUPER = "SUPER::$f";
4357 my $pool = SVN::Pool->new;
4358 my @ret = $self->$SUPER(@_,$pool);
4360 wantarray ? @ret : $ret[0];
4365 sub _auth_providers () {
4367 SVN::Client::get_simple_provider(),
4368 SVN::Client::get_ssl_server_trust_file_provider(),
4369 SVN::Client::get_simple_prompt_provider(
4370 \&Git::SVN::Prompt::simple, 2),
4371 SVN::Client::get_ssl_client_cert_file_provider(),
4372 SVN::Client::get_ssl_client_cert_prompt_provider(
4373 \&Git::SVN::Prompt::ssl_client_cert, 2),
4374 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4375 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4376 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4377 SVN::Client::get_username_provider(),
4378 SVN::Client::get_ssl_server_trust_prompt_provider(
4379 \&Git::SVN::Prompt::ssl_server_trust),
4380 SVN::Client::get_username_prompt_provider(
4381 \&Git::SVN::Prompt::username, 2)
4385 sub escape_uri_only {
4388 foreach (split m{/}, $uri) {
4389 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4397 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4398 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4399 $url = "$scheme://$domain$uri";
4405 my ($class, $url) = @_;
4407 return $RA if ($RA && $RA->{url} eq $url);
4409 SVN::_Core::svn_config_ensure($config_dir, undef);
4410 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4411 my $config = SVN::Core::config_get_config($config_dir);
4413 my $dont_store_passwords = 1;
4414 my $conf_t = ${$config}{'config'};
4417 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4418 # produces warnings that variables are used only once.
4419 # I had not found the better way to shut them up, so
4420 # the warnings of type 'once' are disabled in this block.
4421 if (SVN::_Core::svn_config_get_bool($conf_t,
4422 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4423 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4425 SVN::_Core::svn_auth_set_parameter($baton,
4426 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4427 bless (\$dont_store_passwords, "_p_void"));
4429 if (SVN::_Core::svn_config_get_bool($conf_t,
4430 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4431 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4433 $Git::SVN::Prompt::_no_auth_cache = 1;
4435 } # no warnings 'once'
4436 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4438 pool => SVN::Pool->new,
4439 auth_provider_callbacks => $callbacks);
4440 $self->{url} = $url;
4441 $self->{svn_path} = $url;
4442 $self->{repos_root} = $self->get_repos_root;
4443 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4444 $self->{cache} = { check_path => { r => 0, data => {} },
4445 get_dir => { r => 0, data => {} } };
4446 $RA = bless $self, $class;
4450 my ($self, $path, $r) = @_;
4451 my $cache = $self->{cache}->{check_path};
4452 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4453 return $cache->{data}->{$path};
4455 my $pool = SVN::Pool->new;
4456 my $t = $self->SUPER::check_path($path, $r, $pool);
4458 if ($r != $cache->{r}) {
4459 %{$cache->{data}} = ();
4462 $cache->{data}->{$path} = $t;
4466 my ($self, $dir, $r) = @_;
4467 my $cache = $self->{cache}->{get_dir};
4468 if ($r == $cache->{r}) {
4469 if (my $x = $cache->{data}->{$dir}) {
4470 return wantarray ? @$x : $x->[0];
4473 my $pool = SVN::Pool->new;
4474 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4475 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4477 if ($r != $cache->{r}) {
4478 %{$cache->{data}} = ();
4481 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4482 wantarray ? (\%dirents, $r, $props) : \%dirents;
4486 # do not call the real DESTROY since we store ourselves in $RA
4489 # get_log(paths, start, end, limit,
4490 # discover_changed_paths, strict_node_history, receiver)
4492 my ($self, @args) = @_;
4493 my $pool = SVN::Pool->new;
4495 # svn_log_changed_path_t objects passed to get_log are likely to be
4496 # overwritten even if only the refs are copied to an external variable,
4497 # so we should dup the structures in their entirety. Using an
4498 # externally passed pool (instead of our temporary and quickly cleared
4499 # pool in Git::SVN::Ra) does not help matters at all...
4500 my $receiver = pop @args;
4501 my $prefix = "/".$self->{svn_path};
4502 $prefix =~ s#/+($)##;
4503 my $prefix_regex = qr#^\Q$prefix\E#;
4505 my ($paths) = $_[0];
4506 return &$receiver(@_) unless $paths;
4508 foreach my $p (keys %$paths) {
4509 my $i = $paths->{$p};
4510 # Make path relative to our url, not repos_root
4511 $p =~ s/$prefix_regex//;
4512 my %s = map { $_ => $i->$_; }
4513 qw/copyfrom_path copyfrom_rev action/;
4514 if ($s{'copyfrom_path'}) {
4515 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4523 # the limit parameter was not supported in SVN 1.1.x, so we
4524 # drop it. Therefore, the receiver callback passed to it
4525 # is made aware of this limitation by being wrapped if
4526 # the limit passed to is being wrapped.
4527 if ($SVN::Core::VERSION le '1.2.0') {
4528 my $limit = splice(@args, 3, 1);
4530 my $receiver = pop @args;
4531 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4534 my $ret = $self->SUPER::get_log(@args, $pool);
4540 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4541 my $ctx = SVN::Client->new(auth => _auth_providers);
4542 my $out = IO::File->new_tmpfile;
4544 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4545 # $ctx->diff(), so we'll create a default one
4546 my $pool = SVN::Pool->new_default_sub;
4548 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4549 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4551 my $ret = (($out->stat)[7] == 0);
4552 close $out or croak $!;
4557 sub get_commit_editor {
4558 my ($self, $log, $cb, $pool) = @_;
4559 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4560 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4564 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4565 my $new = ($rev_a == $rev_b);
4566 my $path = $gs->{path};
4568 if ($new && -e $gs->{index}) {
4569 unlink $gs->{index} or die
4570 "Couldn't unlink index: $gs->{index}: $!\n";
4572 my $pool = SVN::Pool->new;
4573 $editor->set_path_strip($path);
4574 my (@pc) = split m#/#, $path;
4575 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4577 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4579 # Since we can't rely on svn_ra_reparent being available, we'll
4580 # just have to do some magic with set_path to make it so
4581 # we only want a partial path.
4583 my $final = join('/', @pc);
4585 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4586 $sp .= '/' if length $sp;
4589 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4591 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4593 $reporter->finish_report($pool);
4595 $editor->{git_commit_ok};
4598 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4599 # svn_ra_reparent didn't work before 1.4)
4601 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4602 my $path = $gs->{path};
4603 my $pool = SVN::Pool->new;
4605 my $full_url = $self->{url};
4606 my $old_url = $full_url;
4607 $full_url .= '/' . $path if length $path;
4608 my ($ra, $reparented);
4610 if ($old_url =~ m#^svn(\+ssh)?://# ||
4611 ($full_url =~ m#^https?://# &&
4612 escape_url($full_url) ne $full_url)) {
4616 $ra = Git::SVN::Ra->new($full_url);
4618 } elsif ($old_url ne $full_url) {
4619 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4620 $self->{url} = $full_url;
4625 $url_b = escape_url($url_b);
4626 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4627 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4628 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4629 $reporter->finish_report($pool);
4632 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4633 $self->{url} = $old_url;
4637 $editor->{git_commit_ok};
4640 sub longest_common_path {
4641 my ($gsv, $globs) = @_;
4643 my $common_max = scalar @$gsv;
4645 foreach my $gs (@$gsv) {
4646 my @tmp = split m#/#, $gs->{path};
4649 $p .= length($p) ? "/$_" : $_;
4655 $common_max += scalar @$globs;
4656 foreach my $glob (@$globs) {
4657 my @tmp = split m#/#, $glob->{path}->{left};
4660 $p .= length($p) ? "/$_" : $_;
4666 my $longest_path = '';
4667 foreach (sort {length $b <=> length $a} keys %common) {
4668 if ($common{$_} == $common_max) {
4676 sub gs_fetch_loop_common {
4677 my ($self, $base, $head, $gsv, $globs) = @_;
4678 return if ($base > $head);
4679 my $inc = $_log_window_size;
4680 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4681 my $longest_path = longest_common_path($gsv, $globs);
4682 my $ra_url = $self->{url};
4683 my $find_trailing_edge;
4687 my $err_handler = $SVN::Error::handler;
4688 $SVN::Error::handler = sub {
4690 skip_unknown_revs($err);
4693 my ($paths, $r, $author, $date, $log) = @_;
4695 { author => $author, date => $date, log => $log } ];
4697 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4698 sub { $revs{$_[1]} = _cb(@_) });
4700 print "Checked through r$max\r";
4702 $find_trailing_edge = 1;
4704 if ($err and $find_trailing_edge) {
4705 print STDERR "Path '$longest_path' ",
4706 "was probably deleted:\n",
4707 $err->expanded_message,
4708 "\nWill attempt to follow ",
4709 "revisions r$min .. r$max ",
4710 "committed before the deletion\n";
4712 while (--$hi >= $min) {
4714 $self->get_log([$longest_path], $min, $hi,
4717 $revs{$_[1]} = _cb(@_) });
4719 print STDERR "r$min .. r$ok OK\n";
4723 $find_trailing_edge = 0;
4725 $SVN::Error::handler = $err_handler;
4727 my %exists = map { $_->{path} => $_ } @$gsv;
4728 foreach my $r (sort {$a <=> $b} keys %revs) {
4729 my ($paths, $logged) = @{$revs{$r}};
4731 foreach my $gs ($self->match_globs(\%exists, $paths,
4733 if ($gs->rev_map_max >= $r) {
4736 next unless $gs->match_paths($paths, $r);
4737 $gs->{logged_rev_props} = $logged;
4738 if (my $last_commit = $gs->last_commit) {
4739 $gs->assert_index_clean($last_commit);
4741 my $log_entry = $gs->do_fetch($paths, $r);
4743 $gs->do_git_commit($log_entry);
4745 $INDEX_FILES{$gs->{index}} = 1;
4747 foreach my $g (@$globs) {
4748 my $k = "svn-remote.$g->{remote}." .
4750 Git::SVN::tmp_config($k, $r);
4756 $self = Git::SVN::Ra->new($ra_url);
4757 $ra_invalid = undef;
4760 # pre-fill the .rev_db since it'll eventually get filled in
4761 # with '0' x40 if something new gets committed
4762 foreach my $gs (@$gsv) {
4763 next if $gs->rev_map_max >= $max;
4764 next if defined $gs->rev_map_get($max);
4765 $gs->rev_map_set($max, 0 x40);
4767 foreach my $g (@$globs) {
4768 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4769 Git::SVN::tmp_config($k, $max);
4771 last if $max >= $head;
4774 $max = $head if ($max > $head);
4779 sub get_dir_globbed {
4780 my ($self, $left, $depth, $r) = @_;
4782 my @x = eval { $self->get_dir($left, $r) };
4783 return unless scalar @x == 3;
4784 my $dirents = $x[0];
4786 foreach my $de (keys %$dirents) {
4787 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4789 my @args = ("$left/$de", $depth - 1, $r);
4790 foreach my $dir ($self->get_dir_globbed(@args)) {
4791 push @finalents, "$de/$dir";
4794 push @finalents, $de;
4801 my ($self, $exists, $paths, $globs, $r) = @_;
4804 my ($self, $exists, $g, $r) = @_;
4806 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4807 $g->{path}->{depth},
4810 foreach my $de (@dirs) {
4811 my $p = $g->{path}->full_path($de);
4812 next if $exists->{$p};
4813 next if (length $g->{path}->{right} &&
4814 ($self->check_path($p, $r) !=
4816 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4817 $g->{ref}->full_path($de), 1);
4820 foreach my $g (@$globs) {
4821 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4822 if ($path->{action} =~ /^[AR]$/) {
4823 get_dir_check($self, $exists, $g, $r);
4826 foreach (keys %$paths) {
4827 if (/$g->{path}->{left_regex}/ &&
4828 !/$g->{path}->{regex}/) {
4829 next if $paths->{$_}->{action} !~ /^[AR]$/;
4830 get_dir_check($self, $exists, $g, $r);
4832 next unless /$g->{path}->{regex}/;
4834 my $pathname = $g->{path}->full_path($p);
4835 next if $exists->{$pathname};
4836 next if ($self->check_path($pathname, $r) !=
4838 $exists->{$pathname} = Git::SVN->init(
4839 $self->{url}, $pathname, undef,
4840 $g->{ref}->full_path($p), 1);
4843 foreach (split m#/#, $g->{path}->{left}) {
4845 next unless ($paths->{$c} &&
4846 ($paths->{$c}->{action} =~ /^[AR]$/));
4847 get_dir_check($self, $exists, $g, $r);
4855 return $self->{url} if ($self->{url} eq $self->{repos_root});
4856 my $url = $self->{repos_root};
4857 my @components = split(m!/!, $self->{svn_path});
4860 $url .= "/$c" if length $c;
4862 my $ra = (ref $self)->new($url);
4863 my $latest = $ra->get_latest_revnum;
4864 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
4866 } while ($@ && ($c = shift @components));
4872 unless (defined $can_do_switch) {
4873 my $pool = SVN::Pool->new;
4875 $self->do_switch(1, '', 0, $self->{url},
4876 SVN::Delta::Editor->new, $pool);
4881 $rep->abort_report($pool);
4889 sub skip_unknown_revs {
4891 my $errno = $err->apr_err();
4892 # Maybe the branch we're tracking didn't
4893 # exist when the repo started, so it's
4894 # not an error if it doesn't, just continue
4896 # Wonderfully consistent library, eh?
4897 # 160013 - svn:// and file://
4898 # 175002 - http(s)://
4899 # 175007 - http(s):// (this repo required authorization, too...)
4900 # More codes may be discovered later...
4901 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4902 my $err_key = $err->expanded_message;
4903 # revision numbers change every time, filter them out
4904 $err_key =~ s/\d+/\0/g;
4905 $err_key = "$errno\0$err_key";
4906 unless ($ignored_err{$err_key}) {
4907 warn "W: Ignoring error from SVN, path probably ",
4908 "does not exist: ($errno): ",
4909 $err->expanded_message,"\n";
4910 warn "W: Do not be alarmed at the above message ",
4911 "git-svn is just searching aggressively for ",
4913 "This may take a while on large repositories\n";
4914 $ignored_err{$err_key} = 1;
4918 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4921 package Git::SVN::Log;
4924 use POSIX qw/strftime/;
4926 use constant commit_log_separator => ('-' x 72) . "\n";
4927 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4928 %rusers $show_commit $incremental/;
4933 return 1 if defined $c->{r};
4935 # big commit message got truncated by the 16k pretty buffer in rev-list
4936 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4937 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4939 my @log = command(qw/cat-file commit/, $c->{c});
4941 # shift off the headers
4942 shift @log while ($log[0] ne '');
4945 # TODO: make $c->{l} not have a trailing newline in the future
4946 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4948 (undef, $c->{r}, undef) = ::extract_metadata(
4949 (grep(/^git-svn-id: /, @log))[-1]);
4951 return defined $c->{r};
4955 return $color || Git->repository->get_colorbool('color.diff');
4958 sub git_svn_log_cmd {
4959 my ($r_min, $r_max, @args) = @_;
4961 my (@files, @log_opts);
4962 foreach my $x (@args) {
4963 if ($x eq '--' || @files) {
4966 if (::verify_ref("$x^0")) {
4974 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4975 $gs ||= Git::SVN->_new;
4976 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4978 push @cmd, '-r' unless $non_recursive;
4979 push @cmd, qw/--raw --name-status/ if $verbose;
4980 push @cmd, '--color' if log_use_color();
4981 push @cmd, @log_opts;
4982 if (defined $r_max && $r_max == $r_min) {
4983 push @cmd, '--max-count=1';
4984 if (my $c = $gs->rev_map_get($r_max)) {
4987 } elsif (defined $r_max) {
4988 if ($r_max < $r_min) {
4989 ($r_min, $r_max) = ($r_max, $r_min);
4991 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4992 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4993 # If there are no commits in the range, both $c_max and $c_min
4994 # will be undefined. If there is at least 1 commit in the
4995 # range, both will be defined.
4996 return () if !defined $c_min || !defined $c_max;
4997 if ($c_min eq $c_max) {
4998 push @cmd, '--max-count=1', $c_min;
5000 push @cmd, '--boundary', "$c_min..$c_max";
5003 return (@cmd, @files);
5006 # adapted from pager.c
5008 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
5009 if (!defined $pager) {
5011 } elsif (length $pager == 0 || $pager eq 'cat') {
5014 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5018 return unless -t *STDOUT && defined $pager;
5019 pipe my ($rfd, $wfd) or return;
5020 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5022 open STDOUT, '>&', $wfd or
5023 ::fatal "Can't redirect to stdout: $!";
5026 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5027 $ENV{LESS} ||= 'FRSX';
5028 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5031 sub format_svn_date {
5032 # some systmes don't handle or mishandle %z, so be creative.
5033 my $t = shift || time;
5034 my $gm = timelocal(gmtime($t));
5035 my $sign = qw( + + - )[ $t <=> $gm ];
5036 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5037 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5040 sub parse_git_date {
5042 # Date::Parse isn't in the standard Perl distro :(
5043 if ($tz =~ s/^\+//) {
5044 $t += tz_to_s_offset($tz);
5045 } elsif ($tz =~ s/^\-//) {
5046 $t -= tz_to_s_offset($tz);
5051 sub set_local_timezone {
5059 sub tz_to_s_offset {
5062 return ($1 * 60) + ($tz * 3600);
5065 sub get_author_info {
5066 my ($dest, $author, $t, $tz) = @_;
5067 $author =~ s/(?:^\s*|\s*$)//g;
5068 $dest->{a_raw} = $author;
5071 $au = $rusers{$author} || undef;
5074 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5079 $dest->{t_utc} = parse_git_date($t, $tz);
5082 sub process_commit {
5083 my ($c, $r_min, $r_max, $defer) = @_;
5084 if (defined $r_min && defined $r_max) {
5085 if ($r_min == $c->{r} && $r_min == $r_max) {
5089 return 1 if $r_min == $r_max;
5090 if ($r_min < $r_max) {
5091 # we need to reverse the print order
5092 return 0 if (defined $limit && --$limit < 0);
5096 if ($r_min != $r_max) {
5097 return 1 if ($r_min < $c->{r});
5098 return 1 if ($r_max > $c->{r});
5101 return 0 if (defined $limit && --$limit < 0);
5110 if (my $l = $c->{l}) {
5111 while ($l->[0] =~ /^\s*$/) { shift @$l }
5114 $l_fmt ||= 'A' . length($c->{r});
5115 print 'r',pack($l_fmt, $c->{r}),' | ';
5116 print "$c->{c} | " if $show_commit;
5119 show_commit_normal($c);
5123 sub show_commit_changed_paths {
5125 return unless $c->{changed};
5126 print "Changed paths:\n", @{$c->{changed}};
5129 sub show_commit_normal {
5131 print commit_log_separator, "r$c->{r} | ";
5132 print "$c->{c} | " if $show_commit;
5133 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5136 if (my $l = $c->{l}) {
5137 while ($l->[$#$l] eq "\n" && $#$l > 0
5138 && $l->[($#$l - 1)] eq "\n") {
5141 $nr_line = scalar @$l;
5143 print "1 line\n\n\n";
5145 if ($nr_line == 1) {
5146 $nr_line = '1 line';
5148 $nr_line .= ' lines';
5150 print $nr_line, "\n";
5151 show_commit_changed_paths($c);
5153 print $_ foreach @$l;
5157 show_commit_changed_paths($c);
5161 foreach my $x (qw/raw stat diff/) {
5164 print $_ foreach @{$c->{$x}}
5171 my ($r_min, $r_max);
5172 my $r_last = -1; # prevent dupes
5173 set_local_timezone();
5174 if (defined $::_revision) {
5175 if ($::_revision =~ /^(\d+):(\d+)$/) {
5176 ($r_min, $r_max) = ($1, $2);
5177 } elsif ($::_revision =~ /^\d+$/) {
5178 $r_min = $r_max = $::_revision;
5180 ::fatal "-r$::_revision is not supported, use ",
5181 "standard 'git log' arguments instead";
5186 @args = git_svn_log_cmd($r_min, $r_max, @args);
5188 print commit_log_separator unless $incremental || $oneline;
5191 my $log = command_output_pipe(@args);
5193 my (@k, $c, $d, $stat);
5194 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5196 if (/^${esc_color}commit -?($::sha1_short)/o) {
5198 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5200 process_commit($c, $r_min, $r_max, \@k) or
5205 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5206 get_author_info($c, $1, $2, $3);
5207 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5209 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5210 push @{$c->{raw}}, $_;
5211 } elsif (/^${esc_color}[ACRMDT]\t/) {
5212 # we could add $SVN->{svn_path} here, but that requires
5213 # remote access at the moment (repo_path_split)...
5214 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5215 push @{$c->{changed}}, $_;
5216 } elsif (/^${esc_color}diff /o) {
5218 push @{$c->{diff}}, $_;
5220 push @{$c->{diff}}, $_;
5221 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5222 $esc_color*[\+\-]*$esc_color$/x) {
5224 push @{$c->{stat}}, $_;
5225 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5226 push @{$c->{stat}}, $_;
5228 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5229 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5230 } elsif (s/^${esc_color} //o) {
5231 push @{$c->{l}}, $_;
5234 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5236 process_commit($c, $r_min, $r_max, \@k);
5239 ($r_min, $r_max) = ($r_max, $r_min);
5240 process_commit($_, $r_min, $r_max) foreach reverse @k;
5244 print commit_log_separator unless $incremental || $oneline;
5253 my ($fh, $ctx, $rev);
5256 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5257 while (my $line = <$fh>) {
5258 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5259 # Uncommitted edits show up as a rev ID of
5260 # all zeros, which we can't look up with
5263 (undef, $rev, undef) =
5265 $rev = '0' if (!$rev);
5269 $rev = sprintf('%-10s', $rev);
5270 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5275 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5280 my %dsha; #distinct sha keys
5282 while (my $line = <$fh>) {
5283 push @buffer, $line;
5284 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5289 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5291 foreach my $line (@buffer) {
5292 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5294 $rev = '0' if (!$rev)
5296 elsif ($line =~ /^author (.*)/) {
5297 $authors{$rev} = $1;
5298 $authors{$rev} =~ s/\s/_/g;
5300 elsif ($line =~ /^\t(.*)$/) {
5301 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5305 command_close_pipe($fh, $ctx);
5308 package Git::SVN::Migration;
5309 # these version numbers do NOT correspond to actual version numbers
5310 # of git nor git-svn. They are just relative.
5312 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5314 # v1 layout: .git/$id/info/url, refs/remotes/$id
5316 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5318 # v3 layout: .git/svn/$id, refs/remotes/$id
5319 # - info/url may remain for backwards compatibility
5320 # - this is what we migrate up to this layout automatically,
5321 # - this will be used by git svn init on single branches
5322 # v3.1 layout (auto migrated):
5323 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5324 # for backwards compatibility
5326 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5327 # - this is only created for newly multi-init-ed
5328 # repositories. Similar in spirit to the
5329 # --use-separate-remotes option in git-clone (now default)
5330 # - we do not automatically migrate to this (following
5331 # the example set by core git)
5333 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5334 # - newer, more-efficient format that uses 24-bytes per record
5335 # with no filler space.
5336 # - use xxd -c24 < .rev_map.$UUID to view and debug
5337 # - This is a one-way migration, repositories updated to the
5338 # new format will not be able to use old git-svn without
5339 # rebuilding the .rev_db. Rebuilding the rev_db is not
5340 # possible if noMetadata or useSvmProps are set; but should
5341 # be no problem for users that use the (sensible) defaults.
5345 use File::Path qw/mkpath/;
5346 use File::Basename qw/dirname basename/;
5347 use vars qw/$_minimize/;
5349 sub migrate_from_v0 {
5350 my $git_dir = $ENV{GIT_DIR};
5351 return undef unless -d $git_dir;
5352 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5356 my ($id, $orig_ref) = ($_, $_);
5357 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5358 next unless -f "$git_dir/$id/info/url";
5359 my $new_ref = "refs/remotes/$id";
5360 if (::verify_ref("$new_ref^0")) {
5361 print STDERR "W: $orig_ref is probably an old ",
5362 "branch used by an ancient version of ",
5364 "However, $new_ref also exists.\n",
5365 "We will not be able ",
5366 "to use this branch until this ",
5367 "ambiguity is resolved.\n";
5370 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5371 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5372 command_noisy('update-ref', $new_ref, $orig_ref);
5373 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5376 command_close_pipe($fh, $ctx);
5377 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5381 sub migrate_from_v1 {
5382 my $git_dir = $ENV{GIT_DIR};
5384 return $migrated unless -d $git_dir;
5385 my $svn_dir = "$git_dir/svn";
5387 # just in case somebody used 'svn' as their $id at some point...
5388 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5390 print STDERR "Migrating from a git-svn v1 layout...\n";
5392 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5393 "$svn_dir\n\t(required for this version ",
5394 "($::VERSION) of git-svn) does not exist.\n";
5395 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5398 next unless $x =~ s#^refs/remotes/##;
5400 next unless -f "$git_dir/$x/info/url";
5401 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5403 my $dn = dirname("$git_dir/svn/$x");
5404 mkpath([$dn]) unless -d $dn;
5405 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5406 mkpath(["$git_dir/svn/svn"]);
5407 print STDERR " - $git_dir/$x/info => ",
5408 "$git_dir/svn/$x/info\n";
5409 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5411 # don't worry too much about these, they probably
5412 # don't exist with repos this old (save for index,
5413 # and we can easily regenerate that)
5414 foreach my $f (qw/unhandled.log index .rev_db/) {
5415 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5418 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5419 rename "$git_dir/$x", "$git_dir/svn/$x" or
5424 command_close_pipe($fh, $ctx);
5425 print STDERR "Done migrating from a git-svn v1 layout\n";
5430 my ($l_map, $pfx, $path) = @_;
5432 foreach (<$path/*>) {
5433 if (-r "$_/info/url") {
5434 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5435 my $ref_id = $pfx . basename $_;
5436 my $url = ::file_to_s("$_/info/url");
5437 $l_map->{$ref_id} = $url;
5444 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5445 read_old_urls($l_map, $x, $_);
5449 sub migrate_from_v2 {
5450 my @cfg = command(qw/config -l/);
5451 return if grep /^svn-remote\..+\.url=/, @cfg;
5453 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5456 foreach my $ref_id (sort keys %l_map) {
5457 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5459 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5466 sub minimize_connections {
5467 my $r = Git::SVN::read_all_remotes();
5469 my $root_repos = {};
5470 foreach my $repo_id (keys %$r) {
5471 my $url = $r->{$repo_id}->{url} or next;
5472 my $fetch = $r->{$repo_id}->{fetch} or next;
5473 my $ra = Git::SVN::Ra->new($url);
5475 # skip existing cases where we already connect to the root
5476 if (($ra->{url} eq $ra->{repos_root}) ||
5477 ($ra->{repos_root} eq $repo_id)) {
5478 $root_repos->{$ra->{url}} = $repo_id;
5482 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5483 my $root_path = $ra->{url};
5484 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5485 foreach my $path (keys %$fetch) {
5486 my $ref_id = $fetch->{$path};
5487 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5489 # make sure we can read when connecting to
5490 # a higher level of a repository
5491 my ($last_rev, undef) = $gs->last_rev_commit;
5492 if (!defined $last_rev) {
5494 $root_ra->get_latest_revnum;
5498 my $new = $root_path;
5499 $new .= length $path ? "/$path" : '';
5501 $root_ra->get_log([$new], $last_rev, $last_rev,
5505 $new_urls->{$ra->{repos_root}}->{$new} =
5506 { ref_id => $ref_id,
5507 old_repo_id => $repo_id,
5508 old_path => $path };
5513 foreach my $url (keys %$new_urls) {
5514 # see if we can re-use an existing [svn-remote "repo_id"]
5515 # instead of creating a(n ugly) new section:
5516 my $repo_id = $root_repos->{$url} || $url;
5518 my $fetch = $new_urls->{$url};
5519 foreach my $path (keys %$fetch) {
5520 my $x = $fetch->{$path};
5521 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5522 my $pfx = "svn-remote.$x->{old_repo_id}";
5524 my $old_fetch = quotemeta("$x->{old_path}:".
5526 command_noisy(qw/config --unset/,
5527 "$pfx.fetch", '^'. $old_fetch . '$');
5528 delete $r->{$x->{old_repo_id}}->
5529 {fetch}->{$x->{old_path}};
5530 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5531 command_noisy(qw/config --unset/,
5533 push @emptied, $x->{old_repo_id}
5538 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5540 The following [svn-remote] sections in your config file ($file) are empty
5541 and can be safely removed:
5543 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5547 sub migration_check {
5551 minimize_connections() if $_minimize;
5554 package Git::IndexInfo;
5557 use Git qw/command_input_pipe command_close_pipe/;
5561 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5562 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5566 my ($self, $path) = @_;
5567 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5568 return ++$self->{nr};
5574 my ($self, $mode, $hash, $path) = @_;
5575 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5576 return ++$self->{nr};
5583 command_close_pipe($self->{gui}, $self->{ctx});
5586 package Git::SVN::GlobSpec;
5591 my ($class, $glob) = @_;
5593 $re =~ s!/+$!!g; # no need for trailing slashes
5594 $re =~ m!^([^*]*)(\*(?:/\*)*)(.*)$!;
5596 my ($left, $right) = ($1, $3);
5598 my $depth = $re =~ tr/*/*/;
5599 if ($depth != $temp =~ tr/*/*/) {
5600 die "Only one set of wildcard directories " .
5601 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5604 die "One '*' is needed for glob: '$glob'\n";
5606 $re =~ s!\*!\[^/\]*!g;
5607 $re = quotemeta($left) . "($re)" . quotemeta($right);
5608 if (length $left && !($left =~ s!/+$!!g)) {
5609 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5611 if (length $right && !($right =~ s!^/+!!g)) {
5612 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5614 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5615 bless { left => $left, right => $right, left_regex => $left_re,
5616 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5620 my ($self, $path) = @_;
5621 return (length $self->{left} ? "$self->{left}/" : '') .
5622 $path . (length $self->{right} ? "/$self->{right}" : '');
5630 $remotes = { # returned by read_all_remotes()
5632 # svn-remote.svn.url=https://svn.musicpd.org
5633 url => 'https://svn.musicpd.org',
5634 # svn-remote.svn.fetch=mpd/trunk:trunk
5636 'mpd/trunk' => 'trunk',
5638 # svn-remote.svn.tags=mpd/tags/*:tags/*
5643 regex => qr!mpd/tags/([^/]+)$!,
5649 regex => qr!tags/([^/]+)$!,
5656 $log_entry hashref as returned by libsvn_log_entry()
5658 log => 'whitespace-formatted log entry
5659 ', # trailing newline is preserved
5660 revision => '8', # integer
5661 date => '2004-02-24T17:01:44.108345Z', # commit date
5662 author => 'committer name'
5666 # this is generated by generate_diff();
5667 @mods = array of diff-index line hashes, each element represents one line
5668 of diff-index output
5670 diff-index line ($m hash)
5672 mode_a => first column of diff-index output, no leading ':',
5673 mode_b => second column of diff-index output,
5674 sha1_b => sha1sum of the final blob,
5675 chg => change type [MCRADT],
5676 file_a => original file name of a file (iff chg is 'C' or 'R')
5677 file_b => new/current file name of a file (any chg)
5681 # retval of read_url_paths{,_all}();
5683 # repository root url
5684 'https://svn.musicpd.org' => {
5685 # repository path # GIT_SVN_ID
5686 'mpd/trunk' => 'trunk',
5687 'mpd/tags/0.11.5' => 'tags/0.11.5',
5692 I don't trust the each() function on unless I created %hash myself
5693 because the internal iterator may not have started at base.