Merge branch 'mg/pushurl'
[git/git-svn.git] / git-svn.perl
blob33017974d0a098bdaff707ccf0e8660aa5009079
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_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)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, $_tags, $_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
99 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run,
145 'tag|t' => \$_tag } ],
146 tag => [ sub { $_tag = 1; cmd_branch(@_) },
147 'Create a tag in the SVN repository',
148 { 'message|m=s' => \$_message,
149 'dry-run|n' => \$_dry_run } ],
150 'set-tree' => [ \&cmd_set_tree,
151 "Set an SVN repository to a git tree-ish",
152 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
153 'create-ignore' => [ \&cmd_create_ignore,
154 'Create a .gitignore per svn:ignore',
155 { 'revision|r=i' => \$_revision
156 } ],
157 'propget' => [ \&cmd_propget,
158 'Print the value of a property on a file or directory',
159 { 'revision|r=i' => \$_revision } ],
160 'proplist' => [ \&cmd_proplist,
161 'List all properties of a file or directory',
162 { 'revision|r=i' => \$_revision } ],
163 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
164 { 'revision|r=i' => \$_revision
165 } ],
166 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
167 { 'revision|r=i' => \$_revision
168 } ],
169 'multi-fetch' => [ \&cmd_multi_fetch,
170 "Deprecated alias for $0 fetch --all",
171 { 'revision|r=s' => \$_revision, %fc_opts } ],
172 'migrate' => [ sub { },
173 # no-op, we automatically run this anyways,
174 'Migrate configuration/metadata/layout from
175 previous versions of git-svn',
176 { 'minimize' => \$Git::SVN::Migration::_minimize,
177 %remote_opts } ],
178 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
179 { 'limit=i' => \$Git::SVN::Log::limit,
180 'revision|r=s' => \$_revision,
181 'verbose|v' => \$Git::SVN::Log::verbose,
182 'incremental' => \$Git::SVN::Log::incremental,
183 'oneline' => \$Git::SVN::Log::oneline,
184 'show-commit' => \$Git::SVN::Log::show_commit,
185 'non-recursive' => \$Git::SVN::Log::non_recursive,
186 'authors-file|A=s' => \$_authors,
187 'color' => \$Git::SVN::Log::color,
188 'pager=s' => \$Git::SVN::Log::pager
189 } ],
190 'find-rev' => [ \&cmd_find_rev,
191 "Translate between SVN revision numbers and tree-ish",
192 {} ],
193 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
194 { 'merge|m|M' => \$_merge,
195 'verbose|v' => \$_verbose,
196 'strategy|s=s' => \$_strategy,
197 'local|l' => \$_local,
198 'fetch-all|all' => \$_fetch_all,
199 'dry-run|n' => \$_dry_run,
200 %fc_opts } ],
201 'commit-diff' => [ \&cmd_commit_diff,
202 'Commit a diff between two trees',
203 { 'message|m=s' => \$_message,
204 'file|F=s' => \$_file,
205 'revision|r=s' => \$_revision,
206 %cmt_opts } ],
207 'info' => [ \&cmd_info,
208 "Show info about the latest SVN revision
209 on the current branch",
210 { 'url' => \$_url, } ],
211 'blame' => [ \&Git::SVN::Log::cmd_blame,
212 "Show what revision and author last modified each line of a file",
213 { 'git-format' => \$_git_format } ],
216 my $cmd;
217 for (my $i = 0; $i < @ARGV; $i++) {
218 if (defined $cmd{$ARGV[$i]}) {
219 $cmd = $ARGV[$i];
220 splice @ARGV, $i, 1;
221 last;
225 # make sure we're always running at the top-level working directory
226 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
227 unless (-d $ENV{GIT_DIR}) {
228 if ($git_dir_user_set) {
229 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
230 "but it is not a directory\n";
232 my $git_dir = delete $ENV{GIT_DIR};
233 my $cdup = undef;
234 git_cmd_try {
235 $cdup = command_oneline(qw/rev-parse --show-cdup/);
236 $git_dir = '.' unless ($cdup);
237 chomp $cdup if ($cdup);
238 $cdup = "." unless ($cdup && length $cdup);
239 } "Already at toplevel, but $git_dir not found\n";
240 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
241 unless (-d $git_dir) {
242 die "$git_dir still not found after going to ",
243 "'$cdup'\n";
245 $ENV{GIT_DIR} = $git_dir;
247 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
250 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
252 read_repo_config(\%opts);
253 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
254 Getopt::Long::Configure('pass_through');
256 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
257 'minimize-connections' => \$Git::SVN::Migration::_minimize,
258 'id|i=s' => \$Git::SVN::default_ref_id,
259 'svn-remote|remote|R=s' => sub {
260 $Git::SVN::no_reuse_existing = 1;
261 $Git::SVN::default_repo_id = $_[1] });
262 exit 1 if (!$rv && $cmd && $cmd ne 'log');
264 usage(0) if $_help;
265 version() if $_version;
266 usage(1) unless defined $cmd;
267 load_authors() if $_authors;
268 if (defined $_authors_prog) {
269 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
272 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
273 Git::SVN::Migration::migration_check();
275 Git::SVN::init_vars();
276 eval {
277 Git::SVN::verify_remotes_sanity();
278 $cmd{$cmd}->[0]->(@ARGV);
280 fatal $@ if $@;
281 post_fetch_checkout();
282 exit 0;
284 ####################### primary functions ######################
285 sub usage {
286 my $exit = shift || 0;
287 my $fd = $exit ? \*STDERR : \*STDOUT;
288 print $fd <<"";
289 git-svn - bidirectional operations between a single Subversion tree and git
290 Usage: git svn <command> [options] [arguments]\n
292 print $fd "Available commands:\n" unless $cmd;
294 foreach (sort keys %cmd) {
295 next if $cmd && $cmd ne $_;
296 next if /^multi-/; # don't show deprecated commands
297 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
298 foreach (sort keys %{$cmd{$_}->[2]}) {
299 # mixed-case options are for .git/config only
300 next if /[A-Z]/ && /^[a-z]+$/i;
301 # prints out arguments as they should be passed:
302 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
303 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
304 "--$_" : "-$_" }
305 split /\|/,$_)," $x\n";
308 print $fd <<"";
309 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
310 arbitrary identifier if you're tracking multiple SVN branches/repositories in
311 one git repository and want to keep them separate. See git-svn(1) for more
312 information.
314 exit $exit;
317 sub version {
318 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
319 exit 0;
322 sub do_git_init_db {
323 unless (-d $ENV{GIT_DIR}) {
324 my @init_db = ('init');
325 push @init_db, "--template=$_template" if defined $_template;
326 if (defined $_shared) {
327 if ($_shared =~ /[a-z]/) {
328 push @init_db, "--shared=$_shared";
329 } else {
330 push @init_db, "--shared";
333 command_noisy(@init_db);
334 $_repository = Git->repository(Repository => ".git");
336 command_noisy('config', 'core.autocrlf', 'false');
337 my $set;
338 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
339 foreach my $i (keys %icv) {
340 die "'$set' and '$i' cannot both be set\n" if $set;
341 next unless defined $icv{$i};
342 command_noisy('config', "$pfx.$i", $icv{$i});
343 $set = $i;
345 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
346 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
347 if defined $$ignore_regex;
350 sub init_subdir {
351 my $repo_path = shift or return;
352 mkpath([$repo_path]) unless -d $repo_path;
353 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
354 $ENV{GIT_DIR} = '.git';
355 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
358 sub cmd_clone {
359 my ($url, $path) = @_;
360 if (!defined $path &&
361 (defined $_trunk || defined $_branches || defined $_tags ||
362 defined $_stdlayout) &&
363 $url !~ m#^[a-z\+]+://#) {
364 $path = $url;
366 $path = basename($url) if !defined $path || !length $path;
367 cmd_init($url, $path);
368 Git::SVN::fetch_all($Git::SVN::default_repo_id);
369 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
372 sub cmd_init {
373 if (defined $_stdlayout) {
374 $_trunk = 'trunk' if (!defined $_trunk);
375 $_tags = 'tags' if (!defined $_tags);
376 $_branches = 'branches' if (!defined $_branches);
378 if (defined $_trunk || defined $_branches || defined $_tags) {
379 return cmd_multi_init(@_);
381 my $url = shift or die "SVN repository location required ",
382 "as a command-line argument\n";
383 init_subdir(@_);
384 do_git_init_db();
386 Git::SVN->init($url);
389 sub cmd_fetch {
390 if (grep /^\d+=./, @_) {
391 die "'<rev>=<commit>' fetch arguments are ",
392 "no longer supported.\n";
394 my ($remote) = @_;
395 if (@_ > 1) {
396 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
398 if ($_fetch_parent) {
399 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
400 unless ($gs) {
401 die "Unable to determine upstream SVN information from ",
402 "working tree history\n";
404 # just fetch, don't checkout.
405 $_no_checkout = 'true';
406 $_fetch_all ? $gs->fetch_all : $gs->fetch;
407 } elsif ($_fetch_all) {
408 cmd_multi_fetch();
409 } else {
410 $remote ||= $Git::SVN::default_repo_id;
411 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
415 sub cmd_set_tree {
416 my (@commits) = @_;
417 if ($_stdin || !@commits) {
418 print "Reading from stdin...\n";
419 @commits = ();
420 while (<STDIN>) {
421 if (/\b($sha1_short)\b/o) {
422 unshift @commits, $1;
426 my @revs;
427 foreach my $c (@commits) {
428 my @tmp = command('rev-parse',$c);
429 if (scalar @tmp == 1) {
430 push @revs, $tmp[0];
431 } elsif (scalar @tmp > 1) {
432 push @revs, reverse(command('rev-list',@tmp));
433 } else {
434 fatal "Failed to rev-parse $c";
437 my $gs = Git::SVN->new;
438 my ($r_last, $cmt_last) = $gs->last_rev_commit;
439 $gs->fetch;
440 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
441 fatal "There are new revisions that were fetched ",
442 "and need to be merged (or acknowledged) ",
443 "before committing.\nlast rev: $r_last\n",
444 " current: $gs->{last_rev}";
446 $gs->set_tree($_) foreach @revs;
447 print "Done committing ",scalar @revs," revisions to SVN\n";
448 unlink $gs->{index};
451 sub cmd_dcommit {
452 my $head = shift;
453 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
454 'Cannot dcommit with a dirty index. Commit your changes first, '
455 . "or stash them with `git stash'.\n";
456 $head ||= 'HEAD';
457 my @refs;
458 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
459 unless ($gs) {
460 die "Unable to determine upstream SVN information from ",
461 "$head history.\nPerhaps the repository is empty.";
464 if (defined $_commit_url) {
465 $url = $_commit_url;
466 } else {
467 $url = eval { command_oneline('config', '--get',
468 "svn-remote.$gs->{repo_id}.commiturl") };
469 if (!$url) {
470 $url = $gs->full_url
474 my $last_rev = $_revision if defined $_revision;
475 if ($url) {
476 print "Committing to $url ...\n";
478 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
479 if ($_no_rebase && scalar(@$linear_refs) > 1) {
480 warn "Attempting to commit more than one change while ",
481 "--no-rebase is enabled.\n",
482 "If these changes depend on each other, re-running ",
483 "without --no-rebase may be required."
485 my $expect_url = $url;
486 Git::SVN::remove_username($expect_url);
487 while (1) {
488 my $d = shift @$linear_refs or last;
489 unless (defined $last_rev) {
490 (undef, $last_rev, undef) = cmt_metadata("$d~1");
491 unless (defined $last_rev) {
492 fatal "Unable to extract revision information ",
493 "from commit $d~1";
496 if ($_dry_run) {
497 print "diff-tree $d~1 $d\n";
498 } else {
499 my $cmt_rev;
500 my %ed_opts = ( r => $last_rev,
501 log => get_commit_entry($d)->{log},
502 ra => Git::SVN::Ra->new($url),
503 config => SVN::Core::config_get_config(
504 $Git::SVN::Ra::config_dir
506 tree_a => "$d~1",
507 tree_b => $d,
508 editor_cb => sub {
509 print "Committed r$_[0]\n";
510 $cmt_rev = $_[0];
512 svn_path => '');
513 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
514 print "No changes\n$d~1 == $d\n";
515 } elsif ($parents->{$d} && @{$parents->{$d}}) {
516 $gs->{inject_parents_dcommit}->{$cmt_rev} =
517 $parents->{$d};
519 $_fetch_all ? $gs->fetch_all : $gs->fetch;
520 $last_rev = $cmt_rev;
521 next if $_no_rebase;
523 # we always want to rebase against the current HEAD,
524 # not any head that was passed to us
525 my @diff = command('diff-tree', $d,
526 $gs->refname, '--');
527 my @finish;
528 if (@diff) {
529 @finish = rebase_cmd();
530 print STDERR "W: $d and ", $gs->refname,
531 " differ, using @finish:\n",
532 join("\n", @diff), "\n";
533 } else {
534 print "No changes between current HEAD and ",
535 $gs->refname,
536 "\nResetting to the latest ",
537 $gs->refname, "\n";
538 @finish = qw/reset --mixed/;
540 command_noisy(@finish, $gs->refname);
541 if (@diff) {
542 @refs = ();
543 my ($url_, $rev_, $uuid_, $gs_) =
544 working_head_info($head, \@refs);
545 my ($linear_refs_, $parents_) =
546 linearize_history($gs_, \@refs);
547 if (scalar(@$linear_refs) !=
548 scalar(@$linear_refs_)) {
549 fatal "# of revisions changed ",
550 "\nbefore:\n",
551 join("\n", @$linear_refs),
552 "\n\nafter:\n",
553 join("\n", @$linear_refs_), "\n",
554 'If you are attempting to commit ',
555 "merges, try running:\n\t",
556 'git rebase --interactive',
557 '--preserve-merges ',
558 $gs->refname,
559 "\nBefore dcommitting";
561 if ($url_ ne $expect_url) {
562 fatal "URL mismatch after rebase: ",
563 "$url_ != $expect_url";
565 if ($uuid_ ne $uuid) {
566 fatal "uuid mismatch after rebase: ",
567 "$uuid_ != $uuid";
569 # remap parents
570 my (%p, @l, $i);
571 for ($i = 0; $i < scalar @$linear_refs; $i++) {
572 my $new = $linear_refs_->[$i] or next;
573 $p{$new} =
574 $parents->{$linear_refs->[$i]};
575 push @l, $new;
577 $parents = \%p;
578 $linear_refs = \@l;
582 unlink $gs->{index};
585 sub cmd_branch {
586 my ($branch_name, $head) = @_;
588 unless (defined $branch_name && length $branch_name) {
589 die(($_tag ? "tag" : "branch") . " name required\n");
591 $head ||= 'HEAD';
593 my ($src, $rev, undef, $gs) = working_head_info($head);
595 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
596 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
597 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
598 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
600 my $ctx = SVN::Client->new(
601 auth => Git::SVN::Ra::_auth_providers(),
602 log_msg => sub {
603 ${ $_[0] } = defined $_message
604 ? $_message
605 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
606 . $branch_name;
610 eval {
611 $ctx->ls($dst, 'HEAD', 0);
612 } and die "branch ${branch_name} already exists\n";
614 print "Copying ${src} at r${rev} to ${dst}...\n";
615 $ctx->copy($src, $rev, $dst)
616 unless $_dry_run;
618 $gs->fetch_all;
621 sub cmd_find_rev {
622 my $revision_or_hash = shift or die "SVN or git revision required ",
623 "as a command-line argument\n";
624 my $result;
625 if ($revision_or_hash =~ /^r\d+$/) {
626 my $head = shift;
627 $head ||= 'HEAD';
628 my @refs;
629 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
630 unless ($gs) {
631 die "Unable to determine upstream SVN information from ",
632 "$head history\n";
634 my $desired_revision = substr($revision_or_hash, 1);
635 $result = $gs->rev_map_get($desired_revision, $uuid);
636 } else {
637 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
638 $result = $rev;
640 print "$result\n" if $result;
643 sub cmd_rebase {
644 command_noisy(qw/update-index --refresh/);
645 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
646 unless ($gs) {
647 die "Unable to determine upstream SVN information from ",
648 "working tree history\n";
650 if ($_dry_run) {
651 print "Remote Branch: " . $gs->refname . "\n";
652 print "SVN URL: " . $url . "\n";
653 return;
655 if (command(qw/diff-index HEAD --/)) {
656 print STDERR "Cannot rebase with uncommited changes:\n";
657 command_noisy('status');
658 exit 1;
660 unless ($_local) {
661 # rebase will checkout for us, so no need to do it explicitly
662 $_no_checkout = 'true';
663 $_fetch_all ? $gs->fetch_all : $gs->fetch;
665 command_noisy(rebase_cmd(), $gs->refname);
668 sub cmd_show_ignore {
669 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
670 $gs ||= Git::SVN->new;
671 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
672 $gs->prop_walk($gs->{path}, $r, sub {
673 my ($gs, $path, $props) = @_;
674 print STDOUT "\n# $path\n";
675 my $s = $props->{'svn:ignore'} or return;
676 $s =~ s/[\r\n]+/\n/g;
677 chomp $s;
678 $s =~ s#^#$path#gm;
679 print STDOUT "$s\n";
683 sub cmd_show_externals {
684 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
685 $gs ||= Git::SVN->new;
686 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
687 $gs->prop_walk($gs->{path}, $r, sub {
688 my ($gs, $path, $props) = @_;
689 print STDOUT "\n# $path\n";
690 my $s = $props->{'svn:externals'} or return;
691 $s =~ s/[\r\n]+/\n/g;
692 chomp $s;
693 $s =~ s#^#$path#gm;
694 print STDOUT "$s\n";
698 sub cmd_create_ignore {
699 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
700 $gs ||= Git::SVN->new;
701 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
702 $gs->prop_walk($gs->{path}, $r, sub {
703 my ($gs, $path, $props) = @_;
704 # $path is of the form /path/to/dir/
705 $path = '.' . $path;
706 # SVN can have attributes on empty directories,
707 # which git won't track
708 mkpath([$path]) unless -d $path;
709 my $ignore = $path . '.gitignore';
710 my $s = $props->{'svn:ignore'} or return;
711 open(GITIGNORE, '>', $ignore)
712 or fatal("Failed to open `$ignore' for writing: $!");
713 $s =~ s/[\r\n]+/\n/g;
714 chomp $s;
715 # Prefix all patterns so that the ignore doesn't apply
716 # to sub-directories.
717 $s =~ s#^#/#gm;
718 print GITIGNORE "$s\n";
719 close(GITIGNORE)
720 or fatal("Failed to close `$ignore': $!");
721 command_noisy('add', '-f', $ignore);
725 sub canonicalize_path {
726 my ($path) = @_;
727 my $dot_slash_added = 0;
728 if (substr($path, 0, 1) ne "/") {
729 $path = "./" . $path;
730 $dot_slash_added = 1;
732 # File::Spec->canonpath doesn't collapse x/../y into y (for a
733 # good reason), so let's do this manually.
734 $path =~ s#/+#/#g;
735 $path =~ s#/\.(?:/|$)#/#g;
736 $path =~ s#/[^/]+/\.\.##g;
737 $path =~ s#/$##g;
738 $path =~ s#^\./## if $dot_slash_added;
739 $path =~ s#^/##;
740 $path =~ s#^\.$##;
741 return $path;
744 # get_svnprops(PATH)
745 # ------------------
746 # Helper for cmd_propget and cmd_proplist below.
747 sub get_svnprops {
748 my $path = shift;
749 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
750 $gs ||= Git::SVN->new;
752 # prefix THE PATH by the sub-directory from which the user
753 # invoked us.
754 $path = $cmd_dir_prefix . $path;
755 fatal("No such file or directory: $path") unless -e $path;
756 my $is_dir = -d $path ? 1 : 0;
757 $path = $gs->{path} . '/' . $path;
759 # canonicalize the path (otherwise libsvn will abort or fail to
760 # find the file)
761 $path = canonicalize_path($path);
763 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
764 my $props;
765 if ($is_dir) {
766 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
768 else {
769 (undef, $props) = $gs->ra->get_file($path, $r, undef);
771 return $props;
774 # cmd_propget (PROP, PATH)
775 # ------------------------
776 # Print the SVN property PROP for PATH.
777 sub cmd_propget {
778 my ($prop, $path) = @_;
779 $path = '.' if not defined $path;
780 usage(1) if not defined $prop;
781 my $props = get_svnprops($path);
782 if (not defined $props->{$prop}) {
783 fatal("`$path' does not have a `$prop' SVN property.");
785 print $props->{$prop} . "\n";
788 # cmd_proplist (PATH)
789 # -------------------
790 # Print the list of SVN properties for PATH.
791 sub cmd_proplist {
792 my $path = shift;
793 $path = '.' if not defined $path;
794 my $props = get_svnprops($path);
795 print "Properties on '$path':\n";
796 foreach (sort keys %{$props}) {
797 print " $_\n";
801 sub cmd_multi_init {
802 my $url = shift;
803 unless (defined $_trunk || defined $_branches || defined $_tags) {
804 usage(1);
807 # there are currently some bugs that prevent multi-init/multi-fetch
808 # setups from working well without this.
809 $Git::SVN::_minimize_url = 1;
811 $_prefix = '' unless defined $_prefix;
812 if (defined $url) {
813 $url =~ s#/+$##;
814 init_subdir(@_);
816 do_git_init_db();
817 if (defined $_trunk) {
818 my $trunk_ref = $_prefix . 'trunk';
819 # try both old-style and new-style lookups:
820 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
821 unless ($gs_trunk) {
822 my ($trunk_url, $trunk_path) =
823 complete_svn_url($url, $_trunk);
824 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
825 undef, $trunk_ref);
828 return unless defined $_branches || defined $_tags;
829 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
830 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
831 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
834 sub cmd_multi_fetch {
835 my $remotes = Git::SVN::read_all_remotes();
836 foreach my $repo_id (sort keys %$remotes) {
837 if ($remotes->{$repo_id}->{url}) {
838 Git::SVN::fetch_all($repo_id, $remotes);
843 # this command is special because it requires no metadata
844 sub cmd_commit_diff {
845 my ($ta, $tb, $url) = @_;
846 my $usage = "Usage: $0 commit-diff -r<revision> ".
847 "<tree-ish> <tree-ish> [<URL>]";
848 fatal($usage) if (!defined $ta || !defined $tb);
849 my $svn_path = '';
850 if (!defined $url) {
851 my $gs = eval { Git::SVN->new };
852 if (!$gs) {
853 fatal("Needed URL or usable git-svn --id in ",
854 "the command-line\n", $usage);
856 $url = $gs->{url};
857 $svn_path = $gs->{path};
859 unless (defined $_revision) {
860 fatal("-r|--revision is a required argument\n", $usage);
862 if (defined $_message && defined $_file) {
863 fatal("Both --message/-m and --file/-F specified ",
864 "for the commit message.\n",
865 "I have no idea what you mean");
867 if (defined $_file) {
868 $_message = file_to_s($_file);
869 } else {
870 $_message ||= get_commit_entry($tb)->{log};
872 my $ra ||= Git::SVN::Ra->new($url);
873 my $r = $_revision;
874 if ($r eq 'HEAD') {
875 $r = $ra->get_latest_revnum;
876 } elsif ($r !~ /^\d+$/) {
877 die "revision argument: $r not understood by git-svn\n";
879 my %ed_opts = ( r => $r,
880 log => $_message,
881 ra => $ra,
882 tree_a => $ta,
883 tree_b => $tb,
884 editor_cb => sub { print "Committed r$_[0]\n" },
885 svn_path => $svn_path );
886 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
887 print "No changes\n$ta == $tb\n";
891 sub escape_uri_only {
892 my ($uri) = @_;
893 my @tmp;
894 foreach (split m{/}, $uri) {
895 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
896 push @tmp, $_;
898 join('/', @tmp);
901 sub escape_url {
902 my ($url) = @_;
903 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
904 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
905 $url = "$scheme://$domain$uri";
907 $url;
910 sub cmd_info {
911 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
912 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
913 if (exists $_[1]) {
914 die "Too many arguments specified\n";
917 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
919 if (!$file_type && !$diff_status) {
920 print STDERR "svn: '$path' is not under version control\n";
921 exit 1;
924 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
925 unless ($gs) {
926 die "Unable to determine upstream SVN information from ",
927 "working tree history\n";
930 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
931 $path = "." if $path eq "";
933 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
935 if ($_url) {
936 print escape_url($full_url), "\n";
937 return;
940 my $result = "Path: $path\n";
941 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
942 $result .= "URL: " . escape_url($full_url) . "\n";
944 eval {
945 my $repos_root = $gs->repos_root;
946 Git::SVN::remove_username($repos_root);
947 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
949 if ($@) {
950 $result .= "Repository Root: (offline)\n";
952 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
953 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
954 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
956 $result .= "Node Kind: " .
957 ($file_type eq "dir" ? "directory" : "file") . "\n";
959 my $schedule = $diff_status eq "A"
960 ? "add"
961 : ($diff_status eq "D" ? "delete" : "normal");
962 $result .= "Schedule: $schedule\n";
964 if ($diff_status eq "A") {
965 print $result, "\n";
966 return;
969 my ($lc_author, $lc_rev, $lc_date_utc);
970 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
971 my $log = command_output_pipe(@args);
972 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
973 while (<$log>) {
974 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
975 $lc_author = $1;
976 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
977 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
978 (undef, $lc_rev, undef) = ::extract_metadata($1);
981 close $log;
983 Git::SVN::Log::set_local_timezone();
985 $result .= "Last Changed Author: $lc_author\n";
986 $result .= "Last Changed Rev: $lc_rev\n";
987 $result .= "Last Changed Date: " .
988 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
990 if ($file_type ne "dir") {
991 my $text_last_updated_date =
992 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
993 $result .=
994 "Text Last Updated: " .
995 Git::SVN::Log::format_svn_date($text_last_updated_date) .
996 "\n";
997 my $checksum;
998 if ($diff_status eq "D") {
999 my ($fh, $ctx) =
1000 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1001 if ($file_type eq "link") {
1002 my $file_name = <$fh>;
1003 $checksum = md5sum("link $file_name");
1004 } else {
1005 $checksum = md5sum($fh);
1007 command_close_pipe($fh, $ctx);
1008 } elsif ($file_type eq "link") {
1009 my $file_name =
1010 command(qw(cat-file blob), "HEAD:$path");
1011 $checksum =
1012 md5sum("link " . $file_name);
1013 } else {
1014 open FILE, "<", $path or die $!;
1015 $checksum = md5sum(\*FILE);
1016 close FILE or die $!;
1018 $result .= "Checksum: " . $checksum . "\n";
1021 print $result, "\n";
1024 ########################### utility functions #########################
1026 sub rebase_cmd {
1027 my @cmd = qw/rebase/;
1028 push @cmd, '-v' if $_verbose;
1029 push @cmd, qw/--merge/ if $_merge;
1030 push @cmd, "--strategy=$_strategy" if $_strategy;
1031 @cmd;
1034 sub post_fetch_checkout {
1035 return if $_no_checkout;
1036 my $gs = $Git::SVN::_head or return;
1037 return if verify_ref('refs/heads/master^0');
1039 my $valid_head = verify_ref('HEAD^0');
1040 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1041 return if ($valid_head || !verify_ref('HEAD^0'));
1043 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1044 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1045 return if -f $index;
1047 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1048 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1049 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1050 print STDERR "Checked out HEAD:\n ",
1051 $gs->full_url, " r", $gs->last_rev, "\n";
1054 sub complete_svn_url {
1055 my ($url, $path) = @_;
1056 $path =~ s#/+$##;
1057 if ($path !~ m#^[a-z\+]+://#) {
1058 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1059 fatal("E: '$path' is not a complete URL ",
1060 "and a separate URL is not specified");
1062 return ($url, $path);
1064 return ($path, '');
1067 sub complete_url_ls_init {
1068 my ($ra, $repo_path, $switch, $pfx) = @_;
1069 unless ($repo_path) {
1070 print STDERR "W: $switch not specified\n";
1071 return;
1073 $repo_path =~ s#/+$##;
1074 if ($repo_path =~ m#^[a-z\+]+://#) {
1075 $ra = Git::SVN::Ra->new($repo_path);
1076 $repo_path = '';
1077 } else {
1078 $repo_path =~ s#^/+##;
1079 unless ($ra) {
1080 fatal("E: '$repo_path' is not a complete URL ",
1081 "and a separate URL is not specified");
1084 my $url = $ra->{url};
1085 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1086 my $k = "svn-remote.$gs->{repo_id}.url";
1087 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1088 if ($orig_url && ($orig_url ne $gs->{url})) {
1089 die "$k already set: $orig_url\n",
1090 "wanted to set to: $gs->{url}\n";
1092 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1093 my $remote_path = "$ra->{svn_path}/$repo_path";
1094 $remote_path =~ s#/+#/#g;
1095 $remote_path =~ s#^/##g;
1096 $remote_path .= "/*" if $remote_path !~ /\*/;
1097 my ($n) = ($switch =~ /^--(\w+)/);
1098 if (length $pfx && $pfx !~ m#/$#) {
1099 die "--prefix='$pfx' must have a trailing slash '/'\n";
1101 command_noisy('config',
1102 "svn-remote.$gs->{repo_id}.$n",
1103 "$remote_path:refs/remotes/$pfx*" .
1104 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1107 sub verify_ref {
1108 my ($ref) = @_;
1109 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1110 { STDERR => 0 }); };
1113 sub get_tree_from_treeish {
1114 my ($treeish) = @_;
1115 # $treeish can be a symbolic ref, too:
1116 my $type = command_oneline(qw/cat-file -t/, $treeish);
1117 my $expected;
1118 while ($type eq 'tag') {
1119 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1121 if ($type eq 'commit') {
1122 $expected = (grep /^tree /, command(qw/cat-file commit/,
1123 $treeish))[0];
1124 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1125 die "Unable to get tree from $treeish\n" unless $expected;
1126 } elsif ($type eq 'tree') {
1127 $expected = $treeish;
1128 } else {
1129 die "$treeish is a $type, expected tree, tag or commit\n";
1131 return $expected;
1134 sub get_commit_entry {
1135 my ($treeish) = shift;
1136 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1137 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1138 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1139 open my $log_fh, '>', $commit_editmsg or croak $!;
1141 my $type = command_oneline(qw/cat-file -t/, $treeish);
1142 if ($type eq 'commit' || $type eq 'tag') {
1143 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1144 $type, $treeish);
1145 my $in_msg = 0;
1146 my $author;
1147 my $saw_from = 0;
1148 my $msgbuf = "";
1149 while (<$msg_fh>) {
1150 if (!$in_msg) {
1151 $in_msg = 1 if (/^\s*$/);
1152 $author = $1 if (/^author (.*>)/);
1153 } elsif (/^git-svn-id: /) {
1154 # skip this for now, we regenerate the
1155 # correct one on re-fetch anyways
1156 # TODO: set *:merge properties or like...
1157 } else {
1158 if (/^From:/ || /^Signed-off-by:/) {
1159 $saw_from = 1;
1161 $msgbuf .= $_;
1164 $msgbuf =~ s/\s+$//s;
1165 if ($Git::SVN::_add_author_from && defined($author)
1166 && !$saw_from) {
1167 $msgbuf .= "\n\nFrom: $author";
1169 print $log_fh $msgbuf or croak $!;
1170 command_close_pipe($msg_fh, $ctx);
1172 close $log_fh or croak $!;
1174 if ($_edit || ($type eq 'tree')) {
1175 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1176 # TODO: strip out spaces, comments, like git-commit.sh
1177 system($editor, $commit_editmsg);
1179 rename $commit_editmsg, $commit_msg or croak $!;
1181 require Encode;
1182 # SVN requires messages to be UTF-8 when entering the repo
1183 local $/;
1184 open $log_fh, '<', $commit_msg or croak $!;
1185 binmode $log_fh;
1186 chomp($log_entry{log} = <$log_fh>);
1188 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1189 my $msg = $log_entry{log};
1191 eval { $msg = Encode::decode($enc, $msg, 1) };
1192 if ($@) {
1193 die "Could not decode as $enc:\n", $msg,
1194 "\nPerhaps you need to set i18n.commitencoding\n";
1197 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1198 die "Could not encode as UTF-8:\n$msg\n" if $@;
1200 $log_entry{log} = $msg;
1202 close $log_fh or croak $!;
1204 unlink $commit_msg;
1205 \%log_entry;
1208 sub s_to_file {
1209 my ($str, $file, $mode) = @_;
1210 open my $fd,'>',$file or croak $!;
1211 print $fd $str,"\n" or croak $!;
1212 close $fd or croak $!;
1213 chmod ($mode &~ umask, $file) if (defined $mode);
1216 sub file_to_s {
1217 my $file = shift;
1218 open my $fd,'<',$file or croak "$!: file: $file\n";
1219 local $/;
1220 my $ret = <$fd>;
1221 close $fd or croak $!;
1222 $ret =~ s/\s*$//s;
1223 return $ret;
1226 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1227 sub load_authors {
1228 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1229 my $log = $cmd eq 'log';
1230 while (<$authors>) {
1231 chomp;
1232 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1233 my ($user, $name, $email) = ($1, $2, $3);
1234 if ($log) {
1235 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1236 } else {
1237 $users{$user} = [$name, $email];
1240 close $authors or croak $!;
1243 # convert GetOpt::Long specs for use by git-config
1244 sub read_repo_config {
1245 return unless -d $ENV{GIT_DIR};
1246 my $opts = shift;
1247 my @config_only;
1248 foreach my $o (keys %$opts) {
1249 # if we have mixedCase and a long option-only, then
1250 # it's a config-only variable that we don't need for
1251 # the command-line.
1252 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1253 my $v = $opts->{$o};
1254 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1255 $key =~ s/-//g;
1256 my $arg = 'git config';
1257 $arg .= ' --int' if ($o =~ /[:=]i$/);
1258 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1259 if (ref $v eq 'ARRAY') {
1260 chomp(my @tmp = `$arg --get-all svn.$key`);
1261 @$v = @tmp if @tmp;
1262 } else {
1263 chomp(my $tmp = `$arg --get svn.$key`);
1264 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1265 $$v = $tmp;
1269 delete @$opts{@config_only} if @config_only;
1272 sub extract_metadata {
1273 my $id = shift or return (undef, undef, undef);
1274 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1275 \s([a-f\d\-]+)$/x);
1276 if (!defined $rev || !$uuid || !$url) {
1277 # some of the original repositories I made had
1278 # identifiers like this:
1279 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1281 return ($url, $rev, $uuid);
1284 sub cmt_metadata {
1285 return extract_metadata((grep(/^git-svn-id: /,
1286 command(qw/cat-file commit/, shift)))[-1]);
1289 sub cmt_sha2rev_batch {
1290 my %s2r;
1291 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1292 my $list = shift;
1294 foreach my $sha (@{$list}) {
1295 my $first = 1;
1296 my $size = 0;
1297 print $out $sha, "\n";
1299 while (my $line = <$in>) {
1300 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1301 last;
1302 } elsif ($first &&
1303 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1304 $first = 0;
1305 $size = $1;
1306 next;
1307 } elsif ($line =~ /^(git-svn-id: )/) {
1308 my (undef, $rev, undef) =
1309 extract_metadata($line);
1310 $s2r{$sha} = $rev;
1313 $size -= length($line);
1314 last if ($size == 0);
1318 command_close_bidi_pipe($pid, $in, $out, $ctx);
1320 return \%s2r;
1323 sub working_head_info {
1324 my ($head, $refs) = @_;
1325 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1326 my ($fh, $ctx) = command_output_pipe(@args, $head);
1327 my $hash;
1328 my %max;
1329 while (<$fh>) {
1330 if ( m{^commit ($::sha1)$} ) {
1331 unshift @$refs, $hash if $hash and $refs;
1332 $hash = $1;
1333 next;
1335 next unless s{^\s*(git-svn-id:)}{$1};
1336 my ($url, $rev, $uuid) = extract_metadata($_);
1337 if (defined $url && defined $rev) {
1338 next if $max{$url} and $max{$url} < $rev;
1339 if (my $gs = Git::SVN->find_by_url($url)) {
1340 my $c = $gs->rev_map_get($rev, $uuid);
1341 if ($c && $c eq $hash) {
1342 close $fh; # break the pipe
1343 return ($url, $rev, $uuid, $gs);
1344 } else {
1345 $max{$url} ||= $gs->rev_map_max;
1350 command_close_pipe($fh, $ctx);
1351 (undef, undef, undef, undef);
1354 sub read_commit_parents {
1355 my ($parents, $c) = @_;
1356 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1357 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1358 @{$parents->{$c}} = split(/ /, $p);
1361 sub linearize_history {
1362 my ($gs, $refs) = @_;
1363 my %parents;
1364 foreach my $c (@$refs) {
1365 read_commit_parents(\%parents, $c);
1368 my @linear_refs;
1369 my %skip = ();
1370 my $last_svn_commit = $gs->last_commit;
1371 foreach my $c (reverse @$refs) {
1372 next if $c eq $last_svn_commit;
1373 last if $skip{$c};
1375 unshift @linear_refs, $c;
1376 $skip{$c} = 1;
1378 # we only want the first parent to diff against for linear
1379 # history, we save the rest to inject when we finalize the
1380 # svn commit
1381 my $fp_a = verify_ref("$c~1");
1382 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1383 if (!$fp_a || !$fp_b) {
1384 die "Commit $c\n",
1385 "has no parent commit, and therefore ",
1386 "nothing to diff against.\n",
1387 "You should be working from a repository ",
1388 "originally created by git-svn\n";
1390 if ($fp_a ne $fp_b) {
1391 die "$c~1 = $fp_a, however parsing commit $c ",
1392 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1395 foreach my $p (@{$parents{$c}}) {
1396 $skip{$p} = 1;
1399 (\@linear_refs, \%parents);
1402 sub find_file_type_and_diff_status {
1403 my ($path) = @_;
1404 return ('dir', '') if $path eq '';
1406 my $diff_output =
1407 command_oneline(qw(diff --cached --name-status --), $path) || "";
1408 my $diff_status = (split(' ', $diff_output))[0] || "";
1410 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1412 return (undef, undef) if !$diff_status && !$ls_tree;
1414 if ($diff_status eq "A") {
1415 return ("link", $diff_status) if -l $path;
1416 return ("dir", $diff_status) if -d $path;
1417 return ("file", $diff_status);
1420 my $mode = (split(' ', $ls_tree))[0] || "";
1422 return ("link", $diff_status) if $mode eq "120000";
1423 return ("dir", $diff_status) if $mode eq "040000";
1424 return ("file", $diff_status);
1427 sub md5sum {
1428 my $arg = shift;
1429 my $ref = ref $arg;
1430 my $md5 = Digest::MD5->new();
1431 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1432 $md5->addfile($arg) or croak $!;
1433 } elsif ($ref eq 'SCALAR') {
1434 $md5->add($$arg) or croak $!;
1435 } elsif (!$ref) {
1436 $md5->add($arg) or croak $!;
1437 } else {
1438 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1440 return $md5->hexdigest();
1443 package Git::SVN;
1444 use strict;
1445 use warnings;
1446 use Fcntl qw/:DEFAULT :seek/;
1447 use constant rev_map_fmt => 'NH40';
1448 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1449 $_repack $_repack_flags $_use_svm_props $_head
1450 $_use_svnsync_props $no_reuse_existing $_minimize_url
1451 $_use_log_author $_add_author_from $_localtime/;
1452 use Carp qw/croak/;
1453 use File::Path qw/mkpath/;
1454 use File::Copy qw/copy/;
1455 use IPC::Open3;
1457 my ($_gc_nr, $_gc_period);
1459 # properties that we do not log:
1460 my %SKIP_PROP;
1461 BEGIN {
1462 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1463 svn:special svn:executable
1464 svn:entry:committed-rev
1465 svn:entry:last-author
1466 svn:entry:uuid
1467 svn:entry:committed-date/;
1469 # some options are read globally, but can be overridden locally
1470 # per [svn-remote "..."] section. Command-line options will *NOT*
1471 # override options set in an [svn-remote "..."] section
1472 no strict 'refs';
1473 for my $option (qw/follow_parent no_metadata use_svm_props
1474 use_svnsync_props/) {
1475 my $key = $option;
1476 $key =~ tr/_//d;
1477 my $prop = "-$option";
1478 *$option = sub {
1479 my ($self) = @_;
1480 return $self->{$prop} if exists $self->{$prop};
1481 my $k = "svn-remote.$self->{repo_id}.$key";
1482 eval { command_oneline(qw/config --get/, $k) };
1483 if ($@) {
1484 $self->{$prop} = ${"Git::SVN::_$option"};
1485 } else {
1486 my $v = command_oneline(qw/config --bool/,$k);
1487 $self->{$prop} = $v eq 'false' ? 0 : 1;
1489 return $self->{$prop};
1495 my (%LOCKFILES, %INDEX_FILES);
1496 END {
1497 unlink keys %LOCKFILES if %LOCKFILES;
1498 unlink keys %INDEX_FILES if %INDEX_FILES;
1501 sub resolve_local_globs {
1502 my ($url, $fetch, $glob_spec) = @_;
1503 return unless defined $glob_spec;
1504 my $ref = $glob_spec->{ref};
1505 my $path = $glob_spec->{path};
1506 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1507 next unless m#^refs/remotes/$ref->{regex}$#;
1508 my $p = $1;
1509 my $pathname = desanitize_refname($path->full_path($p));
1510 my $refname = desanitize_refname($ref->full_path($p));
1511 if (my $existing = $fetch->{$pathname}) {
1512 if ($existing ne $refname) {
1513 die "Refspec conflict:\n",
1514 "existing: refs/remotes/$existing\n",
1515 " globbed: refs/remotes/$refname\n";
1517 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1518 $u =~ s!^\Q$url\E(/|$)!! or die
1519 "refs/remotes/$refname: '$url' not found in '$u'\n";
1520 if ($pathname ne $u) {
1521 warn "W: Refspec glob conflict ",
1522 "(ref: refs/remotes/$refname):\n",
1523 "expected path: $pathname\n",
1524 " real path: $u\n",
1525 "Continuing ahead with $u\n";
1526 next;
1528 } else {
1529 $fetch->{$pathname} = $refname;
1534 sub parse_revision_argument {
1535 my ($base, $head) = @_;
1536 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1537 return ($base, $head);
1539 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1540 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1541 return ($head, $head) if ($::_revision eq 'HEAD');
1542 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1543 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1544 die "revision argument: $::_revision not understood by git-svn\n";
1547 sub fetch_all {
1548 my ($repo_id, $remotes) = @_;
1549 if (ref $repo_id) {
1550 my $gs = $repo_id;
1551 $repo_id = undef;
1552 $repo_id = $gs->{repo_id};
1554 $remotes ||= read_all_remotes();
1555 my $remote = $remotes->{$repo_id} or
1556 die "[svn-remote \"$repo_id\"] unknown\n";
1557 my $fetch = $remote->{fetch};
1558 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1559 my (@gs, @globs);
1560 my $ra = Git::SVN::Ra->new($url);
1561 my $uuid = $ra->get_uuid;
1562 my $head = $ra->get_latest_revnum;
1563 my $base = defined $fetch ? $head : 0;
1565 # read the max revs for wildcard expansion (branches/*, tags/*)
1566 foreach my $t (qw/branches tags/) {
1567 defined $remote->{$t} or next;
1568 push @globs, $remote->{$t};
1569 my $max_rev = eval { tmp_config(qw/--int --get/,
1570 "svn-remote.$repo_id.${t}-maxRev") };
1571 if (defined $max_rev && ($max_rev < $base)) {
1572 $base = $max_rev;
1573 } elsif (!defined $max_rev) {
1574 $base = 0;
1578 if ($fetch) {
1579 foreach my $p (sort keys %$fetch) {
1580 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1581 my $lr = $gs->rev_map_max;
1582 if (defined $lr) {
1583 $base = $lr if ($lr < $base);
1585 push @gs, $gs;
1589 ($base, $head) = parse_revision_argument($base, $head);
1590 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1593 sub read_all_remotes {
1594 my $r = {};
1595 my $use_svm_props = eval { command_oneline(qw/config --bool
1596 svn.useSvmProps/) };
1597 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1598 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1599 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1600 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1601 die("svn-remote.$remote: remote ref '$_remote_ref' "
1602 . "must start with 'refs/remotes/'\n")
1603 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1604 my $remote_ref = $1;
1605 $local_ref =~ s{^/}{};
1606 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1607 $r->{$remote}->{svm} = {} if $use_svm_props;
1608 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1609 $r->{$1}->{svm} = {};
1610 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1611 $r->{$1}->{url} = $2;
1612 } elsif (m!^(.+)\.(branches|tags)=
1613 (.*):refs/remotes/(.+)\s*$/!x) {
1614 my ($p, $g) = ($3, $4);
1615 my $rs = $r->{$1}->{$2} = {
1616 t => $2,
1617 remote => $1,
1618 path => Git::SVN::GlobSpec->new($p),
1619 ref => Git::SVN::GlobSpec->new($g) };
1620 if (length($rs->{ref}->{right}) != 0) {
1621 die "The '*' glob character must be the last ",
1622 "character of '$g'\n";
1627 map {
1628 if (defined $r->{$_}->{svm}) {
1629 my $svm;
1630 eval {
1631 my $section = "svn-remote.$_";
1632 $svm = {
1633 source => tmp_config('--get',
1634 "$section.svm-source"),
1635 replace => tmp_config('--get',
1636 "$section.svm-replace"),
1639 $r->{$_}->{svm} = $svm;
1641 } keys %$r;
1646 sub init_vars {
1647 $_gc_nr = $_gc_period = 1000;
1648 if (defined $_repack || defined $_repack_flags) {
1649 warn "Repack options are obsolete; they have no effect.\n";
1653 sub verify_remotes_sanity {
1654 return unless -d $ENV{GIT_DIR};
1655 my %seen;
1656 foreach (command(qw/config -l/)) {
1657 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1658 if ($seen{$1}) {
1659 die "Remote ref refs/remote/$1 is tracked by",
1660 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1661 "Please resolve this ambiguity in ",
1662 "your git configuration file before ",
1663 "continuing\n";
1665 $seen{$1} = $_;
1670 sub find_existing_remote {
1671 my ($url, $remotes) = @_;
1672 return undef if $no_reuse_existing;
1673 my $existing;
1674 foreach my $repo_id (keys %$remotes) {
1675 my $u = $remotes->{$repo_id}->{url} or next;
1676 next if $u ne $url;
1677 $existing = $repo_id;
1678 last;
1680 $existing;
1683 sub init_remote_config {
1684 my ($self, $url, $no_write) = @_;
1685 $url =~ s!/+$!!; # strip trailing slash
1686 my $r = read_all_remotes();
1687 my $existing = find_existing_remote($url, $r);
1688 if ($existing) {
1689 unless ($no_write) {
1690 print STDERR "Using existing ",
1691 "[svn-remote \"$existing\"]\n";
1693 $self->{repo_id} = $existing;
1694 } elsif ($_minimize_url) {
1695 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1696 $existing = find_existing_remote($min_url, $r);
1697 if ($existing) {
1698 unless ($no_write) {
1699 print STDERR "Using existing ",
1700 "[svn-remote \"$existing\"]\n";
1702 $self->{repo_id} = $existing;
1704 if ($min_url ne $url) {
1705 unless ($no_write) {
1706 print STDERR "Using higher level of URL: ",
1707 "$url => $min_url\n";
1709 my $old_path = $self->{path};
1710 $self->{path} = $url;
1711 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1712 if (length $old_path) {
1713 $self->{path} .= "/$old_path";
1715 $url = $min_url;
1718 my $orig_url;
1719 if (!$existing) {
1720 # verify that we aren't overwriting anything:
1721 $orig_url = eval {
1722 command_oneline('config', '--get',
1723 "svn-remote.$self->{repo_id}.url")
1725 if ($orig_url && ($orig_url ne $url)) {
1726 die "svn-remote.$self->{repo_id}.url already set: ",
1727 "$orig_url\nwanted to set to: $url\n";
1730 my ($xrepo_id, $xpath) = find_ref($self->refname);
1731 if (defined $xpath) {
1732 die "svn-remote.$xrepo_id.fetch already set to track ",
1733 "$xpath:refs/remotes/", $self->refname, "\n";
1735 unless ($no_write) {
1736 command_noisy('config',
1737 "svn-remote.$self->{repo_id}.url", $url);
1738 $self->{path} =~ s{^/}{};
1739 command_noisy('config', '--add',
1740 "svn-remote.$self->{repo_id}.fetch",
1741 "$self->{path}:".$self->refname);
1743 $self->{url} = $url;
1746 sub find_by_url { # repos_root and, path are optional
1747 my ($class, $full_url, $repos_root, $path) = @_;
1749 return undef unless defined $full_url;
1750 remove_username($full_url);
1751 remove_username($repos_root) if defined $repos_root;
1752 my $remotes = read_all_remotes();
1753 if (defined $full_url && defined $repos_root && !defined $path) {
1754 $path = $full_url;
1755 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1757 foreach my $repo_id (keys %$remotes) {
1758 my $u = $remotes->{$repo_id}->{url} or next;
1759 remove_username($u);
1760 next if defined $repos_root && $repos_root ne $u;
1762 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1763 foreach (qw/branches tags/) {
1764 resolve_local_globs($u, $fetch,
1765 $remotes->{$repo_id}->{$_});
1767 my $p = $path;
1768 my $rwr = rewrite_root({repo_id => $repo_id});
1769 my $svm = $remotes->{$repo_id}->{svm}
1770 if defined $remotes->{$repo_id}->{svm};
1771 unless (defined $p) {
1772 $p = $full_url;
1773 my $z = $u;
1774 my $prefix = '';
1775 if ($rwr) {
1776 $z = $rwr;
1777 remove_username($z);
1778 } elsif (defined $svm) {
1779 $z = $svm->{source};
1780 $prefix = $svm->{replace};
1781 $prefix =~ s#^\Q$u\E(?:/|$)##;
1782 $prefix =~ s#/$##;
1784 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1786 foreach my $f (keys %$fetch) {
1787 next if $f ne $p;
1788 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1791 undef;
1794 sub init {
1795 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1796 my $self = _new($class, $repo_id, $ref_id, $path);
1797 if (defined $url) {
1798 $self->init_remote_config($url, $no_write);
1800 $self;
1803 sub find_ref {
1804 my ($ref_id) = @_;
1805 foreach (command(qw/config -l/)) {
1806 next unless m!^svn-remote\.(.+)\.fetch=
1807 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1808 my ($repo_id, $path, $ref) = ($1, $2, $3);
1809 if ($ref eq $ref_id) {
1810 $path = '' if ($path =~ m#^\./?#);
1811 return ($repo_id, $path);
1814 (undef, undef, undef);
1817 sub new {
1818 my ($class, $ref_id, $repo_id, $path) = @_;
1819 if (defined $ref_id && !defined $repo_id && !defined $path) {
1820 ($repo_id, $path) = find_ref($ref_id);
1821 if (!defined $repo_id) {
1822 die "Could not find a \"svn-remote.*.fetch\" key ",
1823 "in the repository configuration matching: ",
1824 "refs/remotes/$ref_id\n";
1827 my $self = _new($class, $repo_id, $ref_id, $path);
1828 if (!defined $self->{path} || !length $self->{path}) {
1829 my $fetch = command_oneline('config', '--get',
1830 "svn-remote.$repo_id.fetch",
1831 ":refs/remotes/$ref_id\$") or
1832 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1833 "\":refs/remotes/$ref_id\$\" in config\n";
1834 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1836 $self->{url} = command_oneline('config', '--get',
1837 "svn-remote.$repo_id.url") or
1838 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1839 $self->rebuild;
1840 $self;
1843 sub refname {
1844 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1846 # It cannot end with a slash /, we'll throw up on this because
1847 # SVN can't have directories with a slash in their name, either:
1848 if ($refname =~ m{/$}) {
1849 die "ref: '$refname' ends with a trailing slash, this is ",
1850 "not permitted by git nor Subversion\n";
1853 # It cannot have ASCII control character space, tilde ~, caret ^,
1854 # colon :, question-mark ?, asterisk *, space, or open bracket [
1855 # anywhere.
1857 # Additionally, % must be escaped because it is used for escaping
1858 # and we want our escaped refname to be reversible
1859 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1861 # no slash-separated component can begin with a dot .
1862 # /.* becomes /%2E*
1863 $refname =~ s{/\.}{/%2E}g;
1865 # It cannot have two consecutive dots .. anywhere
1866 # .. becomes %2E%2E
1867 $refname =~ s{\.\.}{%2E%2E}g;
1869 return $refname;
1872 sub desanitize_refname {
1873 my ($refname) = @_;
1874 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1875 return $refname;
1878 sub svm_uuid {
1879 my ($self) = @_;
1880 return $self->{svm}->{uuid} if $self->svm;
1881 $self->ra;
1882 unless ($self->{svm}) {
1883 die "SVM UUID not cached, and reading remotely failed\n";
1885 $self->{svm}->{uuid};
1888 sub svm {
1889 my ($self) = @_;
1890 return $self->{svm} if $self->{svm};
1891 my $svm;
1892 # see if we have it in our config, first:
1893 eval {
1894 my $section = "svn-remote.$self->{repo_id}";
1895 $svm = {
1896 source => tmp_config('--get', "$section.svm-source"),
1897 uuid => tmp_config('--get', "$section.svm-uuid"),
1898 replace => tmp_config('--get', "$section.svm-replace"),
1901 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1902 $self->{svm} = $svm;
1904 $self->{svm};
1907 sub _set_svm_vars {
1908 my ($self, $ra) = @_;
1909 return $ra if $self->svm;
1911 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1912 "(svm:source, svm:uuid) ",
1913 "from the following URLs:\n" );
1914 sub read_svm_props {
1915 my ($self, $ra, $path, $r) = @_;
1916 my $props = ($ra->get_dir($path, $r))[2];
1917 my $src = $props->{'svm:source'};
1918 my $uuid = $props->{'svm:uuid'};
1919 return undef if (!$src || !$uuid);
1921 chomp($src, $uuid);
1923 $uuid =~ m{^[0-9a-f\-]{30,}$}
1924 or die "doesn't look right - svm:uuid is '$uuid'\n";
1926 # the '!' is used to mark the repos_root!/relative/path
1927 $src =~ s{/?!/?}{/};
1928 $src =~ s{/+$}{}; # no trailing slashes please
1929 # username is of no interest
1930 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1932 my $replace = $ra->{url};
1933 $replace .= "/$path" if length $path;
1935 my $section = "svn-remote.$self->{repo_id}";
1936 tmp_config("$section.svm-source", $src);
1937 tmp_config("$section.svm-replace", $replace);
1938 tmp_config("$section.svm-uuid", $uuid);
1939 $self->{svm} = {
1940 source => $src,
1941 uuid => $uuid,
1942 replace => $replace
1946 my $r = $ra->get_latest_revnum;
1947 my $path = $self->{path};
1948 my %tried;
1949 while (length $path) {
1950 unless ($tried{"$self->{url}/$path"}) {
1951 return $ra if $self->read_svm_props($ra, $path, $r);
1952 $tried{"$self->{url}/$path"} = 1;
1954 $path =~ s#/?[^/]+$##;
1956 die "Path: '$path' should be ''\n" if $path ne '';
1957 return $ra if $self->read_svm_props($ra, $path, $r);
1958 $tried{"$self->{url}/$path"} = 1;
1960 if ($ra->{repos_root} eq $self->{url}) {
1961 die @err, (map { " $_\n" } keys %tried), "\n";
1964 # nope, make sure we're connected to the repository root:
1965 my $ok;
1966 my @tried_b;
1967 $path = $ra->{svn_path};
1968 $ra = Git::SVN::Ra->new($ra->{repos_root});
1969 while (length $path) {
1970 unless ($tried{"$ra->{url}/$path"}) {
1971 $ok = $self->read_svm_props($ra, $path, $r);
1972 last if $ok;
1973 $tried{"$ra->{url}/$path"} = 1;
1975 $path =~ s#/?[^/]+$##;
1977 die "Path: '$path' should be ''\n" if $path ne '';
1978 $ok ||= $self->read_svm_props($ra, $path, $r);
1979 $tried{"$ra->{url}/$path"} = 1;
1980 if (!$ok) {
1981 die @err, (map { " $_\n" } keys %tried), "\n";
1983 Git::SVN::Ra->new($self->{url});
1986 sub svnsync {
1987 my ($self) = @_;
1988 return $self->{svnsync} if $self->{svnsync};
1990 if ($self->no_metadata) {
1991 die "Can't have both 'noMetadata' and ",
1992 "'useSvnsyncProps' options set!\n";
1994 if ($self->rewrite_root) {
1995 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1996 "options set!\n";
1999 my $svnsync;
2000 # see if we have it in our config, first:
2001 eval {
2002 my $section = "svn-remote.$self->{repo_id}";
2004 my $url = tmp_config('--get', "$section.svnsync-url");
2005 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2006 die "doesn't look right - svn:sync-from-url is '$url'\n";
2008 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2009 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2010 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2012 $svnsync = { url => $url, uuid => $uuid }
2014 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2015 return $self->{svnsync} = $svnsync;
2018 my $err = "useSvnsyncProps set, but failed to read " .
2019 "svnsync property: svn:sync-from-";
2020 my $rp = $self->ra->rev_proplist(0);
2022 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2023 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2024 die "doesn't look right - svn:sync-from-url is '$url'\n";
2026 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2027 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2028 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2030 my $section = "svn-remote.$self->{repo_id}";
2031 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2032 tmp_config('--add', "$section.svnsync-url", $url);
2033 return $self->{svnsync} = { url => $url, uuid => $uuid };
2036 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2037 # remote lookup (useful for 'git svn log').
2038 sub ra_uuid {
2039 my ($self) = @_;
2040 unless ($self->{ra_uuid}) {
2041 my $key = "svn-remote.$self->{repo_id}.uuid";
2042 my $uuid = eval { tmp_config('--get', $key) };
2043 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2044 $self->{ra_uuid} = $uuid;
2045 } else {
2046 die "ra_uuid called without URL\n" unless $self->{url};
2047 $self->{ra_uuid} = $self->ra->get_uuid;
2048 tmp_config('--add', $key, $self->{ra_uuid});
2051 $self->{ra_uuid};
2054 sub _set_repos_root {
2055 my ($self, $repos_root) = @_;
2056 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2057 $repos_root ||= $self->ra->{repos_root};
2058 tmp_config($k, $repos_root);
2059 $repos_root;
2062 sub repos_root {
2063 my ($self) = @_;
2064 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2065 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2068 sub ra {
2069 my ($self) = shift;
2070 my $ra = Git::SVN::Ra->new($self->{url});
2071 $self->_set_repos_root($ra->{repos_root});
2072 if ($self->use_svm_props && !$self->{svm}) {
2073 if ($self->no_metadata) {
2074 die "Can't have both 'noMetadata' and ",
2075 "'useSvmProps' options set!\n";
2076 } elsif ($self->use_svnsync_props) {
2077 die "Can't have both 'useSvnsyncProps' and ",
2078 "'useSvmProps' options set!\n";
2080 $ra = $self->_set_svm_vars($ra);
2081 $self->{-want_revprops} = 1;
2083 $ra;
2086 sub rel_path {
2087 my ($self) = @_;
2088 my $repos_root = $self->ra->{repos_root};
2089 return $self->{path} if ($self->{url} eq $repos_root);
2090 my $url = $self->{url} .
2091 (length $self->{path} ? "/$self->{path}" : $self->{path});
2092 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2093 $url;
2096 # prop_walk(PATH, REV, SUB)
2097 # -------------------------
2098 # Recursively traverse PATH at revision REV and invoke SUB for each
2099 # directory that contains a SVN property. SUB will be invoked as
2100 # follows: &SUB(gs, path, props); where `gs' is this instance of
2101 # Git::SVN, `path' the path to the directory where the properties
2102 # `props' were found. The `path' will be relative to point of checkout,
2103 # that is, if url://repo/trunk is the current Git branch, and that
2104 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2105 # as `path' (note the trailing `/').
2106 sub prop_walk {
2107 my ($self, $path, $rev, $sub) = @_;
2109 $path =~ s#^/##;
2110 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2111 $path =~ s#^/*#/#g;
2112 my $p = $path;
2113 # Strip the irrelevant part of the path.
2114 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2115 # Ensure the path is terminated by a `/'.
2116 $p =~ s#/*$#/#;
2118 # The properties contain all the internal SVN stuff nobody
2119 # (usually) cares about.
2120 my $interesting_props = 0;
2121 foreach (keys %{$props}) {
2122 # If it doesn't start with `svn:', it must be a
2123 # user-defined property.
2124 ++$interesting_props and next if $_ !~ /^svn:/;
2125 # FIXME: Fragile, if SVN adds new public properties,
2126 # this needs to be updated.
2127 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2128 |eol-style|mime-type
2129 |externals|needs-lock)$/x;
2131 &$sub($self, $p, $props) if $interesting_props;
2133 foreach (sort keys %$dirent) {
2134 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2135 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2139 sub last_rev { ($_[0]->last_rev_commit)[0] }
2140 sub last_commit { ($_[0]->last_rev_commit)[1] }
2142 # returns the newest SVN revision number and newest commit SHA1
2143 sub last_rev_commit {
2144 my ($self) = @_;
2145 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2146 return ($self->{last_rev}, $self->{last_commit});
2148 my $c = ::verify_ref($self->refname.'^0');
2149 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2150 my $rev = (::cmt_metadata($c))[1];
2151 if (defined $rev) {
2152 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2153 return ($rev, $c);
2156 my $map_path = $self->map_path;
2157 unless (-e $map_path) {
2158 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2159 return (undef, undef);
2161 my ($rev, $commit) = $self->rev_map_max(1);
2162 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2163 return ($rev, $commit);
2166 sub get_fetch_range {
2167 my ($self, $min, $max) = @_;
2168 $max ||= $self->ra->get_latest_revnum;
2169 $min ||= $self->rev_map_max;
2170 (++$min, $max);
2173 sub tmp_config {
2174 my (@args) = @_;
2175 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2176 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2177 if (! -f $config && -f $old_def_config) {
2178 rename $old_def_config, $config or
2179 die "Failed rename $old_def_config => $config: $!\n";
2181 my $old_config = $ENV{GIT_CONFIG};
2182 $ENV{GIT_CONFIG} = $config;
2183 $@ = undef;
2184 my @ret = eval {
2185 unless (-f $config) {
2186 mkfile($config);
2187 open my $fh, '>', $config or
2188 die "Can't open $config: $!\n";
2189 print $fh "; This file is used internally by ",
2190 "git-svn\n" or die
2191 "Couldn't write to $config: $!\n";
2192 print $fh "; You should not have to edit it\n" or
2193 die "Couldn't write to $config: $!\n";
2194 close $fh or die "Couldn't close $config: $!\n";
2196 command('config', @args);
2198 my $err = $@;
2199 if (defined $old_config) {
2200 $ENV{GIT_CONFIG} = $old_config;
2201 } else {
2202 delete $ENV{GIT_CONFIG};
2204 die $err if $err;
2205 wantarray ? @ret : $ret[0];
2208 sub tmp_index_do {
2209 my ($self, $sub) = @_;
2210 my $old_index = $ENV{GIT_INDEX_FILE};
2211 $ENV{GIT_INDEX_FILE} = $self->{index};
2212 $@ = undef;
2213 my @ret = eval {
2214 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2215 mkpath([$dir]) unless -d $dir;
2216 &$sub;
2218 my $err = $@;
2219 if (defined $old_index) {
2220 $ENV{GIT_INDEX_FILE} = $old_index;
2221 } else {
2222 delete $ENV{GIT_INDEX_FILE};
2224 die $err if $err;
2225 wantarray ? @ret : $ret[0];
2228 sub assert_index_clean {
2229 my ($self, $treeish) = @_;
2231 $self->tmp_index_do(sub {
2232 command_noisy('read-tree', $treeish) unless -e $self->{index};
2233 my $x = command_oneline('write-tree');
2234 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2235 /^tree ($::sha1)/mo);
2236 return if $y eq $x;
2238 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2239 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2240 command_noisy('read-tree', $treeish);
2241 $x = command_oneline('write-tree');
2242 if ($y ne $x) {
2243 ::fatal "trees ($treeish) $y != $x\n",
2244 "Something is seriously wrong...";
2249 sub get_commit_parents {
2250 my ($self, $log_entry) = @_;
2251 my (%seen, @ret, @tmp);
2252 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2253 if (my $ip = $self->{inject_parents}) {
2254 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2255 push @tmp, $commit;
2258 if (my $cur = ::verify_ref($self->refname.'^0')) {
2259 push @tmp, $cur;
2261 if (my $ipd = $self->{inject_parents_dcommit}) {
2262 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2263 push @tmp, @$commit;
2266 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2267 while (my $p = shift @tmp) {
2268 next if $seen{$p};
2269 $seen{$p} = 1;
2270 push @ret, $p;
2271 # MAXPARENT is defined to 16 in commit-tree.c:
2272 last if @ret >= 16;
2274 if (@tmp) {
2275 die "r$log_entry->{revision}: No room for parents:\n\t",
2276 join("\n\t", @tmp), "\n";
2278 @ret;
2281 sub rewrite_root {
2282 my ($self) = @_;
2283 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2284 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2285 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2286 if ($rwr) {
2287 $rwr =~ s#/+$##;
2288 if ($rwr !~ m#^[a-z\+]+://#) {
2289 die "$rwr is not a valid URL (key: $k)\n";
2292 $self->{-rewrite_root} = $rwr;
2295 sub metadata_url {
2296 my ($self) = @_;
2297 ($self->rewrite_root || $self->{url}) .
2298 (length $self->{path} ? '/' . $self->{path} : '');
2301 sub full_url {
2302 my ($self) = @_;
2303 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2307 sub set_commit_header_env {
2308 my ($log_entry) = @_;
2309 my %env;
2310 foreach my $ned (qw/NAME EMAIL DATE/) {
2311 foreach my $ac (qw/AUTHOR COMMITTER/) {
2312 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2316 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2317 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2318 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2320 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2321 ? $log_entry->{commit_name}
2322 : $log_entry->{name};
2323 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2324 ? $log_entry->{commit_email}
2325 : $log_entry->{email};
2326 \%env;
2329 sub restore_commit_header_env {
2330 my ($env) = @_;
2331 foreach my $ned (qw/NAME EMAIL DATE/) {
2332 foreach my $ac (qw/AUTHOR COMMITTER/) {
2333 my $k = "GIT_${ac}_${ned}";
2334 if (defined $env->{$k}) {
2335 $ENV{$k} = $env->{$k};
2336 } else {
2337 delete $ENV{$k};
2343 sub gc {
2344 command_noisy('gc', '--auto');
2347 sub do_git_commit {
2348 my ($self, $log_entry) = @_;
2349 my $lr = $self->last_rev;
2350 if (defined $lr && $lr >= $log_entry->{revision}) {
2351 die "Last fetched revision of ", $self->refname,
2352 " was r$lr, but we are about to fetch: ",
2353 "r$log_entry->{revision}!\n";
2355 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2356 croak "$log_entry->{revision} = $c already exists! ",
2357 "Why are we refetching it?\n";
2359 my $old_env = set_commit_header_env($log_entry);
2360 my $tree = $log_entry->{tree};
2361 if (!defined $tree) {
2362 $tree = $self->tmp_index_do(sub {
2363 command_oneline('write-tree') });
2365 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2367 my @exec = ('git', 'commit-tree', $tree);
2368 foreach ($self->get_commit_parents($log_entry)) {
2369 push @exec, '-p', $_;
2371 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2372 or croak $!;
2373 binmode $msg_fh;
2375 # we always get UTF-8 from SVN, but we may want our commits in
2376 # a different encoding.
2377 if (my $enc = Git::config('i18n.commitencoding')) {
2378 require Encode;
2379 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2381 print $msg_fh $log_entry->{log} or croak $!;
2382 restore_commit_header_env($old_env);
2383 unless ($self->no_metadata) {
2384 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2385 or croak $!;
2387 $msg_fh->flush == 0 or croak $!;
2388 close $msg_fh or croak $!;
2389 chomp(my $commit = do { local $/; <$out_fh> });
2390 close $out_fh or croak $!;
2391 waitpid $pid, 0;
2392 croak $? if $?;
2393 if ($commit !~ /^$::sha1$/o) {
2394 die "Failed to commit, invalid sha1: $commit\n";
2397 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2399 $self->{last_rev} = $log_entry->{revision};
2400 $self->{last_commit} = $commit;
2401 print "r$log_entry->{revision}" unless $::_q > 1;
2402 if (defined $log_entry->{svm_revision}) {
2403 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2404 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2405 0, $self->svm_uuid);
2407 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2408 if (--$_gc_nr == 0) {
2409 $_gc_nr = $_gc_period;
2410 gc();
2412 return $commit;
2415 sub match_paths {
2416 my ($self, $paths, $r) = @_;
2417 return 1 if $self->{path} eq '';
2418 if (my $path = $paths->{"/$self->{path}"}) {
2419 return ($path->{action} eq 'D') ? 0 : 1;
2421 my $repos_root = $self->ra->{repos_root};
2422 my $extended_path = $self->{url} . '/' . $self->{path};
2423 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2424 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2425 if (grep /$self->{path_regex}/, keys %$paths) {
2426 return 1;
2428 my $c = '';
2429 foreach (split m#/#, $self->{path}) {
2430 $c .= "/$_";
2431 next unless ($paths->{$c} &&
2432 ($paths->{$c}->{action} =~ /^[AR]$/));
2433 if ($self->ra->check_path($self->{path}, $r) ==
2434 $SVN::Node::dir) {
2435 return 1;
2438 return 0;
2441 sub find_parent_branch {
2442 my ($self, $paths, $rev) = @_;
2443 return undef unless $self->follow_parent;
2444 unless (defined $paths) {
2445 my $err_handler = $SVN::Error::handler;
2446 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2447 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2448 $paths =
2449 Git::SVN::Ra::dup_changed_paths($_[0]) });
2450 $SVN::Error::handler = $err_handler;
2452 return undef unless defined $paths;
2454 # look for a parent from another branch:
2455 my @b_path_components = split m#/#, $self->rel_path;
2456 my @a_path_components;
2457 my $i;
2458 while (@b_path_components) {
2459 $i = $paths->{'/'.join('/', @b_path_components)};
2460 last if $i && defined $i->{copyfrom_path};
2461 unshift(@a_path_components, pop(@b_path_components));
2463 return undef unless defined $i && defined $i->{copyfrom_path};
2464 my $branch_from = $i->{copyfrom_path};
2465 if (@a_path_components) {
2466 print STDERR "branch_from: $branch_from => ";
2467 $branch_from .= '/'.join('/', @a_path_components);
2468 print STDERR $branch_from, "\n";
2470 my $r = $i->{copyfrom_rev};
2471 my $repos_root = $self->ra->{repos_root};
2472 my $url = $self->ra->{url};
2473 my $new_url = $repos_root . $branch_from;
2474 print STDERR "Found possible branch point: ",
2475 "$new_url => ", $self->full_url, ", $r\n";
2476 $branch_from =~ s#^/##;
2477 my $gs = $self->other_gs($new_url, $url, $repos_root,
2478 $branch_from, $r, $self->{ref_id});
2479 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2481 my ($base, $head);
2482 if (!defined $r0 || !defined $parent) {
2483 ($base, $head) = parse_revision_argument(0, $r);
2484 } else {
2485 if ($r0 < $r) {
2486 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2487 0, 1, sub { $base = $_[1] - 1 });
2490 if (defined $base && $base <= $r) {
2491 $gs->fetch($base, $r);
2493 ($r0, $parent) = $gs->find_rev_before($r, 1);
2495 if (defined $r0 && defined $parent) {
2496 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2497 my $ed;
2498 if ($self->ra->can_do_switch) {
2499 $self->assert_index_clean($parent);
2500 print STDERR "Following parent with do_switch\n";
2501 # do_switch works with svn/trunk >= r22312, but that
2502 # is not included with SVN 1.4.3 (the latest version
2503 # at the moment), so we can't rely on it
2504 $self->{last_rev} = $r0;
2505 $self->{last_commit} = $parent;
2506 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2507 $gs->ra->gs_do_switch($r0, $rev, $gs,
2508 $self->full_url, $ed)
2509 or die "SVN connection failed somewhere...\n";
2510 } elsif ($self->ra->trees_match($new_url, $r0,
2511 $self->full_url, $rev)) {
2512 print STDERR "Trees match:\n",
2513 " $new_url\@$r0\n",
2514 " ${\$self->full_url}\@$rev\n",
2515 "Following parent with no changes\n";
2516 $self->tmp_index_do(sub {
2517 command_noisy('read-tree', $parent);
2519 $self->{last_commit} = $parent;
2520 } else {
2521 print STDERR "Following parent with do_update\n";
2522 $ed = SVN::Git::Fetcher->new($self);
2523 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2524 or die "SVN connection failed somewhere...\n";
2526 print STDERR "Successfully followed parent\n";
2527 return $self->make_log_entry($rev, [$parent], $ed);
2529 return undef;
2532 sub do_fetch {
2533 my ($self, $paths, $rev) = @_;
2534 my $ed;
2535 my ($last_rev, @parents);
2536 if (my $lc = $self->last_commit) {
2537 # we can have a branch that was deleted, then re-added
2538 # under the same name but copied from another path, in
2539 # which case we'll have multiple parents (we don't
2540 # want to break the original ref, nor lose copypath info):
2541 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2542 push @{$log_entry->{parents}}, $lc;
2543 return $log_entry;
2545 $ed = SVN::Git::Fetcher->new($self);
2546 $last_rev = $self->{last_rev};
2547 $ed->{c} = $lc;
2548 @parents = ($lc);
2549 } else {
2550 $last_rev = $rev;
2551 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2552 return $log_entry;
2554 $ed = SVN::Git::Fetcher->new($self);
2556 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2557 die "SVN connection failed somewhere...\n";
2559 $self->make_log_entry($rev, \@parents, $ed);
2562 sub get_untracked {
2563 my ($self, $ed) = @_;
2564 my @out;
2565 my $h = $ed->{empty};
2566 foreach (sort keys %$h) {
2567 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2568 push @out, " $act: " . uri_encode($_);
2569 warn "W: $act: $_\n";
2571 foreach my $t (qw/dir_prop file_prop/) {
2572 $h = $ed->{$t} or next;
2573 foreach my $path (sort keys %$h) {
2574 my $ppath = $path eq '' ? '.' : $path;
2575 foreach my $prop (sort keys %{$h->{$path}}) {
2576 next if $SKIP_PROP{$prop};
2577 my $v = $h->{$path}->{$prop};
2578 my $t_ppath_prop = "$t: " .
2579 uri_encode($ppath) . ' ' .
2580 uri_encode($prop);
2581 if (defined $v) {
2582 push @out, " +$t_ppath_prop " .
2583 uri_encode($v);
2584 } else {
2585 push @out, " -$t_ppath_prop";
2590 foreach my $t (qw/absent_file absent_directory/) {
2591 $h = $ed->{$t} or next;
2592 foreach my $parent (sort keys %$h) {
2593 foreach my $path (sort @{$h->{$parent}}) {
2594 push @out, " $t: " .
2595 uri_encode("$parent/$path");
2596 warn "W: $t: $parent/$path ",
2597 "Insufficient permissions?\n";
2601 \@out;
2604 # parse_svn_date(DATE)
2605 # --------------------
2606 # Given a date (in UTC) from Subversion, return a string in the format
2607 # "<TZ Offset> <local date/time>" that Git will use.
2609 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2610 # is true we'll convert it to the local timezone instead.
2611 sub parse_svn_date {
2612 my $date = shift || return '+0000 1970-01-01 00:00:00';
2613 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2614 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2615 croak "Unable to parse date: $date\n";
2616 my $parsed_date; # Set next.
2618 if ($Git::SVN::_localtime) {
2619 # Translate the Subversion datetime to an epoch time.
2620 # Begin by switching ourselves to $date's timezone, UTC.
2621 my $old_env_TZ = $ENV{TZ};
2622 $ENV{TZ} = 'UTC';
2624 my $epoch_in_UTC =
2625 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2627 # Determine our local timezone (including DST) at the
2628 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2629 # value of TZ, if any, at the time we were run.
2630 if (defined $Git::SVN::Log::TZ) {
2631 $ENV{TZ} = $Git::SVN::Log::TZ;
2632 } else {
2633 delete $ENV{TZ};
2636 my $our_TZ =
2637 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2639 # This converts $epoch_in_UTC into our local timezone.
2640 my ($sec, $min, $hour, $mday, $mon, $year,
2641 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2643 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2644 $our_TZ, $year + 1900, $mon + 1,
2645 $mday, $hour, $min, $sec);
2647 # Reset us to the timezone in effect when we entered
2648 # this routine.
2649 if (defined $old_env_TZ) {
2650 $ENV{TZ} = $old_env_TZ;
2651 } else {
2652 delete $ENV{TZ};
2654 } else {
2655 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2658 return $parsed_date;
2661 sub other_gs {
2662 my ($self, $new_url, $url, $repos_root,
2663 $branch_from, $r, $old_ref_id) = @_;
2664 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2665 unless ($gs) {
2666 my $ref_id = $old_ref_id;
2667 $ref_id =~ s/\@\d+$//;
2668 $ref_id .= "\@$r";
2669 # just grow a tail if we're not unique enough :x
2670 $ref_id .= '-' while find_ref($ref_id);
2671 print STDERR "Initializing parent: $ref_id\n";
2672 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2673 if ($u =~ s#^\Q$url\E(/|$)##) {
2674 $p = $u;
2675 $u = $url;
2676 $repo_id = $self->{repo_id};
2678 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2683 sub call_authors_prog {
2684 my ($orig_author) = @_;
2685 my $author = `$::_authors_prog $orig_author`;
2686 if ($? != 0) {
2687 die "$::_authors_prog failed with exit code $?\n"
2689 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2690 my ($name, $email) = ($1, $2);
2691 $email = undef if length $2 == 0;
2692 return [$name, $email];
2693 } else {
2694 die "Author: $orig_author: $::_authors_prog returned "
2695 . "invalid author format: $author\n";
2699 sub check_author {
2700 my ($author) = @_;
2701 if (!defined $author || length $author == 0) {
2702 $author = '(no author)';
2704 if (!defined $::users{$author}) {
2705 if (defined $::_authors_prog) {
2706 $::users{$author} = call_authors_prog($author);
2707 } elsif (defined $::_authors) {
2708 die "Author: $author not defined in $::_authors file\n";
2711 $author;
2714 sub make_log_entry {
2715 my ($self, $rev, $parents, $ed) = @_;
2716 my $untracked = $self->get_untracked($ed);
2718 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2719 print $un "r$rev\n" or croak $!;
2720 print $un $_, "\n" foreach @$untracked;
2721 my %log_entry = ( parents => $parents || [], revision => $rev,
2722 log => '');
2724 my $headrev;
2725 my $logged = delete $self->{logged_rev_props};
2726 if (!$logged || $self->{-want_revprops}) {
2727 my $rp = $self->ra->rev_proplist($rev);
2728 foreach (sort keys %$rp) {
2729 my $v = $rp->{$_};
2730 if (/^svn:(author|date|log)$/) {
2731 $log_entry{$1} = $v;
2732 } elsif ($_ eq 'svm:headrev') {
2733 $headrev = $v;
2734 } else {
2735 print $un " rev_prop: ", uri_encode($_), ' ',
2736 uri_encode($v), "\n";
2739 } else {
2740 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2742 close $un or croak $!;
2744 $log_entry{date} = parse_svn_date($log_entry{date});
2745 $log_entry{log} .= "\n";
2746 my $author = $log_entry{author} = check_author($log_entry{author});
2747 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2748 : ($author, undef);
2750 my ($commit_name, $commit_email) = ($name, $email);
2751 if ($_use_log_author) {
2752 my $name_field;
2753 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2754 $name_field = $1;
2755 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2756 $name_field = $1;
2758 if (!defined $name_field) {
2759 if (!defined $email) {
2760 $email = $name;
2762 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2763 ($name, $email) = ($1, $2);
2764 } elsif ($name_field =~ /(.*)@/) {
2765 ($name, $email) = ($1, $name_field);
2766 } else {
2767 ($name, $email) = ($name_field, $name_field);
2770 if (defined $headrev && $self->use_svm_props) {
2771 if ($self->rewrite_root) {
2772 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2773 "options set!\n";
2775 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2776 # we don't want "SVM: initializing mirror for junk" ...
2777 return undef if $r == 0;
2778 my $svm = $self->svm;
2779 if ($uuid ne $svm->{uuid}) {
2780 die "UUID mismatch on SVM path:\n",
2781 "expected: $svm->{uuid}\n",
2782 " got: $uuid\n";
2784 my $full_url = $self->full_url;
2785 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2786 die "Failed to replace '$svm->{replace}' with ",
2787 "'$svm->{source}' in $full_url\n";
2788 # throw away username for storing in records
2789 remove_username($full_url);
2790 $log_entry{metadata} = "$full_url\@$r $uuid";
2791 $log_entry{svm_revision} = $r;
2792 $email ||= "$author\@$uuid";
2793 $commit_email ||= "$author\@$uuid";
2794 } elsif ($self->use_svnsync_props) {
2795 my $full_url = $self->svnsync->{url};
2796 $full_url .= "/$self->{path}" if length $self->{path};
2797 remove_username($full_url);
2798 my $uuid = $self->svnsync->{uuid};
2799 $log_entry{metadata} = "$full_url\@$rev $uuid";
2800 $email ||= "$author\@$uuid";
2801 $commit_email ||= "$author\@$uuid";
2802 } else {
2803 my $url = $self->metadata_url;
2804 remove_username($url);
2805 $log_entry{metadata} = "$url\@$rev " .
2806 $self->ra->get_uuid;
2807 $email ||= "$author\@" . $self->ra->get_uuid;
2808 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2810 $log_entry{name} = $name;
2811 $log_entry{email} = $email;
2812 $log_entry{commit_name} = $commit_name;
2813 $log_entry{commit_email} = $commit_email;
2814 \%log_entry;
2817 sub fetch {
2818 my ($self, $min_rev, $max_rev, @parents) = @_;
2819 my ($last_rev, $last_commit) = $self->last_rev_commit;
2820 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2821 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2824 sub set_tree_cb {
2825 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2826 $self->{inject_parents} = { $rev => $tree };
2827 $self->fetch(undef, undef);
2830 sub set_tree {
2831 my ($self, $tree) = (shift, shift);
2832 my $log_entry = ::get_commit_entry($tree);
2833 unless ($self->{last_rev}) {
2834 ::fatal("Must have an existing revision to commit");
2836 my %ed_opts = ( r => $self->{last_rev},
2837 log => $log_entry->{log},
2838 ra => $self->ra,
2839 tree_a => $self->{last_commit},
2840 tree_b => $tree,
2841 editor_cb => sub {
2842 $self->set_tree_cb($log_entry, $tree, @_) },
2843 svn_path => $self->{path} );
2844 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2845 print "No changes\nr$self->{last_rev} = $tree\n";
2849 sub rebuild_from_rev_db {
2850 my ($self, $path) = @_;
2851 my $r = -1;
2852 open my $fh, '<', $path or croak "open: $!";
2853 binmode $fh or croak "binmode: $!";
2854 while (<$fh>) {
2855 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2856 chomp($_);
2857 ++$r;
2858 next if $_ eq ('0' x 40);
2859 $self->rev_map_set($r, $_);
2860 print "r$r = $_\n";
2862 close $fh or croak "close: $!";
2863 unlink $path or croak "unlink: $!";
2866 sub rebuild {
2867 my ($self) = @_;
2868 my $map_path = $self->map_path;
2869 my $partial = (-e $map_path && ! -z $map_path);
2870 return unless ::verify_ref($self->refname.'^0');
2871 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2872 my $rev_db = $self->rev_db_path;
2873 $self->rebuild_from_rev_db($rev_db);
2874 if ($self->use_svm_props) {
2875 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2876 $self->rebuild_from_rev_db($svm_rev_db);
2878 $self->unlink_rev_db_symlink;
2879 return;
2881 print "Rebuilding $map_path ...\n" if (!$partial);
2882 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2883 (undef, undef));
2884 my ($log, $ctx) =
2885 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2886 ($head ? "$head.." : "") . $self->refname,
2887 '--');
2888 my $metadata_url = $self->metadata_url;
2889 remove_username($metadata_url);
2890 my $svn_uuid = $self->ra_uuid;
2891 my $c;
2892 while (<$log>) {
2893 if ( m{^commit ($::sha1)$} ) {
2894 $c = $1;
2895 next;
2897 next unless s{^\s*(git-svn-id:)}{$1};
2898 my ($url, $rev, $uuid) = ::extract_metadata($_);
2899 remove_username($url);
2901 # ignore merges (from set-tree)
2902 next if (!defined $rev || !$uuid);
2904 # if we merged or otherwise started elsewhere, this is
2905 # how we break out of it
2906 if (($uuid ne $svn_uuid) ||
2907 ($metadata_url && $url && ($url ne $metadata_url))) {
2908 next;
2910 if ($partial && $head) {
2911 print "Partial-rebuilding $map_path ...\n";
2912 print "Currently at $base_rev = $head\n";
2913 $head = undef;
2916 $self->rev_map_set($rev, $c);
2917 print "r$rev = $c\n";
2919 command_close_pipe($log, $ctx);
2920 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2921 my $rev_db_path = $self->rev_db_path;
2922 if (-f $self->rev_db_path) {
2923 unlink $self->rev_db_path or croak "unlink: $!";
2925 $self->unlink_rev_db_symlink;
2928 # rev_map:
2929 # Tie::File seems to be prone to offset errors if revisions get sparse,
2930 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2931 # one of my favorite modules is out :< Next up would be one of the DBM
2932 # modules, but I'm not sure which is most portable...
2934 # This is the replacement for the rev_db format, which was too big
2935 # and inefficient for large repositories with a lot of sparse history
2936 # (mainly tags)
2938 # The format is this:
2939 # - 24 bytes for every record,
2940 # * 4 bytes for the integer representing an SVN revision number
2941 # * 20 bytes representing the sha1 of a git commit
2942 # - No empty padding records like the old format
2943 # (except the last record, which can be overwritten)
2944 # - new records are written append-only since SVN revision numbers
2945 # increase monotonically
2946 # - lookups on SVN revision number are done via a binary search
2947 # - Piping the file to xxd -c24 is a good way of dumping it for
2948 # viewing or editing (piped back through xxd -r), should the need
2949 # ever arise.
2950 # - The last record can be padding revision with an all-zero sha1
2951 # This is used to optimize fetch performance when using multiple
2952 # "fetch" directives in .git/config
2954 # These files are disposable unless noMetadata or useSvmProps is set
2956 sub _rev_map_set {
2957 my ($fh, $rev, $commit) = @_;
2959 binmode $fh or croak "binmode: $!";
2960 my $size = (stat($fh))[7];
2961 ($size % 24) == 0 or croak "inconsistent size: $size";
2963 my $wr_offset = 0;
2964 if ($size > 0) {
2965 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2966 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2967 $read == 24 or croak "read only $read bytes (!= 24)";
2968 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2969 if ($last_commit eq ('0' x40)) {
2970 if ($size >= 48) {
2971 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2972 $read = sysread($fh, $buf, 24) or
2973 croak "read: $!";
2974 $read == 24 or
2975 croak "read only $read bytes (!= 24)";
2976 ($last_rev, $last_commit) =
2977 unpack(rev_map_fmt, $buf);
2978 if ($last_commit eq ('0' x40)) {
2979 croak "inconsistent .rev_map\n";
2982 if ($last_rev >= $rev) {
2983 croak "last_rev is higher!: $last_rev >= $rev";
2985 $wr_offset = -24;
2988 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2989 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2990 croak "write: $!";
2993 sub mkfile {
2994 my ($path) = @_;
2995 unless (-e $path) {
2996 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2997 mkpath([$dir]) unless -d $dir;
2998 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2999 close $fh or die "Couldn't close (create) $path: $!\n";
3003 sub rev_map_set {
3004 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3005 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3006 my $db = $self->map_path($uuid);
3007 my $db_lock = "$db.lock";
3008 my $sig;
3009 if ($update_ref) {
3010 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3011 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3013 mkfile($db);
3015 $LOCKFILES{$db_lock} = 1;
3016 my $sync;
3017 # both of these options make our .rev_db file very, very important
3018 # and we can't afford to lose it because rebuild() won't work
3019 if ($self->use_svm_props || $self->no_metadata) {
3020 $sync = 1;
3021 copy($db, $db_lock) or die "rev_map_set(@_): ",
3022 "Failed to copy: ",
3023 "$db => $db_lock ($!)\n";
3024 } else {
3025 rename $db, $db_lock or die "rev_map_set(@_): ",
3026 "Failed to rename: ",
3027 "$db => $db_lock ($!)\n";
3030 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3031 or croak "Couldn't open $db_lock: $!\n";
3032 _rev_map_set($fh, $rev, $commit);
3033 if ($sync) {
3034 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3035 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3037 close $fh or croak $!;
3038 if ($update_ref) {
3039 $_head = $self;
3040 command_noisy('update-ref', '-m', "r$rev",
3041 $self->refname, $commit);
3043 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3044 "$db_lock => $db ($!)\n";
3045 delete $LOCKFILES{$db_lock};
3046 if ($update_ref) {
3047 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3048 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3049 kill $sig, $$ if defined $sig;
3053 # If want_commit, this will return an array of (rev, commit) where
3054 # commit _must_ be a valid commit in the archive.
3055 # Otherwise, it'll return the max revision (whether or not the
3056 # commit is valid or just a 0x40 placeholder).
3057 sub rev_map_max {
3058 my ($self, $want_commit) = @_;
3059 $self->rebuild;
3060 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3061 $want_commit ? ($r, $c) : $r;
3064 sub rev_map_max_norebuild {
3065 my ($self, $want_commit) = @_;
3066 my $map_path = $self->map_path;
3067 stat $map_path or return $want_commit ? (0, undef) : 0;
3068 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3069 binmode $fh or croak "binmode: $!";
3070 my $size = (stat($fh))[7];
3071 ($size % 24) == 0 or croak "inconsistent size: $size";
3073 if ($size == 0) {
3074 close $fh or croak "close: $!";
3075 return $want_commit ? (0, undef) : 0;
3078 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3079 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3080 my ($r, $c) = unpack(rev_map_fmt, $buf);
3081 if ($want_commit && $c eq ('0' x40)) {
3082 if ($size < 48) {
3083 return $want_commit ? (0, undef) : 0;
3085 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3086 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3087 ($r, $c) = unpack(rev_map_fmt, $buf);
3088 if ($c eq ('0'x40)) {
3089 croak "Penultimate record is all-zeroes in $map_path";
3092 close $fh or croak "close: $!";
3093 $want_commit ? ($r, $c) : $r;
3096 sub rev_map_get {
3097 my ($self, $rev, $uuid) = @_;
3098 my $map_path = $self->map_path($uuid);
3099 return undef unless -e $map_path;
3101 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3102 binmode $fh or croak "binmode: $!";
3103 my $size = (stat($fh))[7];
3104 ($size % 24) == 0 or croak "inconsistent size: $size";
3106 if ($size == 0) {
3107 close $fh or croak "close: $fh";
3108 return undef;
3111 my ($l, $u) = (0, $size - 24);
3112 my ($r, $c, $buf);
3114 while ($l <= $u) {
3115 my $i = int(($l/24 + $u/24) / 2) * 24;
3116 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3117 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3118 my ($r, $c) = unpack('NH40', $buf);
3120 if ($r < $rev) {
3121 $l = $i + 24;
3122 } elsif ($r > $rev) {
3123 $u = $i - 24;
3124 } else { # $r == $rev
3125 close($fh) or croak "close: $!";
3126 return $c eq ('0' x 40) ? undef : $c;
3129 close($fh) or croak "close: $!";
3130 undef;
3133 # Finds the first svn revision that exists on (if $eq_ok is true) or
3134 # before $rev for the current branch. It will not search any lower
3135 # than $min_rev. Returns the git commit hash and svn revision number
3136 # if found, else (undef, undef).
3137 sub find_rev_before {
3138 my ($self, $rev, $eq_ok, $min_rev) = @_;
3139 --$rev unless $eq_ok;
3140 $min_rev ||= 1;
3141 while ($rev >= $min_rev) {
3142 if (my $c = $self->rev_map_get($rev)) {
3143 return ($rev, $c);
3145 --$rev;
3147 return (undef, undef);
3150 # Finds the first svn revision that exists on (if $eq_ok is true) or
3151 # after $rev for the current branch. It will not search any higher
3152 # than $max_rev. Returns the git commit hash and svn revision number
3153 # if found, else (undef, undef).
3154 sub find_rev_after {
3155 my ($self, $rev, $eq_ok, $max_rev) = @_;
3156 ++$rev unless $eq_ok;
3157 $max_rev ||= $self->rev_map_max;
3158 while ($rev <= $max_rev) {
3159 if (my $c = $self->rev_map_get($rev)) {
3160 return ($rev, $c);
3162 ++$rev;
3164 return (undef, undef);
3167 sub _new {
3168 my ($class, $repo_id, $ref_id, $path) = @_;
3169 unless (defined $repo_id && length $repo_id) {
3170 $repo_id = $Git::SVN::default_repo_id;
3172 unless (defined $ref_id && length $ref_id) {
3173 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3175 $_[1] = $repo_id;
3176 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3177 $_[3] = $path = '' unless (defined $path);
3178 mkpath(["$ENV{GIT_DIR}/svn"]);
3179 bless {
3180 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3181 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3182 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3185 # for read-only access of old .rev_db formats
3186 sub unlink_rev_db_symlink {
3187 my ($self) = @_;
3188 my $link = $self->rev_db_path;
3189 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3190 if (-l $link) {
3191 unlink $link or croak "unlink: $link failed!";
3195 sub rev_db_path {
3196 my ($self, $uuid) = @_;
3197 my $db_path = $self->map_path($uuid);
3198 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3199 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3200 $db_path;
3203 # the new replacement for .rev_db
3204 sub map_path {
3205 my ($self, $uuid) = @_;
3206 $uuid ||= $self->ra_uuid;
3207 "$self->{map_root}.$uuid";
3210 sub uri_encode {
3211 my ($f) = @_;
3212 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3216 sub remove_username {
3217 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3220 package Git::SVN::Prompt;
3221 use strict;
3222 use warnings;
3223 require SVN::Core;
3224 use vars qw/$_no_auth_cache $_username/;
3226 sub simple {
3227 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3228 $may_save = undef if $_no_auth_cache;
3229 $default_username = $_username if defined $_username;
3230 if (defined $default_username && length $default_username) {
3231 if (defined $realm && length $realm) {
3232 print STDERR "Authentication realm: $realm\n";
3233 STDERR->flush;
3235 $cred->username($default_username);
3236 } else {
3237 username($cred, $realm, $may_save, $pool);
3239 $cred->password(_read_password("Password for '" .
3240 $cred->username . "': ", $realm));
3241 $cred->may_save($may_save);
3242 $SVN::_Core::SVN_NO_ERROR;
3245 sub ssl_server_trust {
3246 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3247 $may_save = undef if $_no_auth_cache;
3248 print STDERR "Error validating server certificate for '$realm':\n";
3250 no warnings 'once';
3251 # All variables SVN::Auth::SSL::* are used only once,
3252 # so we're shutting up Perl warnings about this.
3253 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3254 print STDERR " - The certificate is not issued ",
3255 "by a trusted authority. Use the\n",
3256 " fingerprint to validate ",
3257 "the certificate manually!\n";
3259 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3260 print STDERR " - The certificate hostname ",
3261 "does not match.\n";
3263 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3264 print STDERR " - The certificate is not yet valid.\n";
3266 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3267 print STDERR " - The certificate has expired.\n";
3269 if ($failures & $SVN::Auth::SSL::OTHER) {
3270 print STDERR " - The certificate has ",
3271 "an unknown error.\n";
3273 } # no warnings 'once'
3274 printf STDERR
3275 "Certificate information:\n".
3276 " - Hostname: %s\n".
3277 " - Valid: from %s until %s\n".
3278 " - Issuer: %s\n".
3279 " - Fingerprint: %s\n",
3280 map $cert_info->$_, qw(hostname valid_from valid_until
3281 issuer_dname fingerprint);
3282 my $choice;
3283 prompt:
3284 print STDERR $may_save ?
3285 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3286 "(R)eject or accept (t)emporarily? ";
3287 STDERR->flush;
3288 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3289 if ($choice =~ /^t$/i) {
3290 $cred->may_save(undef);
3291 } elsif ($choice =~ /^r$/i) {
3292 return -1;
3293 } elsif ($may_save && $choice =~ /^p$/i) {
3294 $cred->may_save($may_save);
3295 } else {
3296 goto prompt;
3298 $cred->accepted_failures($failures);
3299 $SVN::_Core::SVN_NO_ERROR;
3302 sub ssl_client_cert {
3303 my ($cred, $realm, $may_save, $pool) = @_;
3304 $may_save = undef if $_no_auth_cache;
3305 print STDERR "Client certificate filename: ";
3306 STDERR->flush;
3307 chomp(my $filename = <STDIN>);
3308 $cred->cert_file($filename);
3309 $cred->may_save($may_save);
3310 $SVN::_Core::SVN_NO_ERROR;
3313 sub ssl_client_cert_pw {
3314 my ($cred, $realm, $may_save, $pool) = @_;
3315 $may_save = undef if $_no_auth_cache;
3316 $cred->password(_read_password("Password: ", $realm));
3317 $cred->may_save($may_save);
3318 $SVN::_Core::SVN_NO_ERROR;
3321 sub username {
3322 my ($cred, $realm, $may_save, $pool) = @_;
3323 $may_save = undef if $_no_auth_cache;
3324 if (defined $realm && length $realm) {
3325 print STDERR "Authentication realm: $realm\n";
3327 my $username;
3328 if (defined $_username) {
3329 $username = $_username;
3330 } else {
3331 print STDERR "Username: ";
3332 STDERR->flush;
3333 chomp($username = <STDIN>);
3335 $cred->username($username);
3336 $cred->may_save($may_save);
3337 $SVN::_Core::SVN_NO_ERROR;
3340 sub _read_password {
3341 my ($prompt, $realm) = @_;
3342 print STDERR $prompt;
3343 STDERR->flush;
3344 require Term::ReadKey;
3345 Term::ReadKey::ReadMode('noecho');
3346 my $password = '';
3347 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3348 last if $key =~ /[\012\015]/; # \n\r
3349 $password .= $key;
3351 Term::ReadKey::ReadMode('restore');
3352 print STDERR "\n";
3353 STDERR->flush;
3354 $password;
3357 package SVN::Git::Fetcher;
3358 use vars qw/@ISA/;
3359 use strict;
3360 use warnings;
3361 use Carp qw/croak/;
3362 use File::Temp qw/tempfile/;
3363 use IO::File qw//;
3364 use vars qw/$_ignore_regex/;
3366 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3367 sub new {
3368 my ($class, $git_svn, $switch_path) = @_;
3369 my $self = SVN::Delta::Editor->new;
3370 bless $self, $class;
3371 if (exists $git_svn->{last_commit}) {
3372 $self->{c} = $git_svn->{last_commit};
3373 $self->{empty_symlinks} =
3374 _mark_empty_symlinks($git_svn, $switch_path);
3376 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3377 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3378 $self->{empty} = {};
3379 $self->{dir_prop} = {};
3380 $self->{file_prop} = {};
3381 $self->{absent_dir} = {};
3382 $self->{absent_file} = {};
3383 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3384 $self;
3387 # this uses the Ra object, so it must be called before do_{switch,update},
3388 # not inside them (when the Git::SVN::Fetcher object is passed) to
3389 # do_{switch,update}
3390 sub _mark_empty_symlinks {
3391 my ($git_svn, $switch_path) = @_;
3392 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3393 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3395 my %ret;
3396 my ($rev, $cmt) = $git_svn->last_rev_commit;
3397 return {} unless ($rev && $cmt);
3399 # allow the warning to be printed for each revision we fetch to
3400 # ensure the user sees it. The user can also disable the workaround
3401 # on the repository even while git svn is running and the next
3402 # revision fetched will skip this expensive function.
3403 my $printed_warning;
3404 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3405 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3406 local $/ = "\0";
3407 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3408 $pfx .= '/' if length($pfx);
3409 while (<$ls>) {
3410 chomp;
3411 s/\A100644 blob $empty_blob\t//o or next;
3412 unless ($printed_warning) {
3413 print STDERR "Scanning for empty symlinks, ",
3414 "this may take a while if you have ",
3415 "many empty files\n",
3416 "You may disable this with `",
3417 "git config svn.brokenSymlinkWorkaround ",
3418 "false'.\n",
3419 "This may be done in a different ",
3420 "terminal without restarting ",
3421 "git svn\n";
3422 $printed_warning = 1;
3424 my $path = $_;
3425 my (undef, $props) =
3426 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3427 if ($props->{'svn:special'}) {
3428 $ret{$path} = 1;
3431 command_close_pipe($ls, $ctx);
3432 \%ret;
3435 # returns true if a given path is inside a ".git" directory
3436 sub in_dot_git {
3437 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3440 # return value: 0 -- don't ignore, 1 -- ignore
3441 sub is_path_ignored {
3442 my ($self, $path) = @_;
3443 return 1 if in_dot_git($path);
3444 return 1 if defined($self->{ignore_regex}) &&
3445 $path =~ m!$self->{ignore_regex}!;
3446 return 0 unless defined($_ignore_regex);
3447 return 1 if $path =~ m!$_ignore_regex!o;
3448 return 0;
3451 sub set_path_strip {
3452 my ($self, $path) = @_;
3453 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3456 sub open_root {
3457 { path => '' };
3460 sub open_directory {
3461 my ($self, $path, $pb, $rev) = @_;
3462 { path => $path };
3465 sub git_path {
3466 my ($self, $path) = @_;
3467 if ($self->{path_strip}) {
3468 $path =~ s!$self->{path_strip}!! or
3469 die "Failed to strip path '$path' ($self->{path_strip})\n";
3471 $path;
3474 sub delete_entry {
3475 my ($self, $path, $rev, $pb) = @_;
3476 return undef if $self->is_path_ignored($path);
3478 my $gpath = $self->git_path($path);
3479 return undef if ($gpath eq '');
3481 # remove entire directories.
3482 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3483 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3484 if ($tree) {
3485 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3486 -r --name-only -z/,
3487 $tree);
3488 local $/ = "\0";
3489 while (<$ls>) {
3490 chomp;
3491 my $rmpath = "$gpath/$_";
3492 $self->{gii}->remove($rmpath);
3493 print "\tD\t$rmpath\n" unless $::_q;
3495 print "\tD\t$gpath/\n" unless $::_q;
3496 command_close_pipe($ls, $ctx);
3497 $self->{empty}->{$path} = 0
3498 } else {
3499 $self->{gii}->remove($gpath);
3500 print "\tD\t$gpath\n" unless $::_q;
3502 undef;
3505 sub open_file {
3506 my ($self, $path, $pb, $rev) = @_;
3507 my ($mode, $blob);
3509 goto out if $self->is_path_ignored($path);
3511 my $gpath = $self->git_path($path);
3512 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3513 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3514 unless (defined $mode && defined $blob) {
3515 die "$path was not found in commit $self->{c} (r$rev)\n";
3517 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3518 $mode = '120000';
3520 out:
3521 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3522 pool => SVN::Pool->new, action => 'M' };
3525 sub add_file {
3526 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3527 my $mode;
3529 if (!$self->is_path_ignored($path)) {
3530 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3531 delete $self->{empty}->{$dir};
3532 $mode = '100644';
3534 { path => $path, mode_a => $mode, mode_b => $mode,
3535 pool => SVN::Pool->new, action => 'A' };
3538 sub add_directory {
3539 my ($self, $path, $cp_path, $cp_rev) = @_;
3540 goto out if $self->is_path_ignored($path);
3541 my $gpath = $self->git_path($path);
3542 if ($gpath eq '') {
3543 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3544 -r --name-only -z/,
3545 $self->{c});
3546 local $/ = "\0";
3547 while (<$ls>) {
3548 chomp;
3549 $self->{gii}->remove($_);
3550 print "\tD\t$_\n" unless $::_q;
3552 command_close_pipe($ls, $ctx);
3553 $self->{empty}->{$path} = 0;
3555 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3556 delete $self->{empty}->{$dir};
3557 $self->{empty}->{$path} = 1;
3558 out:
3559 { path => $path };
3562 sub change_dir_prop {
3563 my ($self, $db, $prop, $value) = @_;
3564 return undef if $self->is_path_ignored($db->{path});
3565 $self->{dir_prop}->{$db->{path}} ||= {};
3566 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3567 undef;
3570 sub absent_directory {
3571 my ($self, $path, $pb) = @_;
3572 return undef if $self->is_path_ignored($path);
3573 $self->{absent_dir}->{$pb->{path}} ||= [];
3574 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3575 undef;
3578 sub absent_file {
3579 my ($self, $path, $pb) = @_;
3580 return undef if $self->is_path_ignored($path);
3581 $self->{absent_file}->{$pb->{path}} ||= [];
3582 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3583 undef;
3586 sub change_file_prop {
3587 my ($self, $fb, $prop, $value) = @_;
3588 return undef if $self->is_path_ignored($fb->{path});
3589 if ($prop eq 'svn:executable') {
3590 if ($fb->{mode_b} != 120000) {
3591 $fb->{mode_b} = defined $value ? 100755 : 100644;
3593 } elsif ($prop eq 'svn:special') {
3594 $fb->{mode_b} = defined $value ? 120000 : 100644;
3595 } else {
3596 $self->{file_prop}->{$fb->{path}} ||= {};
3597 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3599 undef;
3602 sub apply_textdelta {
3603 my ($self, $fb, $exp) = @_;
3604 return undef if $self->is_path_ignored($fb->{path});
3605 my $fh = $::_repository->temp_acquire('svn_delta');
3606 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3607 # (but $base does not,) so dup() it for reading in close_file
3608 open my $dup, '<&', $fh or croak $!;
3609 my $base = $::_repository->temp_acquire('git_blob');
3611 if ($fb->{blob}) {
3612 my ($base_is_link, $size);
3614 if ($fb->{mode_a} eq '120000' &&
3615 ! $self->{empty_symlinks}->{$fb->{path}}) {
3616 print $base 'link ' or die "print $!\n";
3617 $base_is_link = 1;
3619 retry:
3620 $size = $::_repository->cat_blob($fb->{blob}, $base);
3621 die "Failed to read object $fb->{blob}" if ($size < 0);
3623 if (defined $exp) {
3624 seek $base, 0, 0 or croak $!;
3625 my $got = ::md5sum($base);
3626 if ($got ne $exp) {
3627 my $err = "Checksum mismatch: ".
3628 "$fb->{path} $fb->{blob}\n" .
3629 "expected: $exp\n" .
3630 " got: $got\n";
3631 if ($base_is_link) {
3632 warn $err,
3633 "Retrying... (possibly ",
3634 "a bad symlink from SVN)\n";
3635 $::_repository->temp_reset($base);
3636 $base_is_link = 0;
3637 goto retry;
3639 die $err;
3643 seek $base, 0, 0 or croak $!;
3644 $fb->{fh} = $fh;
3645 $fb->{base} = $base;
3646 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3649 sub close_file {
3650 my ($self, $fb, $exp) = @_;
3651 return undef if $self->is_path_ignored($fb->{path});
3653 my $hash;
3654 my $path = $self->git_path($fb->{path});
3655 if (my $fh = $fb->{fh}) {
3656 if (defined $exp) {
3657 seek($fh, 0, 0) or croak $!;
3658 my $got = ::md5sum($fh);
3659 if ($got ne $exp) {
3660 die "Checksum mismatch: $path\n",
3661 "expected: $exp\n got: $got\n";
3664 if ($fb->{mode_b} == 120000) {
3665 sysseek($fh, 0, 0) or croak $!;
3666 my $rd = sysread($fh, my $buf, 5);
3668 if (!defined $rd) {
3669 croak "sysread: $!\n";
3670 } elsif ($rd == 0) {
3671 warn "$path has mode 120000",
3672 " but it points to nothing\n",
3673 "converting to an empty file with mode",
3674 " 100644\n";
3675 $fb->{mode_b} = '100644';
3676 } elsif ($buf ne 'link ') {
3677 warn "$path has mode 120000",
3678 " but is not a link\n";
3679 } else {
3680 my $tmp_fh = $::_repository->temp_acquire(
3681 'svn_hash');
3682 my $res;
3683 while ($res = sysread($fh, my $str, 1024)) {
3684 my $out = syswrite($tmp_fh, $str, $res);
3685 defined($out) && $out == $res
3686 or croak("write ",
3687 Git::temp_path($tmp_fh),
3688 ": $!\n");
3690 defined $res or croak $!;
3692 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3693 Git::temp_release($tmp_fh, 1);
3697 $hash = $::_repository->hash_and_insert_object(
3698 Git::temp_path($fh));
3699 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3701 Git::temp_release($fb->{base}, 1);
3702 Git::temp_release($fh, 1);
3703 } else {
3704 $hash = $fb->{blob} or die "no blob information\n";
3706 $fb->{pool}->clear;
3707 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3708 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3709 undef;
3712 sub abort_edit {
3713 my $self = shift;
3714 $self->{nr} = $self->{gii}->{nr};
3715 delete $self->{gii};
3716 $self->SUPER::abort_edit(@_);
3719 sub close_edit {
3720 my $self = shift;
3721 $self->{git_commit_ok} = 1;
3722 $self->{nr} = $self->{gii}->{nr};
3723 delete $self->{gii};
3724 $self->SUPER::close_edit(@_);
3727 package SVN::Git::Editor;
3728 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3729 use strict;
3730 use warnings;
3731 use Carp qw/croak/;
3732 use IO::File;
3734 sub new {
3735 my ($class, $opts) = @_;
3736 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3737 die "$_ required!\n" unless (defined $opts->{$_});
3740 my $pool = SVN::Pool->new;
3741 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3742 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3743 $opts->{r}, $mods);
3745 # $opts->{ra} functions should not be used after this:
3746 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3747 $opts->{editor_cb}, $pool);
3748 my $self = SVN::Delta::Editor->new(@ce, $pool);
3749 bless $self, $class;
3750 foreach (qw/svn_path r tree_a tree_b/) {
3751 $self->{$_} = $opts->{$_};
3753 $self->{url} = $opts->{ra}->{url};
3754 $self->{mods} = $mods;
3755 $self->{types} = $types;
3756 $self->{pool} = $pool;
3757 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3758 $self->{rm} = { };
3759 $self->{path_prefix} = length $self->{svn_path} ?
3760 "$self->{svn_path}/" : '';
3761 $self->{config} = $opts->{config};
3762 return $self;
3765 sub generate_diff {
3766 my ($tree_a, $tree_b) = @_;
3767 my @diff_tree = qw(diff-tree -z -r);
3768 if ($_cp_similarity) {
3769 push @diff_tree, "-C$_cp_similarity";
3770 } else {
3771 push @diff_tree, '-C';
3773 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3774 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3775 push @diff_tree, $tree_a, $tree_b;
3776 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3777 local $/ = "\0";
3778 my $state = 'meta';
3779 my @mods;
3780 while (<$diff_fh>) {
3781 chomp $_; # this gets rid of the trailing "\0"
3782 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3783 ($::sha1)\s($::sha1)\s
3784 ([MTCRAD])\d*$/xo) {
3785 push @mods, { mode_a => $1, mode_b => $2,
3786 sha1_a => $3, sha1_b => $4,
3787 chg => $5 };
3788 if ($5 =~ /^(?:C|R)$/) {
3789 $state = 'file_a';
3790 } else {
3791 $state = 'file_b';
3793 } elsif ($state eq 'file_a') {
3794 my $x = $mods[$#mods] or croak "Empty array\n";
3795 if ($x->{chg} !~ /^(?:C|R)$/) {
3796 croak "Error parsing $_, $x->{chg}\n";
3798 $x->{file_a} = $_;
3799 $state = 'file_b';
3800 } elsif ($state eq 'file_b') {
3801 my $x = $mods[$#mods] or croak "Empty array\n";
3802 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3803 croak "Error parsing $_, $x->{chg}\n";
3805 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3806 croak "Error parsing $_, $x->{chg}\n";
3808 $x->{file_b} = $_;
3809 $state = 'meta';
3810 } else {
3811 croak "Error parsing $_\n";
3814 command_close_pipe($diff_fh, $ctx);
3815 \@mods;
3818 sub check_diff_paths {
3819 my ($ra, $pfx, $rev, $mods) = @_;
3820 my %types;
3821 $pfx .= '/' if length $pfx;
3823 sub type_diff_paths {
3824 my ($ra, $types, $path, $rev) = @_;
3825 my @p = split m#/+#, $path;
3826 my $c = shift @p;
3827 unless (defined $types->{$c}) {
3828 $types->{$c} = $ra->check_path($c, $rev);
3830 while (@p) {
3831 $c .= '/' . shift @p;
3832 next if defined $types->{$c};
3833 $types->{$c} = $ra->check_path($c, $rev);
3837 foreach my $m (@$mods) {
3838 foreach my $f (qw/file_a file_b/) {
3839 next unless defined $m->{$f};
3840 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3841 if (length $pfx.$dir && ! defined $types{$dir}) {
3842 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3846 \%types;
3849 sub split_path {
3850 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3853 sub repo_path {
3854 my ($self, $path) = @_;
3855 $self->{path_prefix}.(defined $path ? $path : '');
3858 sub url_path {
3859 my ($self, $path) = @_;
3860 if ($self->{url} =~ m#^https?://#) {
3861 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3863 $self->{url} . '/' . $self->repo_path($path);
3866 sub rmdirs {
3867 my ($self) = @_;
3868 my $rm = $self->{rm};
3869 delete $rm->{''}; # we never delete the url we're tracking
3870 return unless %$rm;
3872 foreach (keys %$rm) {
3873 my @d = split m#/#, $_;
3874 my $c = shift @d;
3875 $rm->{$c} = 1;
3876 while (@d) {
3877 $c .= '/' . shift @d;
3878 $rm->{$c} = 1;
3881 delete $rm->{$self->{svn_path}};
3882 delete $rm->{''}; # we never delete the url we're tracking
3883 return unless %$rm;
3885 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3886 $self->{tree_b});
3887 local $/ = "\0";
3888 while (<$fh>) {
3889 chomp;
3890 my @dn = split m#/#, $_;
3891 while (pop @dn) {
3892 delete $rm->{join '/', @dn};
3894 unless (%$rm) {
3895 close $fh;
3896 return;
3899 command_close_pipe($fh, $ctx);
3901 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3902 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3903 $self->close_directory($bat->{$d}, $p);
3904 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3905 print "\tD+\t$d/\n" unless $::_q;
3906 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3907 delete $bat->{$d};
3911 sub open_or_add_dir {
3912 my ($self, $full_path, $baton) = @_;
3913 my $t = $self->{types}->{$full_path};
3914 if (!defined $t) {
3915 die "$full_path not known in r$self->{r} or we have a bug!\n";
3918 no warnings 'once';
3919 # SVN::Node::none and SVN::Node::file are used only once,
3920 # so we're shutting up Perl's warnings about them.
3921 if ($t == $SVN::Node::none) {
3922 return $self->add_directory($full_path, $baton,
3923 undef, -1, $self->{pool});
3924 } elsif ($t == $SVN::Node::dir) {
3925 return $self->open_directory($full_path, $baton,
3926 $self->{r}, $self->{pool});
3927 } # no warnings 'once'
3928 print STDERR "$full_path already exists in repository at ",
3929 "r$self->{r} and it is not a directory (",
3930 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3931 } # no warnings 'once'
3932 exit 1;
3935 sub ensure_path {
3936 my ($self, $path) = @_;
3937 my $bat = $self->{bat};
3938 my $repo_path = $self->repo_path($path);
3939 return $bat->{''} unless (length $repo_path);
3940 my @p = split m#/+#, $repo_path;
3941 my $c = shift @p;
3942 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3943 while (@p) {
3944 my $c0 = $c;
3945 $c .= '/' . shift @p;
3946 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3948 return $bat->{$c};
3951 # Subroutine to convert a globbing pattern to a regular expression.
3952 # From perl cookbook.
3953 sub glob2pat {
3954 my $globstr = shift;
3955 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3956 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3957 return '^' . $globstr . '$';
3960 sub check_autoprop {
3961 my ($self, $pattern, $properties, $file, $fbat) = @_;
3962 # Convert the globbing pattern to a regular expression.
3963 my $regex = glob2pat($pattern);
3964 # Check if the pattern matches the file name.
3965 if($file =~ m/($regex)/) {
3966 # Parse the list of properties to set.
3967 my @props = split(/;/, $properties);
3968 foreach my $prop (@props) {
3969 # Parse 'name=value' syntax and set the property.
3970 if ($prop =~ /([^=]+)=(.*)/) {
3971 my ($n,$v) = ($1,$2);
3972 for ($n, $v) {
3973 s/^\s+//; s/\s+$//;
3975 $self->change_file_prop($fbat, $n, $v);
3981 sub apply_autoprops {
3982 my ($self, $file, $fbat) = @_;
3983 my $conf_t = ${$self->{config}}{'config'};
3984 no warnings 'once';
3985 # Check [miscellany]/enable-auto-props in svn configuration.
3986 if (SVN::_Core::svn_config_get_bool(
3987 $conf_t,
3988 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3989 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3990 0)) {
3991 # Auto-props are enabled. Enumerate them to look for matches.
3992 my $callback = sub {
3993 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3995 SVN::_Core::svn_config_enumerate(
3996 $conf_t,
3997 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3998 $callback);
4002 sub A {
4003 my ($self, $m) = @_;
4004 my ($dir, $file) = split_path($m->{file_b});
4005 my $pbat = $self->ensure_path($dir);
4006 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4007 undef, -1);
4008 print "\tA\t$m->{file_b}\n" unless $::_q;
4009 $self->apply_autoprops($file, $fbat);
4010 $self->chg_file($fbat, $m);
4011 $self->close_file($fbat,undef,$self->{pool});
4014 sub C {
4015 my ($self, $m) = @_;
4016 my ($dir, $file) = split_path($m->{file_b});
4017 my $pbat = $self->ensure_path($dir);
4018 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4019 $self->url_path($m->{file_a}), $self->{r});
4020 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4021 $self->chg_file($fbat, $m);
4022 $self->close_file($fbat,undef,$self->{pool});
4025 sub delete_entry {
4026 my ($self, $path, $pbat) = @_;
4027 my $rpath = $self->repo_path($path);
4028 my ($dir, $file) = split_path($rpath);
4029 $self->{rm}->{$dir} = 1;
4030 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4033 sub R {
4034 my ($self, $m) = @_;
4035 my ($dir, $file) = split_path($m->{file_b});
4036 my $pbat = $self->ensure_path($dir);
4037 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4038 $self->url_path($m->{file_a}), $self->{r});
4039 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4040 $self->apply_autoprops($file, $fbat);
4041 $self->chg_file($fbat, $m);
4042 $self->close_file($fbat,undef,$self->{pool});
4044 ($dir, $file) = split_path($m->{file_a});
4045 $pbat = $self->ensure_path($dir);
4046 $self->delete_entry($m->{file_a}, $pbat);
4049 sub M {
4050 my ($self, $m) = @_;
4051 my ($dir, $file) = split_path($m->{file_b});
4052 my $pbat = $self->ensure_path($dir);
4053 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4054 $pbat,$self->{r},$self->{pool});
4055 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4056 $self->chg_file($fbat, $m);
4057 $self->close_file($fbat,undef,$self->{pool});
4060 sub T { shift->M(@_) }
4062 sub change_file_prop {
4063 my ($self, $fbat, $pname, $pval) = @_;
4064 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4067 sub _chg_file_get_blob ($$$$) {
4068 my ($self, $fbat, $m, $which) = @_;
4069 my $fh = $::_repository->temp_acquire("git_blob_$which");
4070 if ($m->{"mode_$which"} =~ /^120/) {
4071 print $fh 'link ' or croak $!;
4072 $self->change_file_prop($fbat,'svn:special','*');
4073 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4074 $self->change_file_prop($fbat,'svn:special',undef);
4076 my $blob = $m->{"sha1_$which"};
4077 return ($fh,) if ($blob =~ /^0{40}$/);
4078 my $size = $::_repository->cat_blob($blob, $fh);
4079 croak "Failed to read object $blob" if ($size < 0);
4080 $fh->flush == 0 or croak $!;
4081 seek $fh, 0, 0 or croak $!;
4083 my $exp = ::md5sum($fh);
4084 seek $fh, 0, 0 or croak $!;
4085 return ($fh, $exp);
4088 sub chg_file {
4089 my ($self, $fbat, $m) = @_;
4090 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4091 $self->change_file_prop($fbat,'svn:executable','*');
4092 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4093 $self->change_file_prop($fbat,'svn:executable',undef);
4095 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4096 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4097 my $pool = SVN::Pool->new;
4098 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4099 if (-s $fh_a) {
4100 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4101 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4102 if (defined $res) {
4103 die "Unexpected result from send_txstream: $res\n",
4104 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4106 } else {
4107 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4108 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4109 if ($got ne $exp_b);
4111 Git::temp_release($fh_b, 1);
4112 Git::temp_release($fh_a, 1);
4113 $pool->clear;
4116 sub D {
4117 my ($self, $m) = @_;
4118 my ($dir, $file) = split_path($m->{file_b});
4119 my $pbat = $self->ensure_path($dir);
4120 print "\tD\t$m->{file_b}\n" unless $::_q;
4121 $self->delete_entry($m->{file_b}, $pbat);
4124 sub close_edit {
4125 my ($self) = @_;
4126 my ($p,$bat) = ($self->{pool}, $self->{bat});
4127 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4128 next if $_ eq '';
4129 $self->close_directory($bat->{$_}, $p);
4131 $self->close_directory($bat->{''}, $p);
4132 $self->SUPER::close_edit($p);
4133 $p->clear;
4136 sub abort_edit {
4137 my ($self) = @_;
4138 $self->SUPER::abort_edit($self->{pool});
4141 sub DESTROY {
4142 my $self = shift;
4143 $self->SUPER::DESTROY(@_);
4144 $self->{pool}->clear;
4147 # this drives the editor
4148 sub apply_diff {
4149 my ($self) = @_;
4150 my $mods = $self->{mods};
4151 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4152 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4153 my $f = $m->{chg};
4154 if (defined $o{$f}) {
4155 $self->$f($m);
4156 } else {
4157 fatal("Invalid change type: $f");
4160 $self->rmdirs if $_rmdir;
4161 if (@$mods == 0) {
4162 $self->abort_edit;
4163 } else {
4164 $self->close_edit;
4166 return scalar @$mods;
4169 package Git::SVN::Ra;
4170 use vars qw/@ISA $config_dir $_log_window_size/;
4171 use strict;
4172 use warnings;
4173 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4175 BEGIN {
4176 # enforce temporary pool usage for some simple functions
4177 no strict 'refs';
4178 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4179 get_file/) {
4180 my $SUPER = "SUPER::$f";
4181 *$f = sub {
4182 my $self = shift;
4183 my $pool = SVN::Pool->new;
4184 my @ret = $self->$SUPER(@_,$pool);
4185 $pool->clear;
4186 wantarray ? @ret : $ret[0];
4191 sub _auth_providers () {
4193 SVN::Client::get_simple_provider(),
4194 SVN::Client::get_ssl_server_trust_file_provider(),
4195 SVN::Client::get_simple_prompt_provider(
4196 \&Git::SVN::Prompt::simple, 2),
4197 SVN::Client::get_ssl_client_cert_file_provider(),
4198 SVN::Client::get_ssl_client_cert_prompt_provider(
4199 \&Git::SVN::Prompt::ssl_client_cert, 2),
4200 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4201 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4202 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4203 SVN::Client::get_username_provider(),
4204 SVN::Client::get_ssl_server_trust_prompt_provider(
4205 \&Git::SVN::Prompt::ssl_server_trust),
4206 SVN::Client::get_username_prompt_provider(
4207 \&Git::SVN::Prompt::username, 2)
4211 sub escape_uri_only {
4212 my ($uri) = @_;
4213 my @tmp;
4214 foreach (split m{/}, $uri) {
4215 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4216 push @tmp, $_;
4218 join('/', @tmp);
4221 sub escape_url {
4222 my ($url) = @_;
4223 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4224 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4225 $url = "$scheme://$domain$uri";
4227 $url;
4230 sub new {
4231 my ($class, $url) = @_;
4232 $url =~ s!/+$!!;
4233 return $RA if ($RA && $RA->{url} eq $url);
4235 SVN::_Core::svn_config_ensure($config_dir, undef);
4236 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4237 my $config = SVN::Core::config_get_config($config_dir);
4238 $RA = undef;
4239 my $dont_store_passwords = 1;
4240 my $conf_t = ${$config}{'config'};
4242 no warnings 'once';
4243 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4244 # produces warnings that variables are used only once.
4245 # I had not found the better way to shut them up, so
4246 # the warnings of type 'once' are disabled in this block.
4247 if (SVN::_Core::svn_config_get_bool($conf_t,
4248 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4249 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4250 1) == 0) {
4251 SVN::_Core::svn_auth_set_parameter($baton,
4252 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4253 bless (\$dont_store_passwords, "_p_void"));
4255 if (SVN::_Core::svn_config_get_bool($conf_t,
4256 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4257 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4258 1) == 0) {
4259 $Git::SVN::Prompt::_no_auth_cache = 1;
4261 } # no warnings 'once'
4262 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4263 config => $config,
4264 pool => SVN::Pool->new,
4265 auth_provider_callbacks => $callbacks);
4266 $self->{url} = $url;
4267 $self->{svn_path} = $url;
4268 $self->{repos_root} = $self->get_repos_root;
4269 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4270 $self->{cache} = { check_path => { r => 0, data => {} },
4271 get_dir => { r => 0, data => {} } };
4272 $RA = bless $self, $class;
4275 sub check_path {
4276 my ($self, $path, $r) = @_;
4277 my $cache = $self->{cache}->{check_path};
4278 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4279 return $cache->{data}->{$path};
4281 my $pool = SVN::Pool->new;
4282 my $t = $self->SUPER::check_path($path, $r, $pool);
4283 $pool->clear;
4284 if ($r != $cache->{r}) {
4285 %{$cache->{data}} = ();
4286 $cache->{r} = $r;
4288 $cache->{data}->{$path} = $t;
4291 sub get_dir {
4292 my ($self, $dir, $r) = @_;
4293 my $cache = $self->{cache}->{get_dir};
4294 if ($r == $cache->{r}) {
4295 if (my $x = $cache->{data}->{$dir}) {
4296 return wantarray ? @$x : $x->[0];
4299 my $pool = SVN::Pool->new;
4300 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4301 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4302 $pool->clear;
4303 if ($r != $cache->{r}) {
4304 %{$cache->{data}} = ();
4305 $cache->{r} = $r;
4307 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4308 wantarray ? (\%dirents, $r, $props) : \%dirents;
4311 sub DESTROY {
4312 # do not call the real DESTROY since we store ourselves in $RA
4315 # get_log(paths, start, end, limit,
4316 # discover_changed_paths, strict_node_history, receiver)
4317 sub get_log {
4318 my ($self, @args) = @_;
4319 my $pool = SVN::Pool->new;
4321 # the limit parameter was not supported in SVN 1.1.x, so we
4322 # drop it. Therefore, the receiver callback passed to it
4323 # is made aware of this limitation by being wrapped if
4324 # the limit passed to is being wrapped.
4325 if ($SVN::Core::VERSION le '1.2.0') {
4326 my $limit = splice(@args, 3, 1);
4327 if ($limit > 0) {
4328 my $receiver = pop @args;
4329 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4332 my $ret = $self->SUPER::get_log(@args, $pool);
4333 $pool->clear;
4334 $ret;
4337 sub trees_match {
4338 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4339 my $ctx = SVN::Client->new(auth => _auth_providers);
4340 my $out = IO::File->new_tmpfile;
4342 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4343 # $ctx->diff(), so we'll create a default one
4344 my $pool = SVN::Pool->new_default_sub;
4346 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4347 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4348 $out->flush;
4349 my $ret = (($out->stat)[7] == 0);
4350 close $out or croak $!;
4352 $ret;
4355 sub get_commit_editor {
4356 my ($self, $log, $cb, $pool) = @_;
4357 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4358 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4361 sub gs_do_update {
4362 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4363 my $new = ($rev_a == $rev_b);
4364 my $path = $gs->{path};
4366 if ($new && -e $gs->{index}) {
4367 unlink $gs->{index} or die
4368 "Couldn't unlink index: $gs->{index}: $!\n";
4370 my $pool = SVN::Pool->new;
4371 $editor->set_path_strip($path);
4372 my (@pc) = split m#/#, $path;
4373 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4374 1, $editor, $pool);
4375 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4377 # Since we can't rely on svn_ra_reparent being available, we'll
4378 # just have to do some magic with set_path to make it so
4379 # we only want a partial path.
4380 my $sp = '';
4381 my $final = join('/', @pc);
4382 while (@pc) {
4383 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4384 $sp .= '/' if length $sp;
4385 $sp .= shift @pc;
4387 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4389 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4391 $reporter->finish_report($pool);
4392 $pool->clear;
4393 $editor->{git_commit_ok};
4396 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4397 # svn_ra_reparent didn't work before 1.4)
4398 sub gs_do_switch {
4399 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4400 my $path = $gs->{path};
4401 my $pool = SVN::Pool->new;
4403 my $full_url = $self->{url};
4404 my $old_url = $full_url;
4405 $full_url .= '/' . escape_uri_only($path) if length $path;
4406 my ($ra, $reparented);
4408 if ($old_url =~ m#^svn(\+ssh)?://#) {
4409 $_[0] = undef;
4410 $self = undef;
4411 $RA = undef;
4412 $ra = Git::SVN::Ra->new($full_url);
4413 $ra_invalid = 1;
4414 } elsif ($old_url ne $full_url) {
4415 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4416 $self->{url} = $full_url;
4417 $reparented = 1;
4420 $ra ||= $self;
4421 $url_b = escape_url($url_b);
4422 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4423 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4424 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4425 $reporter->finish_report($pool);
4427 if ($reparented) {
4428 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4429 $self->{url} = $old_url;
4432 $pool->clear;
4433 $editor->{git_commit_ok};
4436 sub longest_common_path {
4437 my ($gsv, $globs) = @_;
4438 my %common;
4439 my $common_max = scalar @$gsv;
4441 foreach my $gs (@$gsv) {
4442 my @tmp = split m#/#, $gs->{path};
4443 my $p = '';
4444 foreach (@tmp) {
4445 $p .= length($p) ? "/$_" : $_;
4446 $common{$p} ||= 0;
4447 $common{$p}++;
4450 $globs ||= [];
4451 $common_max += scalar @$globs;
4452 foreach my $glob (@$globs) {
4453 my @tmp = split m#/#, $glob->{path}->{left};
4454 my $p = '';
4455 foreach (@tmp) {
4456 $p .= length($p) ? "/$_" : $_;
4457 $common{$p} ||= 0;
4458 $common{$p}++;
4462 my $longest_path = '';
4463 foreach (sort {length $b <=> length $a} keys %common) {
4464 if ($common{$_} == $common_max) {
4465 $longest_path = $_;
4466 last;
4469 $longest_path;
4472 sub gs_fetch_loop_common {
4473 my ($self, $base, $head, $gsv, $globs) = @_;
4474 return if ($base > $head);
4475 my $inc = $_log_window_size;
4476 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4477 my $longest_path = longest_common_path($gsv, $globs);
4478 my $ra_url = $self->{url};
4479 my $find_trailing_edge;
4480 while (1) {
4481 my %revs;
4482 my $err;
4483 my $err_handler = $SVN::Error::handler;
4484 $SVN::Error::handler = sub {
4485 ($err) = @_;
4486 skip_unknown_revs($err);
4488 sub _cb {
4489 my ($paths, $r, $author, $date, $log) = @_;
4490 [ dup_changed_paths($paths),
4491 { author => $author, date => $date, log => $log } ];
4493 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4494 sub { $revs{$_[1]} = _cb(@_) });
4495 if ($err) {
4496 print "Checked through r$max\r";
4497 } else {
4498 $find_trailing_edge = 1;
4500 if ($err and $find_trailing_edge) {
4501 print STDERR "Path '$longest_path' ",
4502 "was probably deleted:\n",
4503 $err->expanded_message,
4504 "\nWill attempt to follow ",
4505 "revisions r$min .. r$max ",
4506 "committed before the deletion\n";
4507 my $hi = $max;
4508 while (--$hi >= $min) {
4509 my $ok;
4510 $self->get_log([$longest_path], $min, $hi,
4511 0, 1, 1, sub {
4512 $ok = $_[1];
4513 $revs{$_[1]} = _cb(@_) });
4514 if ($ok) {
4515 print STDERR "r$min .. r$ok OK\n";
4516 last;
4519 $find_trailing_edge = 0;
4521 $SVN::Error::handler = $err_handler;
4523 my %exists = map { $_->{path} => $_ } @$gsv;
4524 foreach my $r (sort {$a <=> $b} keys %revs) {
4525 my ($paths, $logged) = @{$revs{$r}};
4527 foreach my $gs ($self->match_globs(\%exists, $paths,
4528 $globs, $r)) {
4529 if ($gs->rev_map_max >= $r) {
4530 next;
4532 next unless $gs->match_paths($paths, $r);
4533 $gs->{logged_rev_props} = $logged;
4534 if (my $last_commit = $gs->last_commit) {
4535 $gs->assert_index_clean($last_commit);
4537 my $log_entry = $gs->do_fetch($paths, $r);
4538 if ($log_entry) {
4539 $gs->do_git_commit($log_entry);
4541 $INDEX_FILES{$gs->{index}} = 1;
4543 foreach my $g (@$globs) {
4544 my $k = "svn-remote.$g->{remote}." .
4545 "$g->{t}-maxRev";
4546 Git::SVN::tmp_config($k, $r);
4548 if ($ra_invalid) {
4549 $_[0] = undef;
4550 $self = undef;
4551 $RA = undef;
4552 $self = Git::SVN::Ra->new($ra_url);
4553 $ra_invalid = undef;
4556 # pre-fill the .rev_db since it'll eventually get filled in
4557 # with '0' x40 if something new gets committed
4558 foreach my $gs (@$gsv) {
4559 next if $gs->rev_map_max >= $max;
4560 next if defined $gs->rev_map_get($max);
4561 $gs->rev_map_set($max, 0 x40);
4563 foreach my $g (@$globs) {
4564 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4565 Git::SVN::tmp_config($k, $max);
4567 last if $max >= $head;
4568 $min = $max + 1;
4569 $max += $inc;
4570 $max = $head if ($max > $head);
4572 Git::SVN::gc();
4575 sub get_dir_globbed {
4576 my ($self, $left, $depth, $r) = @_;
4578 my @x = eval { $self->get_dir($left, $r) };
4579 return unless scalar @x == 3;
4580 my $dirents = $x[0];
4581 my @finalents;
4582 foreach my $de (keys %$dirents) {
4583 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4584 if ($depth > 1) {
4585 my @args = ("$left/$de", $depth - 1, $r);
4586 foreach my $dir ($self->get_dir_globbed(@args)) {
4587 push @finalents, "$de/$dir";
4589 } else {
4590 push @finalents, $de;
4593 @finalents;
4596 sub match_globs {
4597 my ($self, $exists, $paths, $globs, $r) = @_;
4599 sub get_dir_check {
4600 my ($self, $exists, $g, $r) = @_;
4602 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4603 $g->{path}->{depth},
4604 $r);
4606 foreach my $de (@dirs) {
4607 my $p = $g->{path}->full_path($de);
4608 next if $exists->{$p};
4609 next if (length $g->{path}->{right} &&
4610 ($self->check_path($p, $r) !=
4611 $SVN::Node::dir));
4612 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4613 $g->{ref}->full_path($de), 1);
4616 foreach my $g (@$globs) {
4617 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4618 if ($path->{action} =~ /^[AR]$/) {
4619 get_dir_check($self, $exists, $g, $r);
4622 foreach (keys %$paths) {
4623 if (/$g->{path}->{left_regex}/ &&
4624 !/$g->{path}->{regex}/) {
4625 next if $paths->{$_}->{action} !~ /^[AR]$/;
4626 get_dir_check($self, $exists, $g, $r);
4628 next unless /$g->{path}->{regex}/;
4629 my $p = $1;
4630 my $pathname = $g->{path}->full_path($p);
4631 next if $exists->{$pathname};
4632 next if ($self->check_path($pathname, $r) !=
4633 $SVN::Node::dir);
4634 $exists->{$pathname} = Git::SVN->init(
4635 $self->{url}, $pathname, undef,
4636 $g->{ref}->full_path($p), 1);
4638 my $c = '';
4639 foreach (split m#/#, $g->{path}->{left}) {
4640 $c .= "/$_";
4641 next unless ($paths->{$c} &&
4642 ($paths->{$c}->{action} =~ /^[AR]$/));
4643 get_dir_check($self, $exists, $g, $r);
4646 values %$exists;
4649 sub minimize_url {
4650 my ($self) = @_;
4651 return $self->{url} if ($self->{url} eq $self->{repos_root});
4652 my $url = $self->{repos_root};
4653 my @components = split(m!/!, $self->{svn_path});
4654 my $c = '';
4655 do {
4656 $url .= "/$c" if length $c;
4657 eval { (ref $self)->new($url)->get_latest_revnum };
4658 } while ($@ && ($c = shift @components));
4659 $url;
4662 sub can_do_switch {
4663 my $self = shift;
4664 unless (defined $can_do_switch) {
4665 my $pool = SVN::Pool->new;
4666 my $rep = eval {
4667 $self->do_switch(1, '', 0, $self->{url},
4668 SVN::Delta::Editor->new, $pool);
4670 if ($@) {
4671 $can_do_switch = 0;
4672 } else {
4673 $rep->abort_report($pool);
4674 $can_do_switch = 1;
4676 $pool->clear;
4678 $can_do_switch;
4681 sub skip_unknown_revs {
4682 my ($err) = @_;
4683 my $errno = $err->apr_err();
4684 # Maybe the branch we're tracking didn't
4685 # exist when the repo started, so it's
4686 # not an error if it doesn't, just continue
4688 # Wonderfully consistent library, eh?
4689 # 160013 - svn:// and file://
4690 # 175002 - http(s)://
4691 # 175007 - http(s):// (this repo required authorization, too...)
4692 # More codes may be discovered later...
4693 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4694 my $err_key = $err->expanded_message;
4695 # revision numbers change every time, filter them out
4696 $err_key =~ s/\d+/\0/g;
4697 $err_key = "$errno\0$err_key";
4698 unless ($ignored_err{$err_key}) {
4699 warn "W: Ignoring error from SVN, path probably ",
4700 "does not exist: ($errno): ",
4701 $err->expanded_message,"\n";
4702 warn "W: Do not be alarmed at the above message ",
4703 "git-svn is just searching aggressively for ",
4704 "old history.\n",
4705 "This may take a while on large repositories\n";
4706 $ignored_err{$err_key} = 1;
4708 return;
4710 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4713 # svn_log_changed_path_t objects passed to get_log are likely to be
4714 # overwritten even if only the refs are copied to an external variable,
4715 # so we should dup the structures in their entirety. Using an externally
4716 # passed pool (instead of our temporary and quickly cleared pool in
4717 # Git::SVN::Ra) does not help matters at all...
4718 sub dup_changed_paths {
4719 my ($paths) = @_;
4720 return undef unless $paths;
4721 my %ret;
4722 foreach my $p (keys %$paths) {
4723 my $i = $paths->{$p};
4724 my %s = map { $_ => $i->$_ }
4725 qw/copyfrom_path copyfrom_rev action/;
4726 $ret{$p} = \%s;
4728 \%ret;
4731 package Git::SVN::Log;
4732 use strict;
4733 use warnings;
4734 use POSIX qw/strftime/;
4735 use Time::Local;
4736 use constant commit_log_separator => ('-' x 72) . "\n";
4737 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4738 %rusers $show_commit $incremental/;
4739 my $l_fmt;
4741 sub cmt_showable {
4742 my ($c) = @_;
4743 return 1 if defined $c->{r};
4745 # big commit message got truncated by the 16k pretty buffer in rev-list
4746 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4747 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4748 @{$c->{l}} = ();
4749 my @log = command(qw/cat-file commit/, $c->{c});
4751 # shift off the headers
4752 shift @log while ($log[0] ne '');
4753 shift @log;
4755 # TODO: make $c->{l} not have a trailing newline in the future
4756 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4758 (undef, $c->{r}, undef) = ::extract_metadata(
4759 (grep(/^git-svn-id: /, @log))[-1]);
4761 return defined $c->{r};
4764 sub log_use_color {
4765 return $color || Git->repository->get_colorbool('color.diff');
4768 sub git_svn_log_cmd {
4769 my ($r_min, $r_max, @args) = @_;
4770 my $head = 'HEAD';
4771 my (@files, @log_opts);
4772 foreach my $x (@args) {
4773 if ($x eq '--' || @files) {
4774 push @files, $x;
4775 } else {
4776 if (::verify_ref("$x^0")) {
4777 $head = $x;
4778 } else {
4779 push @log_opts, $x;
4784 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4785 $gs ||= Git::SVN->_new;
4786 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4787 $gs->refname);
4788 push @cmd, '-r' unless $non_recursive;
4789 push @cmd, qw/--raw --name-status/ if $verbose;
4790 push @cmd, '--color' if log_use_color();
4791 push @cmd, @log_opts;
4792 if (defined $r_max && $r_max == $r_min) {
4793 push @cmd, '--max-count=1';
4794 if (my $c = $gs->rev_map_get($r_max)) {
4795 push @cmd, $c;
4797 } elsif (defined $r_max) {
4798 if ($r_max < $r_min) {
4799 ($r_min, $r_max) = ($r_max, $r_min);
4801 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4802 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4803 # If there are no commits in the range, both $c_max and $c_min
4804 # will be undefined. If there is at least 1 commit in the
4805 # range, both will be defined.
4806 return () if !defined $c_min || !defined $c_max;
4807 if ($c_min eq $c_max) {
4808 push @cmd, '--max-count=1', $c_min;
4809 } else {
4810 push @cmd, '--boundary', "$c_min..$c_max";
4813 return (@cmd, @files);
4816 # adapted from pager.c
4817 sub config_pager {
4818 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4819 if (!defined $pager) {
4820 $pager = 'less';
4821 } elsif (length $pager == 0 || $pager eq 'cat') {
4822 $pager = undef;
4824 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4827 sub run_pager {
4828 return unless -t *STDOUT && defined $pager;
4829 pipe my ($rfd, $wfd) or return;
4830 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4831 if (!$pid) {
4832 open STDOUT, '>&', $wfd or
4833 ::fatal "Can't redirect to stdout: $!";
4834 return;
4836 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4837 $ENV{LESS} ||= 'FRSX';
4838 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4841 sub format_svn_date {
4842 # some systmes don't handle or mishandle %z, so be creative.
4843 my $t = shift || time;
4844 my $gm = timelocal(gmtime($t));
4845 my $sign = qw( + + - )[ $t <=> $gm ];
4846 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4847 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4850 sub parse_git_date {
4851 my ($t, $tz) = @_;
4852 # Date::Parse isn't in the standard Perl distro :(
4853 if ($tz =~ s/^\+//) {
4854 $t += tz_to_s_offset($tz);
4855 } elsif ($tz =~ s/^\-//) {
4856 $t -= tz_to_s_offset($tz);
4858 return $t;
4861 sub set_local_timezone {
4862 if (defined $TZ) {
4863 $ENV{TZ} = $TZ;
4864 } else {
4865 delete $ENV{TZ};
4869 sub tz_to_s_offset {
4870 my ($tz) = @_;
4871 $tz =~ s/(\d\d)$//;
4872 return ($1 * 60) + ($tz * 3600);
4875 sub get_author_info {
4876 my ($dest, $author, $t, $tz) = @_;
4877 $author =~ s/(?:^\s*|\s*$)//g;
4878 $dest->{a_raw} = $author;
4879 my $au;
4880 if ($::_authors) {
4881 $au = $rusers{$author} || undef;
4883 if (!$au) {
4884 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4886 $dest->{t} = $t;
4887 $dest->{tz} = $tz;
4888 $dest->{a} = $au;
4889 $dest->{t_utc} = parse_git_date($t, $tz);
4892 sub process_commit {
4893 my ($c, $r_min, $r_max, $defer) = @_;
4894 if (defined $r_min && defined $r_max) {
4895 if ($r_min == $c->{r} && $r_min == $r_max) {
4896 show_commit($c);
4897 return 0;
4899 return 1 if $r_min == $r_max;
4900 if ($r_min < $r_max) {
4901 # we need to reverse the print order
4902 return 0 if (defined $limit && --$limit < 0);
4903 push @$defer, $c;
4904 return 1;
4906 if ($r_min != $r_max) {
4907 return 1 if ($r_min < $c->{r});
4908 return 1 if ($r_max > $c->{r});
4911 return 0 if (defined $limit && --$limit < 0);
4912 show_commit($c);
4913 return 1;
4916 sub show_commit {
4917 my $c = shift;
4918 if ($oneline) {
4919 my $x = "\n";
4920 if (my $l = $c->{l}) {
4921 while ($l->[0] =~ /^\s*$/) { shift @$l }
4922 $x = $l->[0];
4924 $l_fmt ||= 'A' . length($c->{r});
4925 print 'r',pack($l_fmt, $c->{r}),' | ';
4926 print "$c->{c} | " if $show_commit;
4927 print $x;
4928 } else {
4929 show_commit_normal($c);
4933 sub show_commit_changed_paths {
4934 my ($c) = @_;
4935 return unless $c->{changed};
4936 print "Changed paths:\n", @{$c->{changed}};
4939 sub show_commit_normal {
4940 my ($c) = @_;
4941 print commit_log_separator, "r$c->{r} | ";
4942 print "$c->{c} | " if $show_commit;
4943 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4944 my $nr_line = 0;
4946 if (my $l = $c->{l}) {
4947 while ($l->[$#$l] eq "\n" && $#$l > 0
4948 && $l->[($#$l - 1)] eq "\n") {
4949 pop @$l;
4951 $nr_line = scalar @$l;
4952 if (!$nr_line) {
4953 print "1 line\n\n\n";
4954 } else {
4955 if ($nr_line == 1) {
4956 $nr_line = '1 line';
4957 } else {
4958 $nr_line .= ' lines';
4960 print $nr_line, "\n";
4961 show_commit_changed_paths($c);
4962 print "\n";
4963 print $_ foreach @$l;
4965 } else {
4966 print "1 line\n";
4967 show_commit_changed_paths($c);
4968 print "\n";
4971 foreach my $x (qw/raw stat diff/) {
4972 if ($c->{$x}) {
4973 print "\n";
4974 print $_ foreach @{$c->{$x}}
4979 sub cmd_show_log {
4980 my (@args) = @_;
4981 my ($r_min, $r_max);
4982 my $r_last = -1; # prevent dupes
4983 set_local_timezone();
4984 if (defined $::_revision) {
4985 if ($::_revision =~ /^(\d+):(\d+)$/) {
4986 ($r_min, $r_max) = ($1, $2);
4987 } elsif ($::_revision =~ /^\d+$/) {
4988 $r_min = $r_max = $::_revision;
4989 } else {
4990 ::fatal "-r$::_revision is not supported, use ",
4991 "standard 'git log' arguments instead";
4995 config_pager();
4996 @args = git_svn_log_cmd($r_min, $r_max, @args);
4997 if (!@args) {
4998 print commit_log_separator unless $incremental || $oneline;
4999 return;
5001 my $log = command_output_pipe(@args);
5002 run_pager();
5003 my (@k, $c, $d, $stat);
5004 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5005 while (<$log>) {
5006 if (/^${esc_color}commit -?($::sha1_short)/o) {
5007 my $cmt = $1;
5008 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5009 $r_last = $c->{r};
5010 process_commit($c, $r_min, $r_max, \@k) or
5011 goto out;
5013 $d = undef;
5014 $c = { c => $cmt };
5015 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5016 get_author_info($c, $1, $2, $3);
5017 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5018 # ignore
5019 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5020 push @{$c->{raw}}, $_;
5021 } elsif (/^${esc_color}[ACRMDT]\t/) {
5022 # we could add $SVN->{svn_path} here, but that requires
5023 # remote access at the moment (repo_path_split)...
5024 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5025 push @{$c->{changed}}, $_;
5026 } elsif (/^${esc_color}diff /o) {
5027 $d = 1;
5028 push @{$c->{diff}}, $_;
5029 } elsif ($d) {
5030 push @{$c->{diff}}, $_;
5031 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5032 $esc_color*[\+\-]*$esc_color$/x) {
5033 $stat = 1;
5034 push @{$c->{stat}}, $_;
5035 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5036 push @{$c->{stat}}, $_;
5037 $stat = undef;
5038 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5039 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5040 } elsif (s/^${esc_color} //o) {
5041 push @{$c->{l}}, $_;
5044 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5045 $r_last = $c->{r};
5046 process_commit($c, $r_min, $r_max, \@k);
5048 if (@k) {
5049 ($r_min, $r_max) = ($r_max, $r_min);
5050 process_commit($_, $r_min, $r_max) foreach reverse @k;
5052 out:
5053 close $log;
5054 print commit_log_separator unless $incremental || $oneline;
5057 sub cmd_blame {
5058 my $path = pop;
5060 config_pager();
5061 run_pager();
5063 my ($fh, $ctx, $rev);
5065 if ($_git_format) {
5066 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5067 while (my $line = <$fh>) {
5068 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5069 # Uncommitted edits show up as a rev ID of
5070 # all zeros, which we can't look up with
5071 # cmt_metadata
5072 if ($1 !~ /^0+$/) {
5073 (undef, $rev, undef) =
5074 ::cmt_metadata($1);
5075 $rev = '0' if (!$rev);
5076 } else {
5077 $rev = '0';
5079 $rev = sprintf('%-10s', $rev);
5080 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5082 print $line;
5084 } else {
5085 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5086 '--', $path);
5087 my ($sha1);
5088 my %authors;
5089 my @buffer;
5090 my %dsha; #distinct sha keys
5092 while (my $line = <$fh>) {
5093 push @buffer, $line;
5094 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5095 $dsha{$1} = 1;
5099 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5101 foreach my $line (@buffer) {
5102 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5103 $rev = $s2r->{$1};
5104 $rev = '0' if (!$rev)
5106 elsif ($line =~ /^author (.*)/) {
5107 $authors{$rev} = $1;
5108 $authors{$rev} =~ s/\s/_/g;
5110 elsif ($line =~ /^\t(.*)$/) {
5111 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5115 command_close_pipe($fh, $ctx);
5118 package Git::SVN::Migration;
5119 # these version numbers do NOT correspond to actual version numbers
5120 # of git nor git-svn. They are just relative.
5122 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5124 # v1 layout: .git/$id/info/url, refs/remotes/$id
5126 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5128 # v3 layout: .git/svn/$id, refs/remotes/$id
5129 # - info/url may remain for backwards compatibility
5130 # - this is what we migrate up to this layout automatically,
5131 # - this will be used by git svn init on single branches
5132 # v3.1 layout (auto migrated):
5133 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5134 # for backwards compatibility
5136 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5137 # - this is only created for newly multi-init-ed
5138 # repositories. Similar in spirit to the
5139 # --use-separate-remotes option in git-clone (now default)
5140 # - we do not automatically migrate to this (following
5141 # the example set by core git)
5143 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5144 # - newer, more-efficient format that uses 24-bytes per record
5145 # with no filler space.
5146 # - use xxd -c24 < .rev_map.$UUID to view and debug
5147 # - This is a one-way migration, repositories updated to the
5148 # new format will not be able to use old git-svn without
5149 # rebuilding the .rev_db. Rebuilding the rev_db is not
5150 # possible if noMetadata or useSvmProps are set; but should
5151 # be no problem for users that use the (sensible) defaults.
5152 use strict;
5153 use warnings;
5154 use Carp qw/croak/;
5155 use File::Path qw/mkpath/;
5156 use File::Basename qw/dirname basename/;
5157 use vars qw/$_minimize/;
5159 sub migrate_from_v0 {
5160 my $git_dir = $ENV{GIT_DIR};
5161 return undef unless -d $git_dir;
5162 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5163 my $migrated = 0;
5164 while (<$fh>) {
5165 chomp;
5166 my ($id, $orig_ref) = ($_, $_);
5167 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5168 next unless -f "$git_dir/$id/info/url";
5169 my $new_ref = "refs/remotes/$id";
5170 if (::verify_ref("$new_ref^0")) {
5171 print STDERR "W: $orig_ref is probably an old ",
5172 "branch used by an ancient version of ",
5173 "git-svn.\n",
5174 "However, $new_ref also exists.\n",
5175 "We will not be able ",
5176 "to use this branch until this ",
5177 "ambiguity is resolved.\n";
5178 next;
5180 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5181 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5182 command_noisy('update-ref', $new_ref, $orig_ref);
5183 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5184 $migrated++;
5186 command_close_pipe($fh, $ctx);
5187 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5188 $migrated;
5191 sub migrate_from_v1 {
5192 my $git_dir = $ENV{GIT_DIR};
5193 my $migrated = 0;
5194 return $migrated unless -d $git_dir;
5195 my $svn_dir = "$git_dir/svn";
5197 # just in case somebody used 'svn' as their $id at some point...
5198 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5200 print STDERR "Migrating from a git-svn v1 layout...\n";
5201 mkpath([$svn_dir]);
5202 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5203 "$svn_dir\n\t(required for this version ",
5204 "($::VERSION) of git-svn) does not exist.\n";
5205 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5206 while (<$fh>) {
5207 my $x = $_;
5208 next unless $x =~ s#^refs/remotes/##;
5209 chomp $x;
5210 next unless -f "$git_dir/$x/info/url";
5211 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5212 next unless $u;
5213 my $dn = dirname("$git_dir/svn/$x");
5214 mkpath([$dn]) unless -d $dn;
5215 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5216 mkpath(["$git_dir/svn/svn"]);
5217 print STDERR " - $git_dir/$x/info => ",
5218 "$git_dir/svn/$x/info\n";
5219 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5220 croak "$!: $x";
5221 # don't worry too much about these, they probably
5222 # don't exist with repos this old (save for index,
5223 # and we can easily regenerate that)
5224 foreach my $f (qw/unhandled.log index .rev_db/) {
5225 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5227 } else {
5228 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5229 rename "$git_dir/$x", "$git_dir/svn/$x" or
5230 croak "$!: $x";
5232 $migrated++;
5234 command_close_pipe($fh, $ctx);
5235 print STDERR "Done migrating from a git-svn v1 layout\n";
5236 $migrated;
5239 sub read_old_urls {
5240 my ($l_map, $pfx, $path) = @_;
5241 my @dir;
5242 foreach (<$path/*>) {
5243 if (-r "$_/info/url") {
5244 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5245 my $ref_id = $pfx . basename $_;
5246 my $url = ::file_to_s("$_/info/url");
5247 $l_map->{$ref_id} = $url;
5248 } elsif (-d $_) {
5249 push @dir, $_;
5252 foreach (@dir) {
5253 my $x = $_;
5254 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5255 read_old_urls($l_map, $x, $_);
5259 sub migrate_from_v2 {
5260 my @cfg = command(qw/config -l/);
5261 return if grep /^svn-remote\..+\.url=/, @cfg;
5262 my %l_map;
5263 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5264 my $migrated = 0;
5266 foreach my $ref_id (sort keys %l_map) {
5267 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5268 if ($@) {
5269 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5271 $migrated++;
5273 $migrated;
5276 sub minimize_connections {
5277 my $r = Git::SVN::read_all_remotes();
5278 my $new_urls = {};
5279 my $root_repos = {};
5280 foreach my $repo_id (keys %$r) {
5281 my $url = $r->{$repo_id}->{url} or next;
5282 my $fetch = $r->{$repo_id}->{fetch} or next;
5283 my $ra = Git::SVN::Ra->new($url);
5285 # skip existing cases where we already connect to the root
5286 if (($ra->{url} eq $ra->{repos_root}) ||
5287 ($ra->{repos_root} eq $repo_id)) {
5288 $root_repos->{$ra->{url}} = $repo_id;
5289 next;
5292 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5293 my $root_path = $ra->{url};
5294 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5295 foreach my $path (keys %$fetch) {
5296 my $ref_id = $fetch->{$path};
5297 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5299 # make sure we can read when connecting to
5300 # a higher level of a repository
5301 my ($last_rev, undef) = $gs->last_rev_commit;
5302 if (!defined $last_rev) {
5303 $last_rev = eval {
5304 $root_ra->get_latest_revnum;
5306 next if $@;
5308 my $new = $root_path;
5309 $new .= length $path ? "/$path" : '';
5310 eval {
5311 $root_ra->get_log([$new], $last_rev, $last_rev,
5312 0, 0, 1, sub { });
5314 next if $@;
5315 $new_urls->{$ra->{repos_root}}->{$new} =
5316 { ref_id => $ref_id,
5317 old_repo_id => $repo_id,
5318 old_path => $path };
5322 my @emptied;
5323 foreach my $url (keys %$new_urls) {
5324 # see if we can re-use an existing [svn-remote "repo_id"]
5325 # instead of creating a(n ugly) new section:
5326 my $repo_id = $root_repos->{$url} || $url;
5328 my $fetch = $new_urls->{$url};
5329 foreach my $path (keys %$fetch) {
5330 my $x = $fetch->{$path};
5331 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5332 my $pfx = "svn-remote.$x->{old_repo_id}";
5334 my $old_fetch = quotemeta("$x->{old_path}:".
5335 "refs/remotes/$x->{ref_id}");
5336 command_noisy(qw/config --unset/,
5337 "$pfx.fetch", '^'. $old_fetch . '$');
5338 delete $r->{$x->{old_repo_id}}->
5339 {fetch}->{$x->{old_path}};
5340 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5341 command_noisy(qw/config --unset/,
5342 "$pfx.url");
5343 push @emptied, $x->{old_repo_id}
5347 if (@emptied) {
5348 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5349 print STDERR <<EOF;
5350 The following [svn-remote] sections in your config file ($file) are empty
5351 and can be safely removed:
5353 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5357 sub migration_check {
5358 migrate_from_v0();
5359 migrate_from_v1();
5360 migrate_from_v2();
5361 minimize_connections() if $_minimize;
5364 package Git::IndexInfo;
5365 use strict;
5366 use warnings;
5367 use Git qw/command_input_pipe command_close_pipe/;
5369 sub new {
5370 my ($class) = @_;
5371 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5372 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5375 sub remove {
5376 my ($self, $path) = @_;
5377 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5378 return ++$self->{nr};
5380 undef;
5383 sub update {
5384 my ($self, $mode, $hash, $path) = @_;
5385 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5386 return ++$self->{nr};
5388 undef;
5391 sub DESTROY {
5392 my ($self) = @_;
5393 command_close_pipe($self->{gui}, $self->{ctx});
5396 package Git::SVN::GlobSpec;
5397 use strict;
5398 use warnings;
5400 sub new {
5401 my ($class, $glob) = @_;
5402 my $re = $glob;
5403 $re =~ s!/+$!!g; # no need for trailing slashes
5404 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5405 my $temp = $re;
5406 my ($left, $right) = ($1, $3);
5407 $re = $2;
5408 my $depth = $re =~ tr/*/*/;
5409 if ($depth != $temp =~ tr/*/*/) {
5410 die "Only one set of wildcard directories " .
5411 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5413 if ($depth == 0) {
5414 die "One '*' is needed for glob: '$glob'\n";
5416 $re =~ s!\*!\[^/\]*!g;
5417 $re = quotemeta($left) . "($re)" . quotemeta($right);
5418 if (length $left && !($left =~ s!/+$!!g)) {
5419 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5421 if (length $right && !($right =~ s!^/+!!g)) {
5422 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5424 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5425 bless { left => $left, right => $right, left_regex => $left_re,
5426 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5429 sub full_path {
5430 my ($self, $path) = @_;
5431 return (length $self->{left} ? "$self->{left}/" : '') .
5432 $path . (length $self->{right} ? "/$self->{right}" : '');
5435 __END__
5437 Data structures:
5440 $remotes = { # returned by read_all_remotes()
5441 'svn' => {
5442 # svn-remote.svn.url=https://svn.musicpd.org
5443 url => 'https://svn.musicpd.org',
5444 # svn-remote.svn.fetch=mpd/trunk:trunk
5445 fetch => {
5446 'mpd/trunk' => 'trunk',
5448 # svn-remote.svn.tags=mpd/tags/*:tags/*
5449 tags => {
5450 path => {
5451 left => 'mpd/tags',
5452 right => '',
5453 regex => qr!mpd/tags/([^/]+)$!,
5454 glob => 'tags/*',
5456 ref => {
5457 left => 'tags',
5458 right => '',
5459 regex => qr!tags/([^/]+)$!,
5460 glob => 'tags/*',
5466 $log_entry hashref as returned by libsvn_log_entry()
5468 log => 'whitespace-formatted log entry
5469 ', # trailing newline is preserved
5470 revision => '8', # integer
5471 date => '2004-02-24T17:01:44.108345Z', # commit date
5472 author => 'committer name'
5476 # this is generated by generate_diff();
5477 @mods = array of diff-index line hashes, each element represents one line
5478 of diff-index output
5480 diff-index line ($m hash)
5482 mode_a => first column of diff-index output, no leading ':',
5483 mode_b => second column of diff-index output,
5484 sha1_b => sha1sum of the final blob,
5485 chg => change type [MCRADT],
5486 file_a => original file name of a file (iff chg is 'C' or 'R')
5487 file_b => new/current file name of a file (any chg)
5491 # retval of read_url_paths{,_all}();
5492 $l_map = {
5493 # repository root url
5494 'https://svn.musicpd.org' => {
5495 # repository path # GIT_SVN_ID
5496 'mpd/trunk' => 'trunk',
5497 'mpd/tags/0.11.5' => 'tags/0.11.5',
5501 Notes:
5502 I don't trust the each() function on unless I created %hash myself
5503 because the internal iterator may not have started at base.