Better usage string for reflog.
[git/kusma.git] / git-svn.perl
blobef1d30db3889d0d33b43b1d15cd19281291f5aea
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe
51 command_bidi_pipe command_close_bidi_pipe/) {
52 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
53 Git::SVN::Migration Git::SVN::Log Git::SVN),
54 __PACKAGE__) {
55 *{"${package}::$_"} = \&{"Git::$_"};
60 my ($SVN);
62 $sha1 = qr/[a-f\d]{40}/;
63 $sha1_short = qr/[a-f\d]{4,40}/;
64 my ($_stdin, $_help, $_edit,
65 $_message, $_file,
66 $_template, $_shared,
67 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
68 $_merge, $_strategy, $_dry_run, $_local,
69 $_prefix, $_no_checkout, $_url, $_verbose,
70 $_git_format, $_commit_url, $_tag);
71 $Git::SVN::_follow_parent = 1;
72 $_q ||= 0;
73 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
74 'config-dir=s' => \$Git::SVN::Ra::config_dir,
75 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
76 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
77 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
78 'authors-file|A=s' => \$_authors,
79 'repack:i' => \$Git::SVN::_repack,
80 'noMetadata' => \$Git::SVN::_no_metadata,
81 'useSvmProps' => \$Git::SVN::_use_svm_props,
82 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
83 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
84 'no-checkout' => \$_no_checkout,
85 'quiet|q+' => \$_q,
86 'repack-flags|repack-args|repack-opts=s' =>
87 \$Git::SVN::_repack_flags,
88 'use-log-author' => \$Git::SVN::_use_log_author,
89 'add-author-from' => \$Git::SVN::_add_author_from,
90 'localtime' => \$Git::SVN::_localtime,
91 %remote_opts );
93 my ($_trunk, $_tags, $_branches, $_stdlayout);
94 my %icv;
95 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
96 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
97 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
98 'stdlayout|s' => \$_stdlayout,
99 'minimize-url|m' => \$Git::SVN::_minimize_url,
100 'no-metadata' => sub { $icv{noMetadata} = 1 },
101 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
102 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
103 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
104 %remote_opts );
105 my %cmt_opts = ( 'edit|e' => \$_edit,
106 'rmdir' => \$SVN::Git::Editor::_rmdir,
107 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
108 'l=i' => \$SVN::Git::Editor::_rename_limit,
109 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
112 my %cmd = (
113 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
114 { 'revision|r=s' => \$_revision,
115 'fetch-all|all' => \$_fetch_all,
116 'parent|p' => \$_fetch_parent,
117 %fc_opts } ],
118 clone => [ \&cmd_clone, "Initialize and fetch revisions",
119 { 'revision|r=s' => \$_revision,
120 %fc_opts, %init_opts } ],
121 init => [ \&cmd_init, "Initialize a repo for tracking" .
122 " (requires URL argument)",
123 \%init_opts ],
124 'multi-init' => [ \&cmd_multi_init,
125 "Deprecated alias for ".
126 "'$0 init -T<trunk> -b<branches> -t<tags>'",
127 \%init_opts ],
128 dcommit => [ \&cmd_dcommit,
129 'Commit several diffs to merge with upstream',
130 { 'merge|m|M' => \$_merge,
131 'strategy|s=s' => \$_strategy,
132 'verbose|v' => \$_verbose,
133 'dry-run|n' => \$_dry_run,
134 'fetch-all|all' => \$_fetch_all,
135 'commit-url=s' => \$_commit_url,
136 'revision|r=i' => \$_revision,
137 'no-rebase' => \$_no_rebase,
138 %cmt_opts, %fc_opts } ],
139 branch => [ \&cmd_branch,
140 'Create a branch in the SVN repository',
141 { 'message|m=s' => \$_message,
142 'dry-run|n' => \$_dry_run,
143 'tag|t' => \$_tag } ],
144 tag => [ sub { $_tag = 1; cmd_branch(@_) },
145 'Create a tag in the SVN repository',
146 { 'message|m=s' => \$_message,
147 'dry-run|n' => \$_dry_run } ],
148 'set-tree' => [ \&cmd_set_tree,
149 "Set an SVN repository to a git tree-ish",
150 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
151 'create-ignore' => [ \&cmd_create_ignore,
152 'Create a .gitignore per svn:ignore',
153 { 'revision|r=i' => \$_revision
154 } ],
155 'propget' => [ \&cmd_propget,
156 'Print the value of a property on a file or directory',
157 { 'revision|r=i' => \$_revision } ],
158 'proplist' => [ \&cmd_proplist,
159 'List all properties of a file or directory',
160 { 'revision|r=i' => \$_revision } ],
161 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
162 { 'revision|r=i' => \$_revision
163 } ],
164 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
165 { 'revision|r=i' => \$_revision
166 } ],
167 'multi-fetch' => [ \&cmd_multi_fetch,
168 "Deprecated alias for $0 fetch --all",
169 { 'revision|r=s' => \$_revision, %fc_opts } ],
170 'migrate' => [ sub { },
171 # no-op, we automatically run this anyways,
172 'Migrate configuration/metadata/layout from
173 previous versions of git-svn',
174 { 'minimize' => \$Git::SVN::Migration::_minimize,
175 %remote_opts } ],
176 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
177 { 'limit=i' => \$Git::SVN::Log::limit,
178 'revision|r=s' => \$_revision,
179 'verbose|v' => \$Git::SVN::Log::verbose,
180 'incremental' => \$Git::SVN::Log::incremental,
181 'oneline' => \$Git::SVN::Log::oneline,
182 'show-commit' => \$Git::SVN::Log::show_commit,
183 'non-recursive' => \$Git::SVN::Log::non_recursive,
184 'authors-file|A=s' => \$_authors,
185 'color' => \$Git::SVN::Log::color,
186 'pager=s' => \$Git::SVN::Log::pager
187 } ],
188 'find-rev' => [ \&cmd_find_rev,
189 "Translate between SVN revision numbers and tree-ish",
190 {} ],
191 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
192 { 'merge|m|M' => \$_merge,
193 'verbose|v' => \$_verbose,
194 'strategy|s=s' => \$_strategy,
195 'local|l' => \$_local,
196 'fetch-all|all' => \$_fetch_all,
197 'dry-run|n' => \$_dry_run,
198 %fc_opts } ],
199 'commit-diff' => [ \&cmd_commit_diff,
200 'Commit a diff between two trees',
201 { 'message|m=s' => \$_message,
202 'file|F=s' => \$_file,
203 'revision|r=s' => \$_revision,
204 %cmt_opts } ],
205 'info' => [ \&cmd_info,
206 "Show info about the latest SVN revision
207 on the current branch",
208 { 'url' => \$_url, } ],
209 'blame' => [ \&Git::SVN::Log::cmd_blame,
210 "Show what revision and author last modified each line of a file",
211 { 'git-format' => \$_git_format } ],
214 my $cmd;
215 for (my $i = 0; $i < @ARGV; $i++) {
216 if (defined $cmd{$ARGV[$i]}) {
217 $cmd = $ARGV[$i];
218 splice @ARGV, $i, 1;
219 last;
223 # make sure we're always running at the top-level working directory
224 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
225 unless (-d $ENV{GIT_DIR}) {
226 if ($git_dir_user_set) {
227 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
228 "but it is not a directory\n";
230 my $git_dir = delete $ENV{GIT_DIR};
231 my $cdup = undef;
232 git_cmd_try {
233 $cdup = command_oneline(qw/rev-parse --show-cdup/);
234 $git_dir = '.' unless ($cdup);
235 chomp $cdup if ($cdup);
236 $cdup = "." unless ($cdup && length $cdup);
237 } "Already at toplevel, but $git_dir not found\n";
238 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
239 unless (-d $git_dir) {
240 die "$git_dir still not found after going to ",
241 "'$cdup'\n";
243 $ENV{GIT_DIR} = $git_dir;
245 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
248 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
250 read_repo_config(\%opts);
251 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
252 Getopt::Long::Configure('pass_through');
254 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
255 'minimize-connections' => \$Git::SVN::Migration::_minimize,
256 'id|i=s' => \$Git::SVN::default_ref_id,
257 'svn-remote|remote|R=s' => sub {
258 $Git::SVN::no_reuse_existing = 1;
259 $Git::SVN::default_repo_id = $_[1] });
260 exit 1 if (!$rv && $cmd && $cmd ne 'log');
262 usage(0) if $_help;
263 version() if $_version;
264 usage(1) unless defined $cmd;
265 load_authors() if $_authors;
267 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
268 Git::SVN::Migration::migration_check();
270 Git::SVN::init_vars();
271 eval {
272 Git::SVN::verify_remotes_sanity();
273 $cmd{$cmd}->[0]->(@ARGV);
275 fatal $@ if $@;
276 post_fetch_checkout();
277 exit 0;
279 ####################### primary functions ######################
280 sub usage {
281 my $exit = shift || 0;
282 my $fd = $exit ? \*STDERR : \*STDOUT;
283 print $fd <<"";
284 git-svn - bidirectional operations between a single Subversion tree and git
285 Usage: git svn <command> [options] [arguments]\n
287 print $fd "Available commands:\n" unless $cmd;
289 foreach (sort keys %cmd) {
290 next if $cmd && $cmd ne $_;
291 next if /^multi-/; # don't show deprecated commands
292 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
293 foreach (sort keys %{$cmd{$_}->[2]}) {
294 # mixed-case options are for .git/config only
295 next if /[A-Z]/ && /^[a-z]+$/i;
296 # prints out arguments as they should be passed:
297 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
298 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
299 "--$_" : "-$_" }
300 split /\|/,$_)," $x\n";
303 print $fd <<"";
304 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
305 arbitrary identifier if you're tracking multiple SVN branches/repositories in
306 one git repository and want to keep them separate. See git-svn(1) for more
307 information.
309 exit $exit;
312 sub version {
313 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
314 exit 0;
317 sub do_git_init_db {
318 unless (-d $ENV{GIT_DIR}) {
319 my @init_db = ('init');
320 push @init_db, "--template=$_template" if defined $_template;
321 if (defined $_shared) {
322 if ($_shared =~ /[a-z]/) {
323 push @init_db, "--shared=$_shared";
324 } else {
325 push @init_db, "--shared";
328 command_noisy(@init_db);
329 $_repository = Git->repository(Repository => ".git");
331 command_noisy('config', 'core.autocrlf', 'false');
332 my $set;
333 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
334 foreach my $i (keys %icv) {
335 die "'$set' and '$i' cannot both be set\n" if $set;
336 next unless defined $icv{$i};
337 command_noisy('config', "$pfx.$i", $icv{$i});
338 $set = $i;
340 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
341 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
342 if defined $$ignore_regex;
345 sub init_subdir {
346 my $repo_path = shift or return;
347 mkpath([$repo_path]) unless -d $repo_path;
348 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
349 $ENV{GIT_DIR} = '.git';
350 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
353 sub cmd_clone {
354 my ($url, $path) = @_;
355 if (!defined $path &&
356 (defined $_trunk || defined $_branches || defined $_tags ||
357 defined $_stdlayout) &&
358 $url !~ m#^[a-z\+]+://#) {
359 $path = $url;
361 $path = basename($url) if !defined $path || !length $path;
362 cmd_init($url, $path);
363 Git::SVN::fetch_all($Git::SVN::default_repo_id);
366 sub cmd_init {
367 if (defined $_stdlayout) {
368 $_trunk = 'trunk' if (!defined $_trunk);
369 $_tags = 'tags' if (!defined $_tags);
370 $_branches = 'branches' if (!defined $_branches);
372 if (defined $_trunk || defined $_branches || defined $_tags) {
373 return cmd_multi_init(@_);
375 my $url = shift or die "SVN repository location required ",
376 "as a command-line argument\n";
377 init_subdir(@_);
378 do_git_init_db();
380 Git::SVN->init($url);
383 sub cmd_fetch {
384 if (grep /^\d+=./, @_) {
385 die "'<rev>=<commit>' fetch arguments are ",
386 "no longer supported.\n";
388 my ($remote) = @_;
389 if (@_ > 1) {
390 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
392 if ($_fetch_parent) {
393 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
394 unless ($gs) {
395 die "Unable to determine upstream SVN information from ",
396 "working tree history\n";
398 # just fetch, don't checkout.
399 $_no_checkout = 'true';
400 $_fetch_all ? $gs->fetch_all : $gs->fetch;
401 } elsif ($_fetch_all) {
402 cmd_multi_fetch();
403 } else {
404 $remote ||= $Git::SVN::default_repo_id;
405 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
409 sub cmd_set_tree {
410 my (@commits) = @_;
411 if ($_stdin || !@commits) {
412 print "Reading from stdin...\n";
413 @commits = ();
414 while (<STDIN>) {
415 if (/\b($sha1_short)\b/o) {
416 unshift @commits, $1;
420 my @revs;
421 foreach my $c (@commits) {
422 my @tmp = command('rev-parse',$c);
423 if (scalar @tmp == 1) {
424 push @revs, $tmp[0];
425 } elsif (scalar @tmp > 1) {
426 push @revs, reverse(command('rev-list',@tmp));
427 } else {
428 fatal "Failed to rev-parse $c";
431 my $gs = Git::SVN->new;
432 my ($r_last, $cmt_last) = $gs->last_rev_commit;
433 $gs->fetch;
434 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
435 fatal "There are new revisions that were fetched ",
436 "and need to be merged (or acknowledged) ",
437 "before committing.\nlast rev: $r_last\n",
438 " current: $gs->{last_rev}";
440 $gs->set_tree($_) foreach @revs;
441 print "Done committing ",scalar @revs," revisions to SVN\n";
442 unlink $gs->{index};
445 sub cmd_dcommit {
446 my $head = shift;
447 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
448 'Cannot dcommit with a dirty index. Commit your changes first, '
449 . "or stash them with `git stash'.\n";
450 $head ||= 'HEAD';
451 my @refs;
452 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
453 unless ($gs) {
454 die "Unable to determine upstream SVN information from ",
455 "$head history.\nPerhaps the repository is empty.";
458 if (defined $_commit_url) {
459 $url = $_commit_url;
460 } else {
461 $url = eval { command_oneline('config', '--get',
462 "svn-remote.$gs->{repo_id}.commiturl") };
463 if (!$url) {
464 $url = $gs->full_url
468 my $last_rev = $_revision if defined $_revision;
469 if ($url) {
470 print "Committing to $url ...\n";
472 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
473 if ($_no_rebase && scalar(@$linear_refs) > 1) {
474 warn "Attempting to commit more than one change while ",
475 "--no-rebase is enabled.\n",
476 "If these changes depend on each other, re-running ",
477 "without --no-rebase may be required."
479 my $expect_url = $url;
480 Git::SVN::remove_username($expect_url);
481 while (1) {
482 my $d = shift @$linear_refs or last;
483 unless (defined $last_rev) {
484 (undef, $last_rev, undef) = cmt_metadata("$d~1");
485 unless (defined $last_rev) {
486 fatal "Unable to extract revision information ",
487 "from commit $d~1";
490 if ($_dry_run) {
491 print "diff-tree $d~1 $d\n";
492 } else {
493 my $cmt_rev;
494 my %ed_opts = ( r => $last_rev,
495 log => get_commit_entry($d)->{log},
496 ra => Git::SVN::Ra->new($url),
497 config => SVN::Core::config_get_config(
498 $Git::SVN::Ra::config_dir
500 tree_a => "$d~1",
501 tree_b => $d,
502 editor_cb => sub {
503 print "Committed r$_[0]\n";
504 $cmt_rev = $_[0];
506 svn_path => '');
507 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
508 print "No changes\n$d~1 == $d\n";
509 } elsif ($parents->{$d} && @{$parents->{$d}}) {
510 $gs->{inject_parents_dcommit}->{$cmt_rev} =
511 $parents->{$d};
513 $_fetch_all ? $gs->fetch_all : $gs->fetch;
514 $last_rev = $cmt_rev;
515 next if $_no_rebase;
517 # we always want to rebase against the current HEAD,
518 # not any head that was passed to us
519 my @diff = command('diff-tree', $d,
520 $gs->refname, '--');
521 my @finish;
522 if (@diff) {
523 @finish = rebase_cmd();
524 print STDERR "W: $d and ", $gs->refname,
525 " differ, using @finish:\n",
526 join("\n", @diff), "\n";
527 } else {
528 print "No changes between current HEAD and ",
529 $gs->refname,
530 "\nResetting to the latest ",
531 $gs->refname, "\n";
532 @finish = qw/reset --mixed/;
534 command_noisy(@finish, $gs->refname);
535 if (@diff) {
536 @refs = ();
537 my ($url_, $rev_, $uuid_, $gs_) =
538 working_head_info($head, \@refs);
539 my ($linear_refs_, $parents_) =
540 linearize_history($gs_, \@refs);
541 if (scalar(@$linear_refs) !=
542 scalar(@$linear_refs_)) {
543 fatal "# of revisions changed ",
544 "\nbefore:\n",
545 join("\n", @$linear_refs),
546 "\n\nafter:\n",
547 join("\n", @$linear_refs_), "\n",
548 'If you are attempting to commit ',
549 "merges, try running:\n\t",
550 'git rebase --interactive',
551 '--preserve-merges ',
552 $gs->refname,
553 "\nBefore dcommitting";
555 if ($url_ ne $expect_url) {
556 fatal "URL mismatch after rebase: ",
557 "$url_ != $expect_url";
559 if ($uuid_ ne $uuid) {
560 fatal "uuid mismatch after rebase: ",
561 "$uuid_ != $uuid";
563 # remap parents
564 my (%p, @l, $i);
565 for ($i = 0; $i < scalar @$linear_refs; $i++) {
566 my $new = $linear_refs_->[$i] or next;
567 $p{$new} =
568 $parents->{$linear_refs->[$i]};
569 push @l, $new;
571 $parents = \%p;
572 $linear_refs = \@l;
576 unlink $gs->{index};
579 sub cmd_branch {
580 my ($branch_name, $head) = @_;
582 unless (defined $branch_name && length $branch_name) {
583 die(($_tag ? "tag" : "branch") . " name required\n");
585 $head ||= 'HEAD';
587 my ($src, $rev, undef, $gs) = working_head_info($head);
589 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
590 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
591 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
592 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
594 my $ctx = SVN::Client->new(
595 auth => Git::SVN::Ra::_auth_providers(),
596 log_msg => sub {
597 ${ $_[0] } = defined $_message
598 ? $_message
599 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
600 . $branch_name;
604 eval {
605 $ctx->ls($dst, 'HEAD', 0);
606 } and die "branch ${branch_name} already exists\n";
608 print "Copying ${src} at r${rev} to ${dst}...\n";
609 $ctx->copy($src, $rev, $dst)
610 unless $_dry_run;
612 $gs->fetch_all;
615 sub cmd_find_rev {
616 my $revision_or_hash = shift or die "SVN or git revision required ",
617 "as a command-line argument\n";
618 my $result;
619 if ($revision_or_hash =~ /^r\d+$/) {
620 my $head = shift;
621 $head ||= 'HEAD';
622 my @refs;
623 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
624 unless ($gs) {
625 die "Unable to determine upstream SVN information from ",
626 "$head history\n";
628 my $desired_revision = substr($revision_or_hash, 1);
629 $result = $gs->rev_map_get($desired_revision, $uuid);
630 } else {
631 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
632 $result = $rev;
634 print "$result\n" if $result;
637 sub cmd_rebase {
638 command_noisy(qw/update-index --refresh/);
639 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
640 unless ($gs) {
641 die "Unable to determine upstream SVN information from ",
642 "working tree history\n";
644 if ($_dry_run) {
645 print "Remote Branch: " . $gs->refname . "\n";
646 print "SVN URL: " . $url . "\n";
647 return;
649 if (command(qw/diff-index HEAD --/)) {
650 print STDERR "Cannot rebase with uncommited changes:\n";
651 command_noisy('status');
652 exit 1;
654 unless ($_local) {
655 # rebase will checkout for us, so no need to do it explicitly
656 $_no_checkout = 'true';
657 $_fetch_all ? $gs->fetch_all : $gs->fetch;
659 command_noisy(rebase_cmd(), $gs->refname);
662 sub cmd_show_ignore {
663 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
664 $gs ||= Git::SVN->new;
665 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
666 $gs->prop_walk($gs->{path}, $r, sub {
667 my ($gs, $path, $props) = @_;
668 print STDOUT "\n# $path\n";
669 my $s = $props->{'svn:ignore'} or return;
670 $s =~ s/[\r\n]+/\n/g;
671 chomp $s;
672 $s =~ s#^#$path#gm;
673 print STDOUT "$s\n";
677 sub cmd_show_externals {
678 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
679 $gs ||= Git::SVN->new;
680 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
681 $gs->prop_walk($gs->{path}, $r, sub {
682 my ($gs, $path, $props) = @_;
683 print STDOUT "\n# $path\n";
684 my $s = $props->{'svn:externals'} or return;
685 $s =~ s/[\r\n]+/\n/g;
686 chomp $s;
687 $s =~ s#^#$path#gm;
688 print STDOUT "$s\n";
692 sub cmd_create_ignore {
693 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
694 $gs ||= Git::SVN->new;
695 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
696 $gs->prop_walk($gs->{path}, $r, sub {
697 my ($gs, $path, $props) = @_;
698 # $path is of the form /path/to/dir/
699 $path = '.' . $path;
700 # SVN can have attributes on empty directories,
701 # which git won't track
702 mkpath([$path]) unless -d $path;
703 my $ignore = $path . '.gitignore';
704 my $s = $props->{'svn:ignore'} or return;
705 open(GITIGNORE, '>', $ignore)
706 or fatal("Failed to open `$ignore' for writing: $!");
707 $s =~ s/[\r\n]+/\n/g;
708 chomp $s;
709 # Prefix all patterns so that the ignore doesn't apply
710 # to sub-directories.
711 $s =~ s#^#/#gm;
712 print GITIGNORE "$s\n";
713 close(GITIGNORE)
714 or fatal("Failed to close `$ignore': $!");
715 command_noisy('add', '-f', $ignore);
719 sub canonicalize_path {
720 my ($path) = @_;
721 my $dot_slash_added = 0;
722 if (substr($path, 0, 1) ne "/") {
723 $path = "./" . $path;
724 $dot_slash_added = 1;
726 # File::Spec->canonpath doesn't collapse x/../y into y (for a
727 # good reason), so let's do this manually.
728 $path =~ s#/+#/#g;
729 $path =~ s#/\.(?:/|$)#/#g;
730 $path =~ s#/[^/]+/\.\.##g;
731 $path =~ s#/$##g;
732 $path =~ s#^\./## if $dot_slash_added;
733 $path =~ s#^/##;
734 $path =~ s#^\.$##;
735 return $path;
738 # get_svnprops(PATH)
739 # ------------------
740 # Helper for cmd_propget and cmd_proplist below.
741 sub get_svnprops {
742 my $path = shift;
743 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
744 $gs ||= Git::SVN->new;
746 # prefix THE PATH by the sub-directory from which the user
747 # invoked us.
748 $path = $cmd_dir_prefix . $path;
749 fatal("No such file or directory: $path") unless -e $path;
750 my $is_dir = -d $path ? 1 : 0;
751 $path = $gs->{path} . '/' . $path;
753 # canonicalize the path (otherwise libsvn will abort or fail to
754 # find the file)
755 $path = canonicalize_path($path);
757 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
758 my $props;
759 if ($is_dir) {
760 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
762 else {
763 (undef, $props) = $gs->ra->get_file($path, $r, undef);
765 return $props;
768 # cmd_propget (PROP, PATH)
769 # ------------------------
770 # Print the SVN property PROP for PATH.
771 sub cmd_propget {
772 my ($prop, $path) = @_;
773 $path = '.' if not defined $path;
774 usage(1) if not defined $prop;
775 my $props = get_svnprops($path);
776 if (not defined $props->{$prop}) {
777 fatal("`$path' does not have a `$prop' SVN property.");
779 print $props->{$prop} . "\n";
782 # cmd_proplist (PATH)
783 # -------------------
784 # Print the list of SVN properties for PATH.
785 sub cmd_proplist {
786 my $path = shift;
787 $path = '.' if not defined $path;
788 my $props = get_svnprops($path);
789 print "Properties on '$path':\n";
790 foreach (sort keys %{$props}) {
791 print " $_\n";
795 sub cmd_multi_init {
796 my $url = shift;
797 unless (defined $_trunk || defined $_branches || defined $_tags) {
798 usage(1);
801 # there are currently some bugs that prevent multi-init/multi-fetch
802 # setups from working well without this.
803 $Git::SVN::_minimize_url = 1;
805 $_prefix = '' unless defined $_prefix;
806 if (defined $url) {
807 $url =~ s#/+$##;
808 init_subdir(@_);
810 do_git_init_db();
811 if (defined $_trunk) {
812 my $trunk_ref = $_prefix . 'trunk';
813 # try both old-style and new-style lookups:
814 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
815 unless ($gs_trunk) {
816 my ($trunk_url, $trunk_path) =
817 complete_svn_url($url, $_trunk);
818 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
819 undef, $trunk_ref);
822 return unless defined $_branches || defined $_tags;
823 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
824 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
825 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
828 sub cmd_multi_fetch {
829 my $remotes = Git::SVN::read_all_remotes();
830 foreach my $repo_id (sort keys %$remotes) {
831 if ($remotes->{$repo_id}->{url}) {
832 Git::SVN::fetch_all($repo_id, $remotes);
837 # this command is special because it requires no metadata
838 sub cmd_commit_diff {
839 my ($ta, $tb, $url) = @_;
840 my $usage = "Usage: $0 commit-diff -r<revision> ".
841 "<tree-ish> <tree-ish> [<URL>]";
842 fatal($usage) if (!defined $ta || !defined $tb);
843 my $svn_path = '';
844 if (!defined $url) {
845 my $gs = eval { Git::SVN->new };
846 if (!$gs) {
847 fatal("Needed URL or usable git-svn --id in ",
848 "the command-line\n", $usage);
850 $url = $gs->{url};
851 $svn_path = $gs->{path};
853 unless (defined $_revision) {
854 fatal("-r|--revision is a required argument\n", $usage);
856 if (defined $_message && defined $_file) {
857 fatal("Both --message/-m and --file/-F specified ",
858 "for the commit message.\n",
859 "I have no idea what you mean");
861 if (defined $_file) {
862 $_message = file_to_s($_file);
863 } else {
864 $_message ||= get_commit_entry($tb)->{log};
866 my $ra ||= Git::SVN::Ra->new($url);
867 my $r = $_revision;
868 if ($r eq 'HEAD') {
869 $r = $ra->get_latest_revnum;
870 } elsif ($r !~ /^\d+$/) {
871 die "revision argument: $r not understood by git-svn\n";
873 my %ed_opts = ( r => $r,
874 log => $_message,
875 ra => $ra,
876 tree_a => $ta,
877 tree_b => $tb,
878 editor_cb => sub { print "Committed r$_[0]\n" },
879 svn_path => $svn_path );
880 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
881 print "No changes\n$ta == $tb\n";
885 sub escape_uri_only {
886 my ($uri) = @_;
887 my @tmp;
888 foreach (split m{/}, $uri) {
889 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
890 push @tmp, $_;
892 join('/', @tmp);
895 sub escape_url {
896 my ($url) = @_;
897 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
898 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
899 $url = "$scheme://$domain$uri";
901 $url;
904 sub cmd_info {
905 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
906 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
907 if (exists $_[1]) {
908 die "Too many arguments specified\n";
911 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
913 if (!$file_type && !$diff_status) {
914 print STDERR "svn: '$path' is not under version control\n";
915 exit 1;
918 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
919 unless ($gs) {
920 die "Unable to determine upstream SVN information from ",
921 "working tree history\n";
924 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
925 $path = "." if $path eq "";
927 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
929 if ($_url) {
930 print escape_url($full_url), "\n";
931 return;
934 my $result = "Path: $path\n";
935 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
936 $result .= "URL: " . escape_url($full_url) . "\n";
938 eval {
939 my $repos_root = $gs->repos_root;
940 Git::SVN::remove_username($repos_root);
941 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
943 if ($@) {
944 $result .= "Repository Root: (offline)\n";
946 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
947 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
948 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
950 $result .= "Node Kind: " .
951 ($file_type eq "dir" ? "directory" : "file") . "\n";
953 my $schedule = $diff_status eq "A"
954 ? "add"
955 : ($diff_status eq "D" ? "delete" : "normal");
956 $result .= "Schedule: $schedule\n";
958 if ($diff_status eq "A") {
959 print $result, "\n";
960 return;
963 my ($lc_author, $lc_rev, $lc_date_utc);
964 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
965 my $log = command_output_pipe(@args);
966 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
967 while (<$log>) {
968 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
969 $lc_author = $1;
970 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
971 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
972 (undef, $lc_rev, undef) = ::extract_metadata($1);
975 close $log;
977 Git::SVN::Log::set_local_timezone();
979 $result .= "Last Changed Author: $lc_author\n";
980 $result .= "Last Changed Rev: $lc_rev\n";
981 $result .= "Last Changed Date: " .
982 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
984 if ($file_type ne "dir") {
985 my $text_last_updated_date =
986 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
987 $result .=
988 "Text Last Updated: " .
989 Git::SVN::Log::format_svn_date($text_last_updated_date) .
990 "\n";
991 my $checksum;
992 if ($diff_status eq "D") {
993 my ($fh, $ctx) =
994 command_output_pipe(qw(cat-file blob), "HEAD:$path");
995 if ($file_type eq "link") {
996 my $file_name = <$fh>;
997 $checksum = md5sum("link $file_name");
998 } else {
999 $checksum = md5sum($fh);
1001 command_close_pipe($fh, $ctx);
1002 } elsif ($file_type eq "link") {
1003 my $file_name =
1004 command(qw(cat-file blob), "HEAD:$path");
1005 $checksum =
1006 md5sum("link " . $file_name);
1007 } else {
1008 open FILE, "<", $path or die $!;
1009 $checksum = md5sum(\*FILE);
1010 close FILE or die $!;
1012 $result .= "Checksum: " . $checksum . "\n";
1015 print $result, "\n";
1018 ########################### utility functions #########################
1020 sub rebase_cmd {
1021 my @cmd = qw/rebase/;
1022 push @cmd, '-v' if $_verbose;
1023 push @cmd, qw/--merge/ if $_merge;
1024 push @cmd, "--strategy=$_strategy" if $_strategy;
1025 @cmd;
1028 sub post_fetch_checkout {
1029 return if $_no_checkout;
1030 my $gs = $Git::SVN::_head or return;
1031 return if verify_ref('refs/heads/master^0');
1033 my $valid_head = verify_ref('HEAD^0');
1034 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1035 return if ($valid_head || !verify_ref('HEAD^0'));
1037 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1038 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1039 return if -f $index;
1041 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1042 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1043 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1044 print STDERR "Checked out HEAD:\n ",
1045 $gs->full_url, " r", $gs->last_rev, "\n";
1048 sub complete_svn_url {
1049 my ($url, $path) = @_;
1050 $path =~ s#/+$##;
1051 if ($path !~ m#^[a-z\+]+://#) {
1052 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1053 fatal("E: '$path' is not a complete URL ",
1054 "and a separate URL is not specified");
1056 return ($url, $path);
1058 return ($path, '');
1061 sub complete_url_ls_init {
1062 my ($ra, $repo_path, $switch, $pfx) = @_;
1063 unless ($repo_path) {
1064 print STDERR "W: $switch not specified\n";
1065 return;
1067 $repo_path =~ s#/+$##;
1068 if ($repo_path =~ m#^[a-z\+]+://#) {
1069 $ra = Git::SVN::Ra->new($repo_path);
1070 $repo_path = '';
1071 } else {
1072 $repo_path =~ s#^/+##;
1073 unless ($ra) {
1074 fatal("E: '$repo_path' is not a complete URL ",
1075 "and a separate URL is not specified");
1078 my $url = $ra->{url};
1079 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1080 my $k = "svn-remote.$gs->{repo_id}.url";
1081 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1082 if ($orig_url && ($orig_url ne $gs->{url})) {
1083 die "$k already set: $orig_url\n",
1084 "wanted to set to: $gs->{url}\n";
1086 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1087 my $remote_path = "$ra->{svn_path}/$repo_path";
1088 $remote_path =~ s#/+#/#g;
1089 $remote_path =~ s#^/##g;
1090 $remote_path .= "/*" if $remote_path !~ /\*/;
1091 my ($n) = ($switch =~ /^--(\w+)/);
1092 if (length $pfx && $pfx !~ m#/$#) {
1093 die "--prefix='$pfx' must have a trailing slash '/'\n";
1095 command_noisy('config',
1096 "svn-remote.$gs->{repo_id}.$n",
1097 "$remote_path:refs/remotes/$pfx*" .
1098 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1101 sub verify_ref {
1102 my ($ref) = @_;
1103 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1104 { STDERR => 0 }); };
1107 sub get_tree_from_treeish {
1108 my ($treeish) = @_;
1109 # $treeish can be a symbolic ref, too:
1110 my $type = command_oneline(qw/cat-file -t/, $treeish);
1111 my $expected;
1112 while ($type eq 'tag') {
1113 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1115 if ($type eq 'commit') {
1116 $expected = (grep /^tree /, command(qw/cat-file commit/,
1117 $treeish))[0];
1118 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1119 die "Unable to get tree from $treeish\n" unless $expected;
1120 } elsif ($type eq 'tree') {
1121 $expected = $treeish;
1122 } else {
1123 die "$treeish is a $type, expected tree, tag or commit\n";
1125 return $expected;
1128 sub get_commit_entry {
1129 my ($treeish) = shift;
1130 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1131 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1132 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1133 open my $log_fh, '>', $commit_editmsg or croak $!;
1135 my $type = command_oneline(qw/cat-file -t/, $treeish);
1136 if ($type eq 'commit' || $type eq 'tag') {
1137 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1138 $type, $treeish);
1139 my $in_msg = 0;
1140 my $author;
1141 my $saw_from = 0;
1142 my $msgbuf = "";
1143 while (<$msg_fh>) {
1144 if (!$in_msg) {
1145 $in_msg = 1 if (/^\s*$/);
1146 $author = $1 if (/^author (.*>)/);
1147 } elsif (/^git-svn-id: /) {
1148 # skip this for now, we regenerate the
1149 # correct one on re-fetch anyways
1150 # TODO: set *:merge properties or like...
1151 } else {
1152 if (/^From:/ || /^Signed-off-by:/) {
1153 $saw_from = 1;
1155 $msgbuf .= $_;
1158 $msgbuf =~ s/\s+$//s;
1159 if ($Git::SVN::_add_author_from && defined($author)
1160 && !$saw_from) {
1161 $msgbuf .= "\n\nFrom: $author";
1163 print $log_fh $msgbuf or croak $!;
1164 command_close_pipe($msg_fh, $ctx);
1166 close $log_fh or croak $!;
1168 if ($_edit || ($type eq 'tree')) {
1169 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1170 # TODO: strip out spaces, comments, like git-commit.sh
1171 system($editor, $commit_editmsg);
1173 rename $commit_editmsg, $commit_msg or croak $!;
1175 # SVN requires messages to be UTF-8 when entering the repo
1176 local $/;
1177 open $log_fh, '<', $commit_msg or croak $!;
1178 binmode $log_fh;
1179 chomp($log_entry{log} = <$log_fh>);
1181 if (my $enc = Git::config('i18n.commitencoding')) {
1182 require Encode;
1183 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1185 close $log_fh or croak $!;
1187 unlink $commit_msg;
1188 \%log_entry;
1191 sub s_to_file {
1192 my ($str, $file, $mode) = @_;
1193 open my $fd,'>',$file or croak $!;
1194 print $fd $str,"\n" or croak $!;
1195 close $fd or croak $!;
1196 chmod ($mode &~ umask, $file) if (defined $mode);
1199 sub file_to_s {
1200 my $file = shift;
1201 open my $fd,'<',$file or croak "$!: file: $file\n";
1202 local $/;
1203 my $ret = <$fd>;
1204 close $fd or croak $!;
1205 $ret =~ s/\s*$//s;
1206 return $ret;
1209 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1210 sub load_authors {
1211 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1212 my $log = $cmd eq 'log';
1213 while (<$authors>) {
1214 chomp;
1215 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1216 my ($user, $name, $email) = ($1, $2, $3);
1217 if ($log) {
1218 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1219 } else {
1220 $users{$user} = [$name, $email];
1223 close $authors or croak $!;
1226 # convert GetOpt::Long specs for use by git-config
1227 sub read_repo_config {
1228 return unless -d $ENV{GIT_DIR};
1229 my $opts = shift;
1230 my @config_only;
1231 foreach my $o (keys %$opts) {
1232 # if we have mixedCase and a long option-only, then
1233 # it's a config-only variable that we don't need for
1234 # the command-line.
1235 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1236 my $v = $opts->{$o};
1237 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1238 $key =~ s/-//g;
1239 my $arg = 'git config';
1240 $arg .= ' --int' if ($o =~ /[:=]i$/);
1241 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1242 if (ref $v eq 'ARRAY') {
1243 chomp(my @tmp = `$arg --get-all svn.$key`);
1244 @$v = @tmp if @tmp;
1245 } else {
1246 chomp(my $tmp = `$arg --get svn.$key`);
1247 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1248 $$v = $tmp;
1252 delete @$opts{@config_only} if @config_only;
1255 sub extract_metadata {
1256 my $id = shift or return (undef, undef, undef);
1257 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1258 \s([a-f\d\-]+)$/x);
1259 if (!defined $rev || !$uuid || !$url) {
1260 # some of the original repositories I made had
1261 # identifiers like this:
1262 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1264 return ($url, $rev, $uuid);
1267 sub cmt_metadata {
1268 return extract_metadata((grep(/^git-svn-id: /,
1269 command(qw/cat-file commit/, shift)))[-1]);
1272 sub cmt_sha2rev_batch {
1273 my %s2r;
1274 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1275 my $list = shift;
1277 foreach my $sha (@{$list}) {
1278 my $first = 1;
1279 my $size = 0;
1280 print $out $sha, "\n";
1282 while (my $line = <$in>) {
1283 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1284 last;
1285 } elsif ($first &&
1286 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1287 $first = 0;
1288 $size = $1;
1289 next;
1290 } elsif ($line =~ /^(git-svn-id: )/) {
1291 my (undef, $rev, undef) =
1292 extract_metadata($line);
1293 $s2r{$sha} = $rev;
1296 $size -= length($line);
1297 last if ($size == 0);
1301 command_close_bidi_pipe($pid, $in, $out, $ctx);
1303 return \%s2r;
1306 sub working_head_info {
1307 my ($head, $refs) = @_;
1308 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1309 my ($fh, $ctx) = command_output_pipe(@args, $head);
1310 my $hash;
1311 my %max;
1312 while (<$fh>) {
1313 if ( m{^commit ($::sha1)$} ) {
1314 unshift @$refs, $hash if $hash and $refs;
1315 $hash = $1;
1316 next;
1318 next unless s{^\s*(git-svn-id:)}{$1};
1319 my ($url, $rev, $uuid) = extract_metadata($_);
1320 if (defined $url && defined $rev) {
1321 next if $max{$url} and $max{$url} < $rev;
1322 if (my $gs = Git::SVN->find_by_url($url)) {
1323 my $c = $gs->rev_map_get($rev, $uuid);
1324 if ($c && $c eq $hash) {
1325 close $fh; # break the pipe
1326 return ($url, $rev, $uuid, $gs);
1327 } else {
1328 $max{$url} ||= $gs->rev_map_max;
1333 command_close_pipe($fh, $ctx);
1334 (undef, undef, undef, undef);
1337 sub read_commit_parents {
1338 my ($parents, $c) = @_;
1339 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1340 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1341 @{$parents->{$c}} = split(/ /, $p);
1344 sub linearize_history {
1345 my ($gs, $refs) = @_;
1346 my %parents;
1347 foreach my $c (@$refs) {
1348 read_commit_parents(\%parents, $c);
1351 my @linear_refs;
1352 my %skip = ();
1353 my $last_svn_commit = $gs->last_commit;
1354 foreach my $c (reverse @$refs) {
1355 next if $c eq $last_svn_commit;
1356 last if $skip{$c};
1358 unshift @linear_refs, $c;
1359 $skip{$c} = 1;
1361 # we only want the first parent to diff against for linear
1362 # history, we save the rest to inject when we finalize the
1363 # svn commit
1364 my $fp_a = verify_ref("$c~1");
1365 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1366 if (!$fp_a || !$fp_b) {
1367 die "Commit $c\n",
1368 "has no parent commit, and therefore ",
1369 "nothing to diff against.\n",
1370 "You should be working from a repository ",
1371 "originally created by git-svn\n";
1373 if ($fp_a ne $fp_b) {
1374 die "$c~1 = $fp_a, however parsing commit $c ",
1375 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1378 foreach my $p (@{$parents{$c}}) {
1379 $skip{$p} = 1;
1382 (\@linear_refs, \%parents);
1385 sub find_file_type_and_diff_status {
1386 my ($path) = @_;
1387 return ('dir', '') if $path eq '';
1389 my $diff_output =
1390 command_oneline(qw(diff --cached --name-status --), $path) || "";
1391 my $diff_status = (split(' ', $diff_output))[0] || "";
1393 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1395 return (undef, undef) if !$diff_status && !$ls_tree;
1397 if ($diff_status eq "A") {
1398 return ("link", $diff_status) if -l $path;
1399 return ("dir", $diff_status) if -d $path;
1400 return ("file", $diff_status);
1403 my $mode = (split(' ', $ls_tree))[0] || "";
1405 return ("link", $diff_status) if $mode eq "120000";
1406 return ("dir", $diff_status) if $mode eq "040000";
1407 return ("file", $diff_status);
1410 sub md5sum {
1411 my $arg = shift;
1412 my $ref = ref $arg;
1413 my $md5 = Digest::MD5->new();
1414 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1415 $md5->addfile($arg) or croak $!;
1416 } elsif ($ref eq 'SCALAR') {
1417 $md5->add($$arg) or croak $!;
1418 } elsif (!$ref) {
1419 $md5->add($arg) or croak $!;
1420 } else {
1421 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1423 return $md5->hexdigest();
1426 package Git::SVN;
1427 use strict;
1428 use warnings;
1429 use Fcntl qw/:DEFAULT :seek/;
1430 use constant rev_map_fmt => 'NH40';
1431 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1432 $_repack $_repack_flags $_use_svm_props $_head
1433 $_use_svnsync_props $no_reuse_existing $_minimize_url
1434 $_use_log_author $_add_author_from $_localtime/;
1435 use Carp qw/croak/;
1436 use File::Path qw/mkpath/;
1437 use File::Copy qw/copy/;
1438 use IPC::Open3;
1440 my ($_gc_nr, $_gc_period);
1442 # properties that we do not log:
1443 my %SKIP_PROP;
1444 BEGIN {
1445 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1446 svn:special svn:executable
1447 svn:entry:committed-rev
1448 svn:entry:last-author
1449 svn:entry:uuid
1450 svn:entry:committed-date/;
1452 # some options are read globally, but can be overridden locally
1453 # per [svn-remote "..."] section. Command-line options will *NOT*
1454 # override options set in an [svn-remote "..."] section
1455 no strict 'refs';
1456 for my $option (qw/follow_parent no_metadata use_svm_props
1457 use_svnsync_props/) {
1458 my $key = $option;
1459 $key =~ tr/_//d;
1460 my $prop = "-$option";
1461 *$option = sub {
1462 my ($self) = @_;
1463 return $self->{$prop} if exists $self->{$prop};
1464 my $k = "svn-remote.$self->{repo_id}.$key";
1465 eval { command_oneline(qw/config --get/, $k) };
1466 if ($@) {
1467 $self->{$prop} = ${"Git::SVN::_$option"};
1468 } else {
1469 my $v = command_oneline(qw/config --bool/,$k);
1470 $self->{$prop} = $v eq 'false' ? 0 : 1;
1472 return $self->{$prop};
1478 my (%LOCKFILES, %INDEX_FILES);
1479 END {
1480 unlink keys %LOCKFILES if %LOCKFILES;
1481 unlink keys %INDEX_FILES if %INDEX_FILES;
1484 sub resolve_local_globs {
1485 my ($url, $fetch, $glob_spec) = @_;
1486 return unless defined $glob_spec;
1487 my $ref = $glob_spec->{ref};
1488 my $path = $glob_spec->{path};
1489 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1490 next unless m#^refs/remotes/$ref->{regex}$#;
1491 my $p = $1;
1492 my $pathname = desanitize_refname($path->full_path($p));
1493 my $refname = desanitize_refname($ref->full_path($p));
1494 if (my $existing = $fetch->{$pathname}) {
1495 if ($existing ne $refname) {
1496 die "Refspec conflict:\n",
1497 "existing: refs/remotes/$existing\n",
1498 " globbed: refs/remotes/$refname\n";
1500 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1501 $u =~ s!^\Q$url\E(/|$)!! or die
1502 "refs/remotes/$refname: '$url' not found in '$u'\n";
1503 if ($pathname ne $u) {
1504 warn "W: Refspec glob conflict ",
1505 "(ref: refs/remotes/$refname):\n",
1506 "expected path: $pathname\n",
1507 " real path: $u\n",
1508 "Continuing ahead with $u\n";
1509 next;
1511 } else {
1512 $fetch->{$pathname} = $refname;
1517 sub parse_revision_argument {
1518 my ($base, $head) = @_;
1519 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1520 return ($base, $head);
1522 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1523 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1524 return ($head, $head) if ($::_revision eq 'HEAD');
1525 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1526 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1527 die "revision argument: $::_revision not understood by git-svn\n";
1530 sub fetch_all {
1531 my ($repo_id, $remotes) = @_;
1532 if (ref $repo_id) {
1533 my $gs = $repo_id;
1534 $repo_id = undef;
1535 $repo_id = $gs->{repo_id};
1537 $remotes ||= read_all_remotes();
1538 my $remote = $remotes->{$repo_id} or
1539 die "[svn-remote \"$repo_id\"] unknown\n";
1540 my $fetch = $remote->{fetch};
1541 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1542 my (@gs, @globs);
1543 my $ra = Git::SVN::Ra->new($url);
1544 my $uuid = $ra->get_uuid;
1545 my $head = $ra->get_latest_revnum;
1546 my $base = defined $fetch ? $head : 0;
1548 # read the max revs for wildcard expansion (branches/*, tags/*)
1549 foreach my $t (qw/branches tags/) {
1550 defined $remote->{$t} or next;
1551 push @globs, $remote->{$t};
1552 my $max_rev = eval { tmp_config(qw/--int --get/,
1553 "svn-remote.$repo_id.${t}-maxRev") };
1554 if (defined $max_rev && ($max_rev < $base)) {
1555 $base = $max_rev;
1556 } elsif (!defined $max_rev) {
1557 $base = 0;
1561 if ($fetch) {
1562 foreach my $p (sort keys %$fetch) {
1563 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1564 my $lr = $gs->rev_map_max;
1565 if (defined $lr) {
1566 $base = $lr if ($lr < $base);
1568 push @gs, $gs;
1572 ($base, $head) = parse_revision_argument($base, $head);
1573 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1576 sub read_all_remotes {
1577 my $r = {};
1578 my $use_svm_props = eval { command_oneline(qw/config --bool
1579 svn.useSvmProps/) };
1580 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1581 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1582 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1583 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1584 die("svn-remote.$remote: remote ref '$_remote_ref' "
1585 . "must start with 'refs/remotes/'\n")
1586 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1587 my $remote_ref = $1;
1588 $local_ref =~ s{^/}{};
1589 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1590 $r->{$remote}->{svm} = {} if $use_svm_props;
1591 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1592 $r->{$1}->{svm} = {};
1593 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1594 $r->{$1}->{url} = $2;
1595 } elsif (m!^(.+)\.(branches|tags)=
1596 (.*):refs/remotes/(.+)\s*$/!x) {
1597 my ($p, $g) = ($3, $4);
1598 my $rs = $r->{$1}->{$2} = {
1599 t => $2,
1600 remote => $1,
1601 path => Git::SVN::GlobSpec->new($p),
1602 ref => Git::SVN::GlobSpec->new($g) };
1603 if (length($rs->{ref}->{right}) != 0) {
1604 die "The '*' glob character must be the last ",
1605 "character of '$g'\n";
1610 map {
1611 if (defined $r->{$_}->{svm}) {
1612 my $svm;
1613 eval {
1614 my $section = "svn-remote.$_";
1615 $svm = {
1616 source => tmp_config('--get',
1617 "$section.svm-source"),
1618 replace => tmp_config('--get',
1619 "$section.svm-replace"),
1622 $r->{$_}->{svm} = $svm;
1624 } keys %$r;
1629 sub init_vars {
1630 $_gc_nr = $_gc_period = 1000;
1631 if (defined $_repack || defined $_repack_flags) {
1632 warn "Repack options are obsolete; they have no effect.\n";
1636 sub verify_remotes_sanity {
1637 return unless -d $ENV{GIT_DIR};
1638 my %seen;
1639 foreach (command(qw/config -l/)) {
1640 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1641 if ($seen{$1}) {
1642 die "Remote ref refs/remote/$1 is tracked by",
1643 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1644 "Please resolve this ambiguity in ",
1645 "your git configuration file before ",
1646 "continuing\n";
1648 $seen{$1} = $_;
1653 sub find_existing_remote {
1654 my ($url, $remotes) = @_;
1655 return undef if $no_reuse_existing;
1656 my $existing;
1657 foreach my $repo_id (keys %$remotes) {
1658 my $u = $remotes->{$repo_id}->{url} or next;
1659 next if $u ne $url;
1660 $existing = $repo_id;
1661 last;
1663 $existing;
1666 sub init_remote_config {
1667 my ($self, $url, $no_write) = @_;
1668 $url =~ s!/+$!!; # strip trailing slash
1669 my $r = read_all_remotes();
1670 my $existing = find_existing_remote($url, $r);
1671 if ($existing) {
1672 unless ($no_write) {
1673 print STDERR "Using existing ",
1674 "[svn-remote \"$existing\"]\n";
1676 $self->{repo_id} = $existing;
1677 } elsif ($_minimize_url) {
1678 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1679 $existing = find_existing_remote($min_url, $r);
1680 if ($existing) {
1681 unless ($no_write) {
1682 print STDERR "Using existing ",
1683 "[svn-remote \"$existing\"]\n";
1685 $self->{repo_id} = $existing;
1687 if ($min_url ne $url) {
1688 unless ($no_write) {
1689 print STDERR "Using higher level of URL: ",
1690 "$url => $min_url\n";
1692 my $old_path = $self->{path};
1693 $self->{path} = $url;
1694 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1695 if (length $old_path) {
1696 $self->{path} .= "/$old_path";
1698 $url = $min_url;
1701 my $orig_url;
1702 if (!$existing) {
1703 # verify that we aren't overwriting anything:
1704 $orig_url = eval {
1705 command_oneline('config', '--get',
1706 "svn-remote.$self->{repo_id}.url")
1708 if ($orig_url && ($orig_url ne $url)) {
1709 die "svn-remote.$self->{repo_id}.url already set: ",
1710 "$orig_url\nwanted to set to: $url\n";
1713 my ($xrepo_id, $xpath) = find_ref($self->refname);
1714 if (defined $xpath) {
1715 die "svn-remote.$xrepo_id.fetch already set to track ",
1716 "$xpath:refs/remotes/", $self->refname, "\n";
1718 unless ($no_write) {
1719 command_noisy('config',
1720 "svn-remote.$self->{repo_id}.url", $url);
1721 $self->{path} =~ s{^/}{};
1722 command_noisy('config', '--add',
1723 "svn-remote.$self->{repo_id}.fetch",
1724 "$self->{path}:".$self->refname);
1726 $self->{url} = $url;
1729 sub find_by_url { # repos_root and, path are optional
1730 my ($class, $full_url, $repos_root, $path) = @_;
1732 return undef unless defined $full_url;
1733 remove_username($full_url);
1734 remove_username($repos_root) if defined $repos_root;
1735 my $remotes = read_all_remotes();
1736 if (defined $full_url && defined $repos_root && !defined $path) {
1737 $path = $full_url;
1738 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1740 foreach my $repo_id (keys %$remotes) {
1741 my $u = $remotes->{$repo_id}->{url} or next;
1742 remove_username($u);
1743 next if defined $repos_root && $repos_root ne $u;
1745 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1746 foreach (qw/branches tags/) {
1747 resolve_local_globs($u, $fetch,
1748 $remotes->{$repo_id}->{$_});
1750 my $p = $path;
1751 my $rwr = rewrite_root({repo_id => $repo_id});
1752 my $svm = $remotes->{$repo_id}->{svm}
1753 if defined $remotes->{$repo_id}->{svm};
1754 unless (defined $p) {
1755 $p = $full_url;
1756 my $z = $u;
1757 my $prefix = '';
1758 if ($rwr) {
1759 $z = $rwr;
1760 remove_username($z);
1761 } elsif (defined $svm) {
1762 $z = $svm->{source};
1763 $prefix = $svm->{replace};
1764 $prefix =~ s#^\Q$u\E(?:/|$)##;
1765 $prefix =~ s#/$##;
1767 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1769 foreach my $f (keys %$fetch) {
1770 next if $f ne $p;
1771 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1774 undef;
1777 sub init {
1778 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1779 my $self = _new($class, $repo_id, $ref_id, $path);
1780 if (defined $url) {
1781 $self->init_remote_config($url, $no_write);
1783 $self;
1786 sub find_ref {
1787 my ($ref_id) = @_;
1788 foreach (command(qw/config -l/)) {
1789 next unless m!^svn-remote\.(.+)\.fetch=
1790 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1791 my ($repo_id, $path, $ref) = ($1, $2, $3);
1792 if ($ref eq $ref_id) {
1793 $path = '' if ($path =~ m#^\./?#);
1794 return ($repo_id, $path);
1797 (undef, undef, undef);
1800 sub new {
1801 my ($class, $ref_id, $repo_id, $path) = @_;
1802 if (defined $ref_id && !defined $repo_id && !defined $path) {
1803 ($repo_id, $path) = find_ref($ref_id);
1804 if (!defined $repo_id) {
1805 die "Could not find a \"svn-remote.*.fetch\" key ",
1806 "in the repository configuration matching: ",
1807 "refs/remotes/$ref_id\n";
1810 my $self = _new($class, $repo_id, $ref_id, $path);
1811 if (!defined $self->{path} || !length $self->{path}) {
1812 my $fetch = command_oneline('config', '--get',
1813 "svn-remote.$repo_id.fetch",
1814 ":refs/remotes/$ref_id\$") or
1815 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1816 "\":refs/remotes/$ref_id\$\" in config\n";
1817 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1819 $self->{url} = command_oneline('config', '--get',
1820 "svn-remote.$repo_id.url") or
1821 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1822 $self->rebuild;
1823 $self;
1826 sub refname {
1827 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1829 # It cannot end with a slash /, we'll throw up on this because
1830 # SVN can't have directories with a slash in their name, either:
1831 if ($refname =~ m{/$}) {
1832 die "ref: '$refname' ends with a trailing slash, this is ",
1833 "not permitted by git nor Subversion\n";
1836 # It cannot have ASCII control character space, tilde ~, caret ^,
1837 # colon :, question-mark ?, asterisk *, space, or open bracket [
1838 # anywhere.
1840 # Additionally, % must be escaped because it is used for escaping
1841 # and we want our escaped refname to be reversible
1842 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1844 # no slash-separated component can begin with a dot .
1845 # /.* becomes /%2E*
1846 $refname =~ s{/\.}{/%2E}g;
1848 # It cannot have two consecutive dots .. anywhere
1849 # .. becomes %2E%2E
1850 $refname =~ s{\.\.}{%2E%2E}g;
1852 return $refname;
1855 sub desanitize_refname {
1856 my ($refname) = @_;
1857 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1858 return $refname;
1861 sub svm_uuid {
1862 my ($self) = @_;
1863 return $self->{svm}->{uuid} if $self->svm;
1864 $self->ra;
1865 unless ($self->{svm}) {
1866 die "SVM UUID not cached, and reading remotely failed\n";
1868 $self->{svm}->{uuid};
1871 sub svm {
1872 my ($self) = @_;
1873 return $self->{svm} if $self->{svm};
1874 my $svm;
1875 # see if we have it in our config, first:
1876 eval {
1877 my $section = "svn-remote.$self->{repo_id}";
1878 $svm = {
1879 source => tmp_config('--get', "$section.svm-source"),
1880 uuid => tmp_config('--get', "$section.svm-uuid"),
1881 replace => tmp_config('--get', "$section.svm-replace"),
1884 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1885 $self->{svm} = $svm;
1887 $self->{svm};
1890 sub _set_svm_vars {
1891 my ($self, $ra) = @_;
1892 return $ra if $self->svm;
1894 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1895 "(svm:source, svm:uuid) ",
1896 "from the following URLs:\n" );
1897 sub read_svm_props {
1898 my ($self, $ra, $path, $r) = @_;
1899 my $props = ($ra->get_dir($path, $r))[2];
1900 my $src = $props->{'svm:source'};
1901 my $uuid = $props->{'svm:uuid'};
1902 return undef if (!$src || !$uuid);
1904 chomp($src, $uuid);
1906 $uuid =~ m{^[0-9a-f\-]{30,}$}
1907 or die "doesn't look right - svm:uuid is '$uuid'\n";
1909 # the '!' is used to mark the repos_root!/relative/path
1910 $src =~ s{/?!/?}{/};
1911 $src =~ s{/+$}{}; # no trailing slashes please
1912 # username is of no interest
1913 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1915 my $replace = $ra->{url};
1916 $replace .= "/$path" if length $path;
1918 my $section = "svn-remote.$self->{repo_id}";
1919 tmp_config("$section.svm-source", $src);
1920 tmp_config("$section.svm-replace", $replace);
1921 tmp_config("$section.svm-uuid", $uuid);
1922 $self->{svm} = {
1923 source => $src,
1924 uuid => $uuid,
1925 replace => $replace
1929 my $r = $ra->get_latest_revnum;
1930 my $path = $self->{path};
1931 my %tried;
1932 while (length $path) {
1933 unless ($tried{"$self->{url}/$path"}) {
1934 return $ra if $self->read_svm_props($ra, $path, $r);
1935 $tried{"$self->{url}/$path"} = 1;
1937 $path =~ s#/?[^/]+$##;
1939 die "Path: '$path' should be ''\n" if $path ne '';
1940 return $ra if $self->read_svm_props($ra, $path, $r);
1941 $tried{"$self->{url}/$path"} = 1;
1943 if ($ra->{repos_root} eq $self->{url}) {
1944 die @err, (map { " $_\n" } keys %tried), "\n";
1947 # nope, make sure we're connected to the repository root:
1948 my $ok;
1949 my @tried_b;
1950 $path = $ra->{svn_path};
1951 $ra = Git::SVN::Ra->new($ra->{repos_root});
1952 while (length $path) {
1953 unless ($tried{"$ra->{url}/$path"}) {
1954 $ok = $self->read_svm_props($ra, $path, $r);
1955 last if $ok;
1956 $tried{"$ra->{url}/$path"} = 1;
1958 $path =~ s#/?[^/]+$##;
1960 die "Path: '$path' should be ''\n" if $path ne '';
1961 $ok ||= $self->read_svm_props($ra, $path, $r);
1962 $tried{"$ra->{url}/$path"} = 1;
1963 if (!$ok) {
1964 die @err, (map { " $_\n" } keys %tried), "\n";
1966 Git::SVN::Ra->new($self->{url});
1969 sub svnsync {
1970 my ($self) = @_;
1971 return $self->{svnsync} if $self->{svnsync};
1973 if ($self->no_metadata) {
1974 die "Can't have both 'noMetadata' and ",
1975 "'useSvnsyncProps' options set!\n";
1977 if ($self->rewrite_root) {
1978 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1979 "options set!\n";
1982 my $svnsync;
1983 # see if we have it in our config, first:
1984 eval {
1985 my $section = "svn-remote.$self->{repo_id}";
1987 my $url = tmp_config('--get', "$section.svnsync-url");
1988 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1989 die "doesn't look right - svn:sync-from-url is '$url'\n";
1991 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1992 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1993 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1995 $svnsync = { url => $url, uuid => $uuid }
1997 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1998 return $self->{svnsync} = $svnsync;
2001 my $err = "useSvnsyncProps set, but failed to read " .
2002 "svnsync property: svn:sync-from-";
2003 my $rp = $self->ra->rev_proplist(0);
2005 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2006 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2007 die "doesn't look right - svn:sync-from-url is '$url'\n";
2009 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2010 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2011 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2013 my $section = "svn-remote.$self->{repo_id}";
2014 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2015 tmp_config('--add', "$section.svnsync-url", $url);
2016 return $self->{svnsync} = { url => $url, uuid => $uuid };
2019 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2020 # remote lookup (useful for 'git svn log').
2021 sub ra_uuid {
2022 my ($self) = @_;
2023 unless ($self->{ra_uuid}) {
2024 my $key = "svn-remote.$self->{repo_id}.uuid";
2025 my $uuid = eval { tmp_config('--get', $key) };
2026 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2027 $self->{ra_uuid} = $uuid;
2028 } else {
2029 die "ra_uuid called without URL\n" unless $self->{url};
2030 $self->{ra_uuid} = $self->ra->get_uuid;
2031 tmp_config('--add', $key, $self->{ra_uuid});
2034 $self->{ra_uuid};
2037 sub _set_repos_root {
2038 my ($self, $repos_root) = @_;
2039 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2040 $repos_root ||= $self->ra->{repos_root};
2041 tmp_config($k, $repos_root);
2042 $repos_root;
2045 sub repos_root {
2046 my ($self) = @_;
2047 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2048 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2051 sub ra {
2052 my ($self) = shift;
2053 my $ra = Git::SVN::Ra->new($self->{url});
2054 $self->_set_repos_root($ra->{repos_root});
2055 if ($self->use_svm_props && !$self->{svm}) {
2056 if ($self->no_metadata) {
2057 die "Can't have both 'noMetadata' and ",
2058 "'useSvmProps' options set!\n";
2059 } elsif ($self->use_svnsync_props) {
2060 die "Can't have both 'useSvnsyncProps' and ",
2061 "'useSvmProps' options set!\n";
2063 $ra = $self->_set_svm_vars($ra);
2064 $self->{-want_revprops} = 1;
2066 $ra;
2069 sub rel_path {
2070 my ($self) = @_;
2071 my $repos_root = $self->ra->{repos_root};
2072 return $self->{path} if ($self->{url} eq $repos_root);
2073 my $url = $self->{url} .
2074 (length $self->{path} ? "/$self->{path}" : $self->{path});
2075 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2076 $url;
2079 # prop_walk(PATH, REV, SUB)
2080 # -------------------------
2081 # Recursively traverse PATH at revision REV and invoke SUB for each
2082 # directory that contains a SVN property. SUB will be invoked as
2083 # follows: &SUB(gs, path, props); where `gs' is this instance of
2084 # Git::SVN, `path' the path to the directory where the properties
2085 # `props' were found. The `path' will be relative to point of checkout,
2086 # that is, if url://repo/trunk is the current Git branch, and that
2087 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2088 # as `path' (note the trailing `/').
2089 sub prop_walk {
2090 my ($self, $path, $rev, $sub) = @_;
2092 $path =~ s#^/##;
2093 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2094 $path =~ s#^/*#/#g;
2095 my $p = $path;
2096 # Strip the irrelevant part of the path.
2097 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2098 # Ensure the path is terminated by a `/'.
2099 $p =~ s#/*$#/#;
2101 # The properties contain all the internal SVN stuff nobody
2102 # (usually) cares about.
2103 my $interesting_props = 0;
2104 foreach (keys %{$props}) {
2105 # If it doesn't start with `svn:', it must be a
2106 # user-defined property.
2107 ++$interesting_props and next if $_ !~ /^svn:/;
2108 # FIXME: Fragile, if SVN adds new public properties,
2109 # this needs to be updated.
2110 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2111 |eol-style|mime-type
2112 |externals|needs-lock)$/x;
2114 &$sub($self, $p, $props) if $interesting_props;
2116 foreach (sort keys %$dirent) {
2117 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2118 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2122 sub last_rev { ($_[0]->last_rev_commit)[0] }
2123 sub last_commit { ($_[0]->last_rev_commit)[1] }
2125 # returns the newest SVN revision number and newest commit SHA1
2126 sub last_rev_commit {
2127 my ($self) = @_;
2128 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2129 return ($self->{last_rev}, $self->{last_commit});
2131 my $c = ::verify_ref($self->refname.'^0');
2132 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2133 my $rev = (::cmt_metadata($c))[1];
2134 if (defined $rev) {
2135 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2136 return ($rev, $c);
2139 my $map_path = $self->map_path;
2140 unless (-e $map_path) {
2141 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2142 return (undef, undef);
2144 my ($rev, $commit) = $self->rev_map_max(1);
2145 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2146 return ($rev, $commit);
2149 sub get_fetch_range {
2150 my ($self, $min, $max) = @_;
2151 $max ||= $self->ra->get_latest_revnum;
2152 $min ||= $self->rev_map_max;
2153 (++$min, $max);
2156 sub tmp_config {
2157 my (@args) = @_;
2158 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2159 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2160 if (! -f $config && -f $old_def_config) {
2161 rename $old_def_config, $config or
2162 die "Failed rename $old_def_config => $config: $!\n";
2164 my $old_config = $ENV{GIT_CONFIG};
2165 $ENV{GIT_CONFIG} = $config;
2166 $@ = undef;
2167 my @ret = eval {
2168 unless (-f $config) {
2169 mkfile($config);
2170 open my $fh, '>', $config or
2171 die "Can't open $config: $!\n";
2172 print $fh "; This file is used internally by ",
2173 "git-svn\n" or die
2174 "Couldn't write to $config: $!\n";
2175 print $fh "; You should not have to edit it\n" or
2176 die "Couldn't write to $config: $!\n";
2177 close $fh or die "Couldn't close $config: $!\n";
2179 command('config', @args);
2181 my $err = $@;
2182 if (defined $old_config) {
2183 $ENV{GIT_CONFIG} = $old_config;
2184 } else {
2185 delete $ENV{GIT_CONFIG};
2187 die $err if $err;
2188 wantarray ? @ret : $ret[0];
2191 sub tmp_index_do {
2192 my ($self, $sub) = @_;
2193 my $old_index = $ENV{GIT_INDEX_FILE};
2194 $ENV{GIT_INDEX_FILE} = $self->{index};
2195 $@ = undef;
2196 my @ret = eval {
2197 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2198 mkpath([$dir]) unless -d $dir;
2199 &$sub;
2201 my $err = $@;
2202 if (defined $old_index) {
2203 $ENV{GIT_INDEX_FILE} = $old_index;
2204 } else {
2205 delete $ENV{GIT_INDEX_FILE};
2207 die $err if $err;
2208 wantarray ? @ret : $ret[0];
2211 sub assert_index_clean {
2212 my ($self, $treeish) = @_;
2214 $self->tmp_index_do(sub {
2215 command_noisy('read-tree', $treeish) unless -e $self->{index};
2216 my $x = command_oneline('write-tree');
2217 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2218 /^tree ($::sha1)/mo);
2219 return if $y eq $x;
2221 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2222 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2223 command_noisy('read-tree', $treeish);
2224 $x = command_oneline('write-tree');
2225 if ($y ne $x) {
2226 ::fatal "trees ($treeish) $y != $x\n",
2227 "Something is seriously wrong...";
2232 sub get_commit_parents {
2233 my ($self, $log_entry) = @_;
2234 my (%seen, @ret, @tmp);
2235 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2236 if (my $ip = $self->{inject_parents}) {
2237 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2238 push @tmp, $commit;
2241 if (my $cur = ::verify_ref($self->refname.'^0')) {
2242 push @tmp, $cur;
2244 if (my $ipd = $self->{inject_parents_dcommit}) {
2245 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2246 push @tmp, @$commit;
2249 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2250 while (my $p = shift @tmp) {
2251 next if $seen{$p};
2252 $seen{$p} = 1;
2253 push @ret, $p;
2254 # MAXPARENT is defined to 16 in commit-tree.c:
2255 last if @ret >= 16;
2257 if (@tmp) {
2258 die "r$log_entry->{revision}: No room for parents:\n\t",
2259 join("\n\t", @tmp), "\n";
2261 @ret;
2264 sub rewrite_root {
2265 my ($self) = @_;
2266 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2267 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2268 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2269 if ($rwr) {
2270 $rwr =~ s#/+$##;
2271 if ($rwr !~ m#^[a-z\+]+://#) {
2272 die "$rwr is not a valid URL (key: $k)\n";
2275 $self->{-rewrite_root} = $rwr;
2278 sub metadata_url {
2279 my ($self) = @_;
2280 ($self->rewrite_root || $self->{url}) .
2281 (length $self->{path} ? '/' . $self->{path} : '');
2284 sub full_url {
2285 my ($self) = @_;
2286 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2290 sub set_commit_header_env {
2291 my ($log_entry) = @_;
2292 my %env;
2293 foreach my $ned (qw/NAME EMAIL DATE/) {
2294 foreach my $ac (qw/AUTHOR COMMITTER/) {
2295 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2299 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2300 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2301 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2303 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2304 ? $log_entry->{commit_name}
2305 : $log_entry->{name};
2306 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2307 ? $log_entry->{commit_email}
2308 : $log_entry->{email};
2309 \%env;
2312 sub restore_commit_header_env {
2313 my ($env) = @_;
2314 foreach my $ned (qw/NAME EMAIL DATE/) {
2315 foreach my $ac (qw/AUTHOR COMMITTER/) {
2316 my $k = "GIT_${ac}_${ned}";
2317 if (defined $env->{$k}) {
2318 $ENV{$k} = $env->{$k};
2319 } else {
2320 delete $ENV{$k};
2326 sub gc {
2327 command_noisy('gc', '--auto');
2330 sub do_git_commit {
2331 my ($self, $log_entry) = @_;
2332 my $lr = $self->last_rev;
2333 if (defined $lr && $lr >= $log_entry->{revision}) {
2334 die "Last fetched revision of ", $self->refname,
2335 " was r$lr, but we are about to fetch: ",
2336 "r$log_entry->{revision}!\n";
2338 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2339 croak "$log_entry->{revision} = $c already exists! ",
2340 "Why are we refetching it?\n";
2342 my $old_env = set_commit_header_env($log_entry);
2343 my $tree = $log_entry->{tree};
2344 if (!defined $tree) {
2345 $tree = $self->tmp_index_do(sub {
2346 command_oneline('write-tree') });
2348 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2350 my @exec = ('git', 'commit-tree', $tree);
2351 foreach ($self->get_commit_parents($log_entry)) {
2352 push @exec, '-p', $_;
2354 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2355 or croak $!;
2356 binmode $msg_fh;
2358 # we always get UTF-8 from SVN, but we may want our commits in
2359 # a different encoding.
2360 if (my $enc = Git::config('i18n.commitencoding')) {
2361 require Encode;
2362 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2364 print $msg_fh $log_entry->{log} or croak $!;
2365 restore_commit_header_env($old_env);
2366 unless ($self->no_metadata) {
2367 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2368 or croak $!;
2370 $msg_fh->flush == 0 or croak $!;
2371 close $msg_fh or croak $!;
2372 chomp(my $commit = do { local $/; <$out_fh> });
2373 close $out_fh or croak $!;
2374 waitpid $pid, 0;
2375 croak $? if $?;
2376 if ($commit !~ /^$::sha1$/o) {
2377 die "Failed to commit, invalid sha1: $commit\n";
2380 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2382 $self->{last_rev} = $log_entry->{revision};
2383 $self->{last_commit} = $commit;
2384 print "r$log_entry->{revision}" unless $::_q > 1;
2385 if (defined $log_entry->{svm_revision}) {
2386 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2387 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2388 0, $self->svm_uuid);
2390 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2391 if (--$_gc_nr == 0) {
2392 $_gc_nr = $_gc_period;
2393 gc();
2395 return $commit;
2398 sub match_paths {
2399 my ($self, $paths, $r) = @_;
2400 return 1 if $self->{path} eq '';
2401 if (my $path = $paths->{"/$self->{path}"}) {
2402 return ($path->{action} eq 'D') ? 0 : 1;
2404 my $repos_root = $self->ra->{repos_root};
2405 my $extended_path = $self->{url} . '/' . $self->{path};
2406 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2407 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2408 if (grep /$self->{path_regex}/, keys %$paths) {
2409 return 1;
2411 my $c = '';
2412 foreach (split m#/#, $self->{path}) {
2413 $c .= "/$_";
2414 next unless ($paths->{$c} &&
2415 ($paths->{$c}->{action} =~ /^[AR]$/));
2416 if ($self->ra->check_path($self->{path}, $r) ==
2417 $SVN::Node::dir) {
2418 return 1;
2421 return 0;
2424 sub find_parent_branch {
2425 my ($self, $paths, $rev) = @_;
2426 return undef unless $self->follow_parent;
2427 unless (defined $paths) {
2428 my $err_handler = $SVN::Error::handler;
2429 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2430 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2431 $paths =
2432 Git::SVN::Ra::dup_changed_paths($_[0]) });
2433 $SVN::Error::handler = $err_handler;
2435 return undef unless defined $paths;
2437 # look for a parent from another branch:
2438 my @b_path_components = split m#/#, $self->rel_path;
2439 my @a_path_components;
2440 my $i;
2441 while (@b_path_components) {
2442 $i = $paths->{'/'.join('/', @b_path_components)};
2443 last if $i && defined $i->{copyfrom_path};
2444 unshift(@a_path_components, pop(@b_path_components));
2446 return undef unless defined $i && defined $i->{copyfrom_path};
2447 my $branch_from = $i->{copyfrom_path};
2448 if (@a_path_components) {
2449 print STDERR "branch_from: $branch_from => ";
2450 $branch_from .= '/'.join('/', @a_path_components);
2451 print STDERR $branch_from, "\n";
2453 my $r = $i->{copyfrom_rev};
2454 my $repos_root = $self->ra->{repos_root};
2455 my $url = $self->ra->{url};
2456 my $new_url = $repos_root . $branch_from;
2457 print STDERR "Found possible branch point: ",
2458 "$new_url => ", $self->full_url, ", $r\n";
2459 $branch_from =~ s#^/##;
2460 my $gs = $self->other_gs($new_url, $url, $repos_root,
2461 $branch_from, $r, $self->{ref_id});
2462 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2464 my ($base, $head);
2465 if (!defined $r0 || !defined $parent) {
2466 ($base, $head) = parse_revision_argument(0, $r);
2467 } else {
2468 if ($r0 < $r) {
2469 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2470 0, 1, sub { $base = $_[1] - 1 });
2473 if (defined $base && $base <= $r) {
2474 $gs->fetch($base, $r);
2476 ($r0, $parent) = $gs->find_rev_before($r, 1);
2478 if (defined $r0 && defined $parent) {
2479 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2480 my $ed;
2481 if ($self->ra->can_do_switch) {
2482 $self->assert_index_clean($parent);
2483 print STDERR "Following parent with do_switch\n";
2484 # do_switch works with svn/trunk >= r22312, but that
2485 # is not included with SVN 1.4.3 (the latest version
2486 # at the moment), so we can't rely on it
2487 $self->{last_rev} = $r0;
2488 $self->{last_commit} = $parent;
2489 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2490 $gs->ra->gs_do_switch($r0, $rev, $gs,
2491 $self->full_url, $ed)
2492 or die "SVN connection failed somewhere...\n";
2493 } elsif ($self->ra->trees_match($new_url, $r0,
2494 $self->full_url, $rev)) {
2495 print STDERR "Trees match:\n",
2496 " $new_url\@$r0\n",
2497 " ${\$self->full_url}\@$rev\n",
2498 "Following parent with no changes\n";
2499 $self->tmp_index_do(sub {
2500 command_noisy('read-tree', $parent);
2502 $self->{last_commit} = $parent;
2503 } else {
2504 print STDERR "Following parent with do_update\n";
2505 $ed = SVN::Git::Fetcher->new($self);
2506 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2507 or die "SVN connection failed somewhere...\n";
2509 print STDERR "Successfully followed parent\n";
2510 return $self->make_log_entry($rev, [$parent], $ed);
2512 return undef;
2515 sub do_fetch {
2516 my ($self, $paths, $rev) = @_;
2517 my $ed;
2518 my ($last_rev, @parents);
2519 if (my $lc = $self->last_commit) {
2520 # we can have a branch that was deleted, then re-added
2521 # under the same name but copied from another path, in
2522 # which case we'll have multiple parents (we don't
2523 # want to break the original ref, nor lose copypath info):
2524 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2525 push @{$log_entry->{parents}}, $lc;
2526 return $log_entry;
2528 $ed = SVN::Git::Fetcher->new($self);
2529 $last_rev = $self->{last_rev};
2530 $ed->{c} = $lc;
2531 @parents = ($lc);
2532 } else {
2533 $last_rev = $rev;
2534 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2535 return $log_entry;
2537 $ed = SVN::Git::Fetcher->new($self);
2539 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2540 die "SVN connection failed somewhere...\n";
2542 $self->make_log_entry($rev, \@parents, $ed);
2545 sub get_untracked {
2546 my ($self, $ed) = @_;
2547 my @out;
2548 my $h = $ed->{empty};
2549 foreach (sort keys %$h) {
2550 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2551 push @out, " $act: " . uri_encode($_);
2552 warn "W: $act: $_\n";
2554 foreach my $t (qw/dir_prop file_prop/) {
2555 $h = $ed->{$t} or next;
2556 foreach my $path (sort keys %$h) {
2557 my $ppath = $path eq '' ? '.' : $path;
2558 foreach my $prop (sort keys %{$h->{$path}}) {
2559 next if $SKIP_PROP{$prop};
2560 my $v = $h->{$path}->{$prop};
2561 my $t_ppath_prop = "$t: " .
2562 uri_encode($ppath) . ' ' .
2563 uri_encode($prop);
2564 if (defined $v) {
2565 push @out, " +$t_ppath_prop " .
2566 uri_encode($v);
2567 } else {
2568 push @out, " -$t_ppath_prop";
2573 foreach my $t (qw/absent_file absent_directory/) {
2574 $h = $ed->{$t} or next;
2575 foreach my $parent (sort keys %$h) {
2576 foreach my $path (sort @{$h->{$parent}}) {
2577 push @out, " $t: " .
2578 uri_encode("$parent/$path");
2579 warn "W: $t: $parent/$path ",
2580 "Insufficient permissions?\n";
2584 \@out;
2587 # parse_svn_date(DATE)
2588 # --------------------
2589 # Given a date (in UTC) from Subversion, return a string in the format
2590 # "<TZ Offset> <local date/time>" that Git will use.
2592 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2593 # is true we'll convert it to the local timezone instead.
2594 sub parse_svn_date {
2595 my $date = shift || return '+0000 1970-01-01 00:00:00';
2596 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2597 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2598 croak "Unable to parse date: $date\n";
2599 my $parsed_date; # Set next.
2601 if ($Git::SVN::_localtime) {
2602 # Translate the Subversion datetime to an epoch time.
2603 # Begin by switching ourselves to $date's timezone, UTC.
2604 my $old_env_TZ = $ENV{TZ};
2605 $ENV{TZ} = 'UTC';
2607 my $epoch_in_UTC =
2608 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2610 # Determine our local timezone (including DST) at the
2611 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2612 # value of TZ, if any, at the time we were run.
2613 if (defined $Git::SVN::Log::TZ) {
2614 $ENV{TZ} = $Git::SVN::Log::TZ;
2615 } else {
2616 delete $ENV{TZ};
2619 my $our_TZ =
2620 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2622 # This converts $epoch_in_UTC into our local timezone.
2623 my ($sec, $min, $hour, $mday, $mon, $year,
2624 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2626 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2627 $our_TZ, $year + 1900, $mon + 1,
2628 $mday, $hour, $min, $sec);
2630 # Reset us to the timezone in effect when we entered
2631 # this routine.
2632 if (defined $old_env_TZ) {
2633 $ENV{TZ} = $old_env_TZ;
2634 } else {
2635 delete $ENV{TZ};
2637 } else {
2638 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2641 return $parsed_date;
2644 sub other_gs {
2645 my ($self, $new_url, $url, $repos_root,
2646 $branch_from, $r, $old_ref_id) = @_;
2647 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2648 unless ($gs) {
2649 my $ref_id = $old_ref_id;
2650 $ref_id =~ s/\@\d+$//;
2651 $ref_id .= "\@$r";
2652 # just grow a tail if we're not unique enough :x
2653 $ref_id .= '-' while find_ref($ref_id);
2654 print STDERR "Initializing parent: $ref_id\n";
2655 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2656 if ($u =~ s#^\Q$url\E(/|$)##) {
2657 $p = $u;
2658 $u = $url;
2659 $repo_id = $self->{repo_id};
2661 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2666 sub check_author {
2667 my ($author) = @_;
2668 if (!defined $author || length $author == 0) {
2669 $author = '(no author)';
2670 } elsif (defined $::_authors && ! defined $::users{$author}) {
2671 die "Author: $author not defined in $::_authors file\n";
2673 $author;
2676 sub make_log_entry {
2677 my ($self, $rev, $parents, $ed) = @_;
2678 my $untracked = $self->get_untracked($ed);
2680 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2681 print $un "r$rev\n" or croak $!;
2682 print $un $_, "\n" foreach @$untracked;
2683 my %log_entry = ( parents => $parents || [], revision => $rev,
2684 log => '');
2686 my $headrev;
2687 my $logged = delete $self->{logged_rev_props};
2688 if (!$logged || $self->{-want_revprops}) {
2689 my $rp = $self->ra->rev_proplist($rev);
2690 foreach (sort keys %$rp) {
2691 my $v = $rp->{$_};
2692 if (/^svn:(author|date|log)$/) {
2693 $log_entry{$1} = $v;
2694 } elsif ($_ eq 'svm:headrev') {
2695 $headrev = $v;
2696 } else {
2697 print $un " rev_prop: ", uri_encode($_), ' ',
2698 uri_encode($v), "\n";
2701 } else {
2702 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2704 close $un or croak $!;
2706 $log_entry{date} = parse_svn_date($log_entry{date});
2707 $log_entry{log} .= "\n";
2708 my $author = $log_entry{author} = check_author($log_entry{author});
2709 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2710 : ($author, undef);
2712 my ($commit_name, $commit_email) = ($name, $email);
2713 if ($_use_log_author) {
2714 my $name_field;
2715 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2716 $name_field = $1;
2717 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2718 $name_field = $1;
2720 if (!defined $name_field) {
2721 if (!defined $email) {
2722 $email = $name;
2724 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2725 ($name, $email) = ($1, $2);
2726 } elsif ($name_field =~ /(.*)@/) {
2727 ($name, $email) = ($1, $name_field);
2728 } else {
2729 ($name, $email) = ($name_field, $name_field);
2732 if (defined $headrev && $self->use_svm_props) {
2733 if ($self->rewrite_root) {
2734 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2735 "options set!\n";
2737 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2738 # we don't want "SVM: initializing mirror for junk" ...
2739 return undef if $r == 0;
2740 my $svm = $self->svm;
2741 if ($uuid ne $svm->{uuid}) {
2742 die "UUID mismatch on SVM path:\n",
2743 "expected: $svm->{uuid}\n",
2744 " got: $uuid\n";
2746 my $full_url = $self->full_url;
2747 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2748 die "Failed to replace '$svm->{replace}' with ",
2749 "'$svm->{source}' in $full_url\n";
2750 # throw away username for storing in records
2751 remove_username($full_url);
2752 $log_entry{metadata} = "$full_url\@$r $uuid";
2753 $log_entry{svm_revision} = $r;
2754 $email ||= "$author\@$uuid";
2755 $commit_email ||= "$author\@$uuid";
2756 } elsif ($self->use_svnsync_props) {
2757 my $full_url = $self->svnsync->{url};
2758 $full_url .= "/$self->{path}" if length $self->{path};
2759 remove_username($full_url);
2760 my $uuid = $self->svnsync->{uuid};
2761 $log_entry{metadata} = "$full_url\@$rev $uuid";
2762 $email ||= "$author\@$uuid";
2763 $commit_email ||= "$author\@$uuid";
2764 } else {
2765 my $url = $self->metadata_url;
2766 remove_username($url);
2767 $log_entry{metadata} = "$url\@$rev " .
2768 $self->ra->get_uuid;
2769 $email ||= "$author\@" . $self->ra->get_uuid;
2770 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2772 $log_entry{name} = $name;
2773 $log_entry{email} = $email;
2774 $log_entry{commit_name} = $commit_name;
2775 $log_entry{commit_email} = $commit_email;
2776 \%log_entry;
2779 sub fetch {
2780 my ($self, $min_rev, $max_rev, @parents) = @_;
2781 my ($last_rev, $last_commit) = $self->last_rev_commit;
2782 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2783 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2786 sub set_tree_cb {
2787 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2788 $self->{inject_parents} = { $rev => $tree };
2789 $self->fetch(undef, undef);
2792 sub set_tree {
2793 my ($self, $tree) = (shift, shift);
2794 my $log_entry = ::get_commit_entry($tree);
2795 unless ($self->{last_rev}) {
2796 ::fatal("Must have an existing revision to commit");
2798 my %ed_opts = ( r => $self->{last_rev},
2799 log => $log_entry->{log},
2800 ra => $self->ra,
2801 tree_a => $self->{last_commit},
2802 tree_b => $tree,
2803 editor_cb => sub {
2804 $self->set_tree_cb($log_entry, $tree, @_) },
2805 svn_path => $self->{path} );
2806 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2807 print "No changes\nr$self->{last_rev} = $tree\n";
2811 sub rebuild_from_rev_db {
2812 my ($self, $path) = @_;
2813 my $r = -1;
2814 open my $fh, '<', $path or croak "open: $!";
2815 binmode $fh or croak "binmode: $!";
2816 while (<$fh>) {
2817 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2818 chomp($_);
2819 ++$r;
2820 next if $_ eq ('0' x 40);
2821 $self->rev_map_set($r, $_);
2822 print "r$r = $_\n";
2824 close $fh or croak "close: $!";
2825 unlink $path or croak "unlink: $!";
2828 sub rebuild {
2829 my ($self) = @_;
2830 my $map_path = $self->map_path;
2831 my $partial = (-e $map_path && ! -z $map_path);
2832 return unless ::verify_ref($self->refname.'^0');
2833 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2834 my $rev_db = $self->rev_db_path;
2835 $self->rebuild_from_rev_db($rev_db);
2836 if ($self->use_svm_props) {
2837 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2838 $self->rebuild_from_rev_db($svm_rev_db);
2840 $self->unlink_rev_db_symlink;
2841 return;
2843 print "Rebuilding $map_path ...\n" if (!$partial);
2844 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2845 (undef, undef));
2846 my ($log, $ctx) =
2847 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2848 ($head ? "$head.." : "") . $self->refname,
2849 '--');
2850 my $metadata_url = $self->metadata_url;
2851 remove_username($metadata_url);
2852 my $svn_uuid = $self->ra_uuid;
2853 my $c;
2854 while (<$log>) {
2855 if ( m{^commit ($::sha1)$} ) {
2856 $c = $1;
2857 next;
2859 next unless s{^\s*(git-svn-id:)}{$1};
2860 my ($url, $rev, $uuid) = ::extract_metadata($_);
2861 remove_username($url);
2863 # ignore merges (from set-tree)
2864 next if (!defined $rev || !$uuid);
2866 # if we merged or otherwise started elsewhere, this is
2867 # how we break out of it
2868 if (($uuid ne $svn_uuid) ||
2869 ($metadata_url && $url && ($url ne $metadata_url))) {
2870 next;
2872 if ($partial && $head) {
2873 print "Partial-rebuilding $map_path ...\n";
2874 print "Currently at $base_rev = $head\n";
2875 $head = undef;
2878 $self->rev_map_set($rev, $c);
2879 print "r$rev = $c\n";
2881 command_close_pipe($log, $ctx);
2882 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2883 my $rev_db_path = $self->rev_db_path;
2884 if (-f $self->rev_db_path) {
2885 unlink $self->rev_db_path or croak "unlink: $!";
2887 $self->unlink_rev_db_symlink;
2890 # rev_map:
2891 # Tie::File seems to be prone to offset errors if revisions get sparse,
2892 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2893 # one of my favorite modules is out :< Next up would be one of the DBM
2894 # modules, but I'm not sure which is most portable...
2896 # This is the replacement for the rev_db format, which was too big
2897 # and inefficient for large repositories with a lot of sparse history
2898 # (mainly tags)
2900 # The format is this:
2901 # - 24 bytes for every record,
2902 # * 4 bytes for the integer representing an SVN revision number
2903 # * 20 bytes representing the sha1 of a git commit
2904 # - No empty padding records like the old format
2905 # (except the last record, which can be overwritten)
2906 # - new records are written append-only since SVN revision numbers
2907 # increase monotonically
2908 # - lookups on SVN revision number are done via a binary search
2909 # - Piping the file to xxd -c24 is a good way of dumping it for
2910 # viewing or editing (piped back through xxd -r), should the need
2911 # ever arise.
2912 # - The last record can be padding revision with an all-zero sha1
2913 # This is used to optimize fetch performance when using multiple
2914 # "fetch" directives in .git/config
2916 # These files are disposable unless noMetadata or useSvmProps is set
2918 sub _rev_map_set {
2919 my ($fh, $rev, $commit) = @_;
2921 binmode $fh or croak "binmode: $!";
2922 my $size = (stat($fh))[7];
2923 ($size % 24) == 0 or croak "inconsistent size: $size";
2925 my $wr_offset = 0;
2926 if ($size > 0) {
2927 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2928 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2929 $read == 24 or croak "read only $read bytes (!= 24)";
2930 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2931 if ($last_commit eq ('0' x40)) {
2932 if ($size >= 48) {
2933 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2934 $read = sysread($fh, $buf, 24) or
2935 croak "read: $!";
2936 $read == 24 or
2937 croak "read only $read bytes (!= 24)";
2938 ($last_rev, $last_commit) =
2939 unpack(rev_map_fmt, $buf);
2940 if ($last_commit eq ('0' x40)) {
2941 croak "inconsistent .rev_map\n";
2944 if ($last_rev >= $rev) {
2945 croak "last_rev is higher!: $last_rev >= $rev";
2947 $wr_offset = -24;
2950 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2951 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2952 croak "write: $!";
2955 sub mkfile {
2956 my ($path) = @_;
2957 unless (-e $path) {
2958 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2959 mkpath([$dir]) unless -d $dir;
2960 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2961 close $fh or die "Couldn't close (create) $path: $!\n";
2965 sub rev_map_set {
2966 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2967 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2968 my $db = $self->map_path($uuid);
2969 my $db_lock = "$db.lock";
2970 my $sig;
2971 if ($update_ref) {
2972 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2973 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2975 mkfile($db);
2977 $LOCKFILES{$db_lock} = 1;
2978 my $sync;
2979 # both of these options make our .rev_db file very, very important
2980 # and we can't afford to lose it because rebuild() won't work
2981 if ($self->use_svm_props || $self->no_metadata) {
2982 $sync = 1;
2983 copy($db, $db_lock) or die "rev_map_set(@_): ",
2984 "Failed to copy: ",
2985 "$db => $db_lock ($!)\n";
2986 } else {
2987 rename $db, $db_lock or die "rev_map_set(@_): ",
2988 "Failed to rename: ",
2989 "$db => $db_lock ($!)\n";
2992 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2993 or croak "Couldn't open $db_lock: $!\n";
2994 _rev_map_set($fh, $rev, $commit);
2995 if ($sync) {
2996 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2997 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2999 close $fh or croak $!;
3000 if ($update_ref) {
3001 $_head = $self;
3002 command_noisy('update-ref', '-m', "r$rev",
3003 $self->refname, $commit);
3005 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3006 "$db_lock => $db ($!)\n";
3007 delete $LOCKFILES{$db_lock};
3008 if ($update_ref) {
3009 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3010 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3011 kill $sig, $$ if defined $sig;
3015 # If want_commit, this will return an array of (rev, commit) where
3016 # commit _must_ be a valid commit in the archive.
3017 # Otherwise, it'll return the max revision (whether or not the
3018 # commit is valid or just a 0x40 placeholder).
3019 sub rev_map_max {
3020 my ($self, $want_commit) = @_;
3021 $self->rebuild;
3022 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3023 $want_commit ? ($r, $c) : $r;
3026 sub rev_map_max_norebuild {
3027 my ($self, $want_commit) = @_;
3028 my $map_path = $self->map_path;
3029 stat $map_path or return $want_commit ? (0, undef) : 0;
3030 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3031 binmode $fh or croak "binmode: $!";
3032 my $size = (stat($fh))[7];
3033 ($size % 24) == 0 or croak "inconsistent size: $size";
3035 if ($size == 0) {
3036 close $fh or croak "close: $!";
3037 return $want_commit ? (0, undef) : 0;
3040 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3041 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3042 my ($r, $c) = unpack(rev_map_fmt, $buf);
3043 if ($want_commit && $c eq ('0' x40)) {
3044 if ($size < 48) {
3045 return $want_commit ? (0, undef) : 0;
3047 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3048 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3049 ($r, $c) = unpack(rev_map_fmt, $buf);
3050 if ($c eq ('0'x40)) {
3051 croak "Penultimate record is all-zeroes in $map_path";
3054 close $fh or croak "close: $!";
3055 $want_commit ? ($r, $c) : $r;
3058 sub rev_map_get {
3059 my ($self, $rev, $uuid) = @_;
3060 my $map_path = $self->map_path($uuid);
3061 return undef unless -e $map_path;
3063 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3064 binmode $fh or croak "binmode: $!";
3065 my $size = (stat($fh))[7];
3066 ($size % 24) == 0 or croak "inconsistent size: $size";
3068 if ($size == 0) {
3069 close $fh or croak "close: $fh";
3070 return undef;
3073 my ($l, $u) = (0, $size - 24);
3074 my ($r, $c, $buf);
3076 while ($l <= $u) {
3077 my $i = int(($l/24 + $u/24) / 2) * 24;
3078 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3079 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3080 my ($r, $c) = unpack('NH40', $buf);
3082 if ($r < $rev) {
3083 $l = $i + 24;
3084 } elsif ($r > $rev) {
3085 $u = $i - 24;
3086 } else { # $r == $rev
3087 close($fh) or croak "close: $!";
3088 return $c eq ('0' x 40) ? undef : $c;
3091 close($fh) or croak "close: $!";
3092 undef;
3095 # Finds the first svn revision that exists on (if $eq_ok is true) or
3096 # before $rev for the current branch. It will not search any lower
3097 # than $min_rev. Returns the git commit hash and svn revision number
3098 # if found, else (undef, undef).
3099 sub find_rev_before {
3100 my ($self, $rev, $eq_ok, $min_rev) = @_;
3101 --$rev unless $eq_ok;
3102 $min_rev ||= 1;
3103 while ($rev >= $min_rev) {
3104 if (my $c = $self->rev_map_get($rev)) {
3105 return ($rev, $c);
3107 --$rev;
3109 return (undef, undef);
3112 # Finds the first svn revision that exists on (if $eq_ok is true) or
3113 # after $rev for the current branch. It will not search any higher
3114 # than $max_rev. Returns the git commit hash and svn revision number
3115 # if found, else (undef, undef).
3116 sub find_rev_after {
3117 my ($self, $rev, $eq_ok, $max_rev) = @_;
3118 ++$rev unless $eq_ok;
3119 $max_rev ||= $self->rev_map_max;
3120 while ($rev <= $max_rev) {
3121 if (my $c = $self->rev_map_get($rev)) {
3122 return ($rev, $c);
3124 ++$rev;
3126 return (undef, undef);
3129 sub _new {
3130 my ($class, $repo_id, $ref_id, $path) = @_;
3131 unless (defined $repo_id && length $repo_id) {
3132 $repo_id = $Git::SVN::default_repo_id;
3134 unless (defined $ref_id && length $ref_id) {
3135 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3137 $_[1] = $repo_id;
3138 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3139 $_[3] = $path = '' unless (defined $path);
3140 mkpath(["$ENV{GIT_DIR}/svn"]);
3141 bless {
3142 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3143 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3144 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3147 # for read-only access of old .rev_db formats
3148 sub unlink_rev_db_symlink {
3149 my ($self) = @_;
3150 my $link = $self->rev_db_path;
3151 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3152 if (-l $link) {
3153 unlink $link or croak "unlink: $link failed!";
3157 sub rev_db_path {
3158 my ($self, $uuid) = @_;
3159 my $db_path = $self->map_path($uuid);
3160 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3161 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3162 $db_path;
3165 # the new replacement for .rev_db
3166 sub map_path {
3167 my ($self, $uuid) = @_;
3168 $uuid ||= $self->ra_uuid;
3169 "$self->{map_root}.$uuid";
3172 sub uri_encode {
3173 my ($f) = @_;
3174 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3178 sub remove_username {
3179 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3182 package Git::SVN::Prompt;
3183 use strict;
3184 use warnings;
3185 require SVN::Core;
3186 use vars qw/$_no_auth_cache $_username/;
3188 sub simple {
3189 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3190 $may_save = undef if $_no_auth_cache;
3191 $default_username = $_username if defined $_username;
3192 if (defined $default_username && length $default_username) {
3193 if (defined $realm && length $realm) {
3194 print STDERR "Authentication realm: $realm\n";
3195 STDERR->flush;
3197 $cred->username($default_username);
3198 } else {
3199 username($cred, $realm, $may_save, $pool);
3201 $cred->password(_read_password("Password for '" .
3202 $cred->username . "': ", $realm));
3203 $cred->may_save($may_save);
3204 $SVN::_Core::SVN_NO_ERROR;
3207 sub ssl_server_trust {
3208 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3209 $may_save = undef if $_no_auth_cache;
3210 print STDERR "Error validating server certificate for '$realm':\n";
3212 no warnings 'once';
3213 # All variables SVN::Auth::SSL::* are used only once,
3214 # so we're shutting up Perl warnings about this.
3215 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3216 print STDERR " - The certificate is not issued ",
3217 "by a trusted authority. Use the\n",
3218 " fingerprint to validate ",
3219 "the certificate manually!\n";
3221 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3222 print STDERR " - The certificate hostname ",
3223 "does not match.\n";
3225 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3226 print STDERR " - The certificate is not yet valid.\n";
3228 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3229 print STDERR " - The certificate has expired.\n";
3231 if ($failures & $SVN::Auth::SSL::OTHER) {
3232 print STDERR " - The certificate has ",
3233 "an unknown error.\n";
3235 } # no warnings 'once'
3236 printf STDERR
3237 "Certificate information:\n".
3238 " - Hostname: %s\n".
3239 " - Valid: from %s until %s\n".
3240 " - Issuer: %s\n".
3241 " - Fingerprint: %s\n",
3242 map $cert_info->$_, qw(hostname valid_from valid_until
3243 issuer_dname fingerprint);
3244 my $choice;
3245 prompt:
3246 print STDERR $may_save ?
3247 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3248 "(R)eject or accept (t)emporarily? ";
3249 STDERR->flush;
3250 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3251 if ($choice =~ /^t$/i) {
3252 $cred->may_save(undef);
3253 } elsif ($choice =~ /^r$/i) {
3254 return -1;
3255 } elsif ($may_save && $choice =~ /^p$/i) {
3256 $cred->may_save($may_save);
3257 } else {
3258 goto prompt;
3260 $cred->accepted_failures($failures);
3261 $SVN::_Core::SVN_NO_ERROR;
3264 sub ssl_client_cert {
3265 my ($cred, $realm, $may_save, $pool) = @_;
3266 $may_save = undef if $_no_auth_cache;
3267 print STDERR "Client certificate filename: ";
3268 STDERR->flush;
3269 chomp(my $filename = <STDIN>);
3270 $cred->cert_file($filename);
3271 $cred->may_save($may_save);
3272 $SVN::_Core::SVN_NO_ERROR;
3275 sub ssl_client_cert_pw {
3276 my ($cred, $realm, $may_save, $pool) = @_;
3277 $may_save = undef if $_no_auth_cache;
3278 $cred->password(_read_password("Password: ", $realm));
3279 $cred->may_save($may_save);
3280 $SVN::_Core::SVN_NO_ERROR;
3283 sub username {
3284 my ($cred, $realm, $may_save, $pool) = @_;
3285 $may_save = undef if $_no_auth_cache;
3286 if (defined $realm && length $realm) {
3287 print STDERR "Authentication realm: $realm\n";
3289 my $username;
3290 if (defined $_username) {
3291 $username = $_username;
3292 } else {
3293 print STDERR "Username: ";
3294 STDERR->flush;
3295 chomp($username = <STDIN>);
3297 $cred->username($username);
3298 $cred->may_save($may_save);
3299 $SVN::_Core::SVN_NO_ERROR;
3302 sub _read_password {
3303 my ($prompt, $realm) = @_;
3304 print STDERR $prompt;
3305 STDERR->flush;
3306 require Term::ReadKey;
3307 Term::ReadKey::ReadMode('noecho');
3308 my $password = '';
3309 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3310 last if $key =~ /[\012\015]/; # \n\r
3311 $password .= $key;
3313 Term::ReadKey::ReadMode('restore');
3314 print STDERR "\n";
3315 STDERR->flush;
3316 $password;
3319 package SVN::Git::Fetcher;
3320 use vars qw/@ISA/;
3321 use strict;
3322 use warnings;
3323 use Carp qw/croak/;
3324 use File::Temp qw/tempfile/;
3325 use IO::File qw//;
3326 use vars qw/$_ignore_regex/;
3328 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3329 sub new {
3330 my ($class, $git_svn, $switch_path) = @_;
3331 my $self = SVN::Delta::Editor->new;
3332 bless $self, $class;
3333 if (exists $git_svn->{last_commit}) {
3334 $self->{c} = $git_svn->{last_commit};
3335 $self->{empty_symlinks} =
3336 _mark_empty_symlinks($git_svn, $switch_path);
3338 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3339 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3340 $self->{empty} = {};
3341 $self->{dir_prop} = {};
3342 $self->{file_prop} = {};
3343 $self->{absent_dir} = {};
3344 $self->{absent_file} = {};
3345 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3346 $self;
3349 # this uses the Ra object, so it must be called before do_{switch,update},
3350 # not inside them (when the Git::SVN::Fetcher object is passed) to
3351 # do_{switch,update}
3352 sub _mark_empty_symlinks {
3353 my ($git_svn, $switch_path) = @_;
3354 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3355 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3357 my %ret;
3358 my ($rev, $cmt) = $git_svn->last_rev_commit;
3359 return {} unless ($rev && $cmt);
3361 # allow the warning to be printed for each revision we fetch to
3362 # ensure the user sees it. The user can also disable the workaround
3363 # on the repository even while git svn is running and the next
3364 # revision fetched will skip this expensive function.
3365 my $printed_warning;
3366 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3367 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3368 local $/ = "\0";
3369 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3370 $pfx .= '/' if length($pfx);
3371 while (<$ls>) {
3372 chomp;
3373 s/\A100644 blob $empty_blob\t//o or next;
3374 unless ($printed_warning) {
3375 print STDERR "Scanning for empty symlinks, ",
3376 "this may take a while if you have ",
3377 "many empty files\n",
3378 "You may disable this with `",
3379 "git config svn.brokenSymlinkWorkaround ",
3380 "false'.\n",
3381 "This may be done in a different ",
3382 "terminal without restarting ",
3383 "git svn\n";
3384 $printed_warning = 1;
3386 my $path = $_;
3387 my (undef, $props) =
3388 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3389 if ($props->{'svn:special'}) {
3390 $ret{$path} = 1;
3393 command_close_pipe($ls, $ctx);
3394 \%ret;
3397 # returns true if a given path is inside a ".git" directory
3398 sub in_dot_git {
3399 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3402 # return value: 0 -- don't ignore, 1 -- ignore
3403 sub is_path_ignored {
3404 my ($self, $path) = @_;
3405 return 1 if in_dot_git($path);
3406 return 1 if defined($self->{ignore_regex}) &&
3407 $path =~ m!$self->{ignore_regex}!;
3408 return 0 unless defined($_ignore_regex);
3409 return 1 if $path =~ m!$_ignore_regex!o;
3410 return 0;
3413 sub set_path_strip {
3414 my ($self, $path) = @_;
3415 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3418 sub open_root {
3419 { path => '' };
3422 sub open_directory {
3423 my ($self, $path, $pb, $rev) = @_;
3424 { path => $path };
3427 sub git_path {
3428 my ($self, $path) = @_;
3429 if ($self->{path_strip}) {
3430 $path =~ s!$self->{path_strip}!! or
3431 die "Failed to strip path '$path' ($self->{path_strip})\n";
3433 $path;
3436 sub delete_entry {
3437 my ($self, $path, $rev, $pb) = @_;
3438 return undef if $self->is_path_ignored($path);
3440 my $gpath = $self->git_path($path);
3441 return undef if ($gpath eq '');
3443 # remove entire directories.
3444 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3445 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3446 if ($tree) {
3447 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3448 -r --name-only -z/,
3449 $tree);
3450 local $/ = "\0";
3451 while (<$ls>) {
3452 chomp;
3453 my $rmpath = "$gpath/$_";
3454 $self->{gii}->remove($rmpath);
3455 print "\tD\t$rmpath\n" unless $::_q;
3457 print "\tD\t$gpath/\n" unless $::_q;
3458 command_close_pipe($ls, $ctx);
3459 $self->{empty}->{$path} = 0
3460 } else {
3461 $self->{gii}->remove($gpath);
3462 print "\tD\t$gpath\n" unless $::_q;
3464 undef;
3467 sub open_file {
3468 my ($self, $path, $pb, $rev) = @_;
3469 my ($mode, $blob);
3471 goto out if $self->is_path_ignored($path);
3473 my $gpath = $self->git_path($path);
3474 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3475 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3476 unless (defined $mode && defined $blob) {
3477 die "$path was not found in commit $self->{c} (r$rev)\n";
3479 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3480 $mode = '120000';
3482 out:
3483 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3484 pool => SVN::Pool->new, action => 'M' };
3487 sub add_file {
3488 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3489 my $mode;
3491 if (!$self->is_path_ignored($path)) {
3492 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3493 delete $self->{empty}->{$dir};
3494 $mode = '100644';
3496 { path => $path, mode_a => $mode, mode_b => $mode,
3497 pool => SVN::Pool->new, action => 'A' };
3500 sub add_directory {
3501 my ($self, $path, $cp_path, $cp_rev) = @_;
3502 goto out if $self->is_path_ignored($path);
3503 my $gpath = $self->git_path($path);
3504 if ($gpath eq '') {
3505 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3506 -r --name-only -z/,
3507 $self->{c});
3508 local $/ = "\0";
3509 while (<$ls>) {
3510 chomp;
3511 $self->{gii}->remove($_);
3512 print "\tD\t$_\n" unless $::_q;
3514 command_close_pipe($ls, $ctx);
3515 $self->{empty}->{$path} = 0;
3517 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3518 delete $self->{empty}->{$dir};
3519 $self->{empty}->{$path} = 1;
3520 out:
3521 { path => $path };
3524 sub change_dir_prop {
3525 my ($self, $db, $prop, $value) = @_;
3526 return undef if $self->is_path_ignored($db->{path});
3527 $self->{dir_prop}->{$db->{path}} ||= {};
3528 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3529 undef;
3532 sub absent_directory {
3533 my ($self, $path, $pb) = @_;
3534 return undef if $self->is_path_ignored($path);
3535 $self->{absent_dir}->{$pb->{path}} ||= [];
3536 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3537 undef;
3540 sub absent_file {
3541 my ($self, $path, $pb) = @_;
3542 return undef if $self->is_path_ignored($path);
3543 $self->{absent_file}->{$pb->{path}} ||= [];
3544 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3545 undef;
3548 sub change_file_prop {
3549 my ($self, $fb, $prop, $value) = @_;
3550 return undef if $self->is_path_ignored($fb->{path});
3551 if ($prop eq 'svn:executable') {
3552 if ($fb->{mode_b} != 120000) {
3553 $fb->{mode_b} = defined $value ? 100755 : 100644;
3555 } elsif ($prop eq 'svn:special') {
3556 $fb->{mode_b} = defined $value ? 120000 : 100644;
3557 } else {
3558 $self->{file_prop}->{$fb->{path}} ||= {};
3559 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3561 undef;
3564 sub apply_textdelta {
3565 my ($self, $fb, $exp) = @_;
3566 return undef if $self->is_path_ignored($fb->{path});
3567 my $fh = $::_repository->temp_acquire('svn_delta');
3568 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3569 # (but $base does not,) so dup() it for reading in close_file
3570 open my $dup, '<&', $fh or croak $!;
3571 my $base = $::_repository->temp_acquire('git_blob');
3573 if ($fb->{blob}) {
3574 my ($base_is_link, $size);
3576 if ($fb->{mode_a} eq '120000' &&
3577 ! $self->{empty_symlinks}->{$fb->{path}}) {
3578 print $base 'link ' or die "print $!\n";
3579 $base_is_link = 1;
3581 retry:
3582 $size = $::_repository->cat_blob($fb->{blob}, $base);
3583 die "Failed to read object $fb->{blob}" if ($size < 0);
3585 if (defined $exp) {
3586 seek $base, 0, 0 or croak $!;
3587 my $got = ::md5sum($base);
3588 if ($got ne $exp) {
3589 my $err = "Checksum mismatch: ".
3590 "$fb->{path} $fb->{blob}\n" .
3591 "expected: $exp\n" .
3592 " got: $got\n";
3593 if ($base_is_link) {
3594 warn $err,
3595 "Retrying... (possibly ",
3596 "a bad symlink from SVN)\n";
3597 $::_repository->temp_reset($base);
3598 $base_is_link = 0;
3599 goto retry;
3601 die $err;
3605 seek $base, 0, 0 or croak $!;
3606 $fb->{fh} = $fh;
3607 $fb->{base} = $base;
3608 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3611 sub close_file {
3612 my ($self, $fb, $exp) = @_;
3613 return undef if $self->is_path_ignored($fb->{path});
3615 my $hash;
3616 my $path = $self->git_path($fb->{path});
3617 if (my $fh = $fb->{fh}) {
3618 if (defined $exp) {
3619 seek($fh, 0, 0) or croak $!;
3620 my $got = ::md5sum($fh);
3621 if ($got ne $exp) {
3622 die "Checksum mismatch: $path\n",
3623 "expected: $exp\n got: $got\n";
3626 if ($fb->{mode_b} == 120000) {
3627 sysseek($fh, 0, 0) or croak $!;
3628 my $rd = sysread($fh, my $buf, 5);
3630 if (!defined $rd) {
3631 croak "sysread: $!\n";
3632 } elsif ($rd == 0) {
3633 warn "$path has mode 120000",
3634 " but it points to nothing\n",
3635 "converting to an empty file with mode",
3636 " 100644\n";
3637 $fb->{mode_b} = '100644';
3638 } elsif ($buf ne 'link ') {
3639 warn "$path has mode 120000",
3640 " but is not a link\n";
3641 } else {
3642 my $tmp_fh = $::_repository->temp_acquire(
3643 'svn_hash');
3644 my $res;
3645 while ($res = sysread($fh, my $str, 1024)) {
3646 my $out = syswrite($tmp_fh, $str, $res);
3647 defined($out) && $out == $res
3648 or croak("write ",
3649 Git::temp_path($tmp_fh),
3650 ": $!\n");
3652 defined $res or croak $!;
3654 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3655 Git::temp_release($tmp_fh, 1);
3659 $hash = $::_repository->hash_and_insert_object(
3660 Git::temp_path($fh));
3661 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3663 Git::temp_release($fb->{base}, 1);
3664 Git::temp_release($fh, 1);
3665 } else {
3666 $hash = $fb->{blob} or die "no blob information\n";
3668 $fb->{pool}->clear;
3669 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3670 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3671 undef;
3674 sub abort_edit {
3675 my $self = shift;
3676 $self->{nr} = $self->{gii}->{nr};
3677 delete $self->{gii};
3678 $self->SUPER::abort_edit(@_);
3681 sub close_edit {
3682 my $self = shift;
3683 $self->{git_commit_ok} = 1;
3684 $self->{nr} = $self->{gii}->{nr};
3685 delete $self->{gii};
3686 $self->SUPER::close_edit(@_);
3689 package SVN::Git::Editor;
3690 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3691 use strict;
3692 use warnings;
3693 use Carp qw/croak/;
3694 use IO::File;
3696 sub new {
3697 my ($class, $opts) = @_;
3698 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3699 die "$_ required!\n" unless (defined $opts->{$_});
3702 my $pool = SVN::Pool->new;
3703 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3704 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3705 $opts->{r}, $mods);
3707 # $opts->{ra} functions should not be used after this:
3708 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3709 $opts->{editor_cb}, $pool);
3710 my $self = SVN::Delta::Editor->new(@ce, $pool);
3711 bless $self, $class;
3712 foreach (qw/svn_path r tree_a tree_b/) {
3713 $self->{$_} = $opts->{$_};
3715 $self->{url} = $opts->{ra}->{url};
3716 $self->{mods} = $mods;
3717 $self->{types} = $types;
3718 $self->{pool} = $pool;
3719 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3720 $self->{rm} = { };
3721 $self->{path_prefix} = length $self->{svn_path} ?
3722 "$self->{svn_path}/" : '';
3723 $self->{config} = $opts->{config};
3724 return $self;
3727 sub generate_diff {
3728 my ($tree_a, $tree_b) = @_;
3729 my @diff_tree = qw(diff-tree -z -r);
3730 if ($_cp_similarity) {
3731 push @diff_tree, "-C$_cp_similarity";
3732 } else {
3733 push @diff_tree, '-C';
3735 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3736 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3737 push @diff_tree, $tree_a, $tree_b;
3738 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3739 local $/ = "\0";
3740 my $state = 'meta';
3741 my @mods;
3742 while (<$diff_fh>) {
3743 chomp $_; # this gets rid of the trailing "\0"
3744 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3745 ($::sha1)\s($::sha1)\s
3746 ([MTCRAD])\d*$/xo) {
3747 push @mods, { mode_a => $1, mode_b => $2,
3748 sha1_a => $3, sha1_b => $4,
3749 chg => $5 };
3750 if ($5 =~ /^(?:C|R)$/) {
3751 $state = 'file_a';
3752 } else {
3753 $state = 'file_b';
3755 } elsif ($state eq 'file_a') {
3756 my $x = $mods[$#mods] or croak "Empty array\n";
3757 if ($x->{chg} !~ /^(?:C|R)$/) {
3758 croak "Error parsing $_, $x->{chg}\n";
3760 $x->{file_a} = $_;
3761 $state = 'file_b';
3762 } elsif ($state eq 'file_b') {
3763 my $x = $mods[$#mods] or croak "Empty array\n";
3764 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3765 croak "Error parsing $_, $x->{chg}\n";
3767 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3768 croak "Error parsing $_, $x->{chg}\n";
3770 $x->{file_b} = $_;
3771 $state = 'meta';
3772 } else {
3773 croak "Error parsing $_\n";
3776 command_close_pipe($diff_fh, $ctx);
3777 \@mods;
3780 sub check_diff_paths {
3781 my ($ra, $pfx, $rev, $mods) = @_;
3782 my %types;
3783 $pfx .= '/' if length $pfx;
3785 sub type_diff_paths {
3786 my ($ra, $types, $path, $rev) = @_;
3787 my @p = split m#/+#, $path;
3788 my $c = shift @p;
3789 unless (defined $types->{$c}) {
3790 $types->{$c} = $ra->check_path($c, $rev);
3792 while (@p) {
3793 $c .= '/' . shift @p;
3794 next if defined $types->{$c};
3795 $types->{$c} = $ra->check_path($c, $rev);
3799 foreach my $m (@$mods) {
3800 foreach my $f (qw/file_a file_b/) {
3801 next unless defined $m->{$f};
3802 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3803 if (length $pfx.$dir && ! defined $types{$dir}) {
3804 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3808 \%types;
3811 sub split_path {
3812 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3815 sub repo_path {
3816 my ($self, $path) = @_;
3817 $self->{path_prefix}.(defined $path ? $path : '');
3820 sub url_path {
3821 my ($self, $path) = @_;
3822 if ($self->{url} =~ m#^https?://#) {
3823 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3825 $self->{url} . '/' . $self->repo_path($path);
3828 sub rmdirs {
3829 my ($self) = @_;
3830 my $rm = $self->{rm};
3831 delete $rm->{''}; # we never delete the url we're tracking
3832 return unless %$rm;
3834 foreach (keys %$rm) {
3835 my @d = split m#/#, $_;
3836 my $c = shift @d;
3837 $rm->{$c} = 1;
3838 while (@d) {
3839 $c .= '/' . shift @d;
3840 $rm->{$c} = 1;
3843 delete $rm->{$self->{svn_path}};
3844 delete $rm->{''}; # we never delete the url we're tracking
3845 return unless %$rm;
3847 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3848 $self->{tree_b});
3849 local $/ = "\0";
3850 while (<$fh>) {
3851 chomp;
3852 my @dn = split m#/#, $_;
3853 while (pop @dn) {
3854 delete $rm->{join '/', @dn};
3856 unless (%$rm) {
3857 close $fh;
3858 return;
3861 command_close_pipe($fh, $ctx);
3863 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3864 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3865 $self->close_directory($bat->{$d}, $p);
3866 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3867 print "\tD+\t$d/\n" unless $::_q;
3868 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3869 delete $bat->{$d};
3873 sub open_or_add_dir {
3874 my ($self, $full_path, $baton) = @_;
3875 my $t = $self->{types}->{$full_path};
3876 if (!defined $t) {
3877 die "$full_path not known in r$self->{r} or we have a bug!\n";
3880 no warnings 'once';
3881 # SVN::Node::none and SVN::Node::file are used only once,
3882 # so we're shutting up Perl's warnings about them.
3883 if ($t == $SVN::Node::none) {
3884 return $self->add_directory($full_path, $baton,
3885 undef, -1, $self->{pool});
3886 } elsif ($t == $SVN::Node::dir) {
3887 return $self->open_directory($full_path, $baton,
3888 $self->{r}, $self->{pool});
3889 } # no warnings 'once'
3890 print STDERR "$full_path already exists in repository at ",
3891 "r$self->{r} and it is not a directory (",
3892 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3893 } # no warnings 'once'
3894 exit 1;
3897 sub ensure_path {
3898 my ($self, $path) = @_;
3899 my $bat = $self->{bat};
3900 my $repo_path = $self->repo_path($path);
3901 return $bat->{''} unless (length $repo_path);
3902 my @p = split m#/+#, $repo_path;
3903 my $c = shift @p;
3904 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3905 while (@p) {
3906 my $c0 = $c;
3907 $c .= '/' . shift @p;
3908 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3910 return $bat->{$c};
3913 # Subroutine to convert a globbing pattern to a regular expression.
3914 # From perl cookbook.
3915 sub glob2pat {
3916 my $globstr = shift;
3917 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3918 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3919 return '^' . $globstr . '$';
3922 sub check_autoprop {
3923 my ($self, $pattern, $properties, $file, $fbat) = @_;
3924 # Convert the globbing pattern to a regular expression.
3925 my $regex = glob2pat($pattern);
3926 # Check if the pattern matches the file name.
3927 if($file =~ m/($regex)/) {
3928 # Parse the list of properties to set.
3929 my @props = split(/;/, $properties);
3930 foreach my $prop (@props) {
3931 # Parse 'name=value' syntax and set the property.
3932 if ($prop =~ /([^=]+)=(.*)/) {
3933 my ($n,$v) = ($1,$2);
3934 for ($n, $v) {
3935 s/^\s+//; s/\s+$//;
3937 $self->change_file_prop($fbat, $n, $v);
3943 sub apply_autoprops {
3944 my ($self, $file, $fbat) = @_;
3945 my $conf_t = ${$self->{config}}{'config'};
3946 no warnings 'once';
3947 # Check [miscellany]/enable-auto-props in svn configuration.
3948 if (SVN::_Core::svn_config_get_bool(
3949 $conf_t,
3950 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3951 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3952 0)) {
3953 # Auto-props are enabled. Enumerate them to look for matches.
3954 my $callback = sub {
3955 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3957 SVN::_Core::svn_config_enumerate(
3958 $conf_t,
3959 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3960 $callback);
3964 sub A {
3965 my ($self, $m) = @_;
3966 my ($dir, $file) = split_path($m->{file_b});
3967 my $pbat = $self->ensure_path($dir);
3968 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3969 undef, -1);
3970 print "\tA\t$m->{file_b}\n" unless $::_q;
3971 $self->apply_autoprops($file, $fbat);
3972 $self->chg_file($fbat, $m);
3973 $self->close_file($fbat,undef,$self->{pool});
3976 sub C {
3977 my ($self, $m) = @_;
3978 my ($dir, $file) = split_path($m->{file_b});
3979 my $pbat = $self->ensure_path($dir);
3980 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3981 $self->url_path($m->{file_a}), $self->{r});
3982 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3983 $self->chg_file($fbat, $m);
3984 $self->close_file($fbat,undef,$self->{pool});
3987 sub delete_entry {
3988 my ($self, $path, $pbat) = @_;
3989 my $rpath = $self->repo_path($path);
3990 my ($dir, $file) = split_path($rpath);
3991 $self->{rm}->{$dir} = 1;
3992 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3995 sub R {
3996 my ($self, $m) = @_;
3997 my ($dir, $file) = split_path($m->{file_b});
3998 my $pbat = $self->ensure_path($dir);
3999 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4000 $self->url_path($m->{file_a}), $self->{r});
4001 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4002 $self->apply_autoprops($file, $fbat);
4003 $self->chg_file($fbat, $m);
4004 $self->close_file($fbat,undef,$self->{pool});
4006 ($dir, $file) = split_path($m->{file_a});
4007 $pbat = $self->ensure_path($dir);
4008 $self->delete_entry($m->{file_a}, $pbat);
4011 sub M {
4012 my ($self, $m) = @_;
4013 my ($dir, $file) = split_path($m->{file_b});
4014 my $pbat = $self->ensure_path($dir);
4015 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4016 $pbat,$self->{r},$self->{pool});
4017 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4018 $self->chg_file($fbat, $m);
4019 $self->close_file($fbat,undef,$self->{pool});
4022 sub T { shift->M(@_) }
4024 sub change_file_prop {
4025 my ($self, $fbat, $pname, $pval) = @_;
4026 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4029 sub _chg_file_get_blob ($$$$) {
4030 my ($self, $fbat, $m, $which) = @_;
4031 my $fh = $::_repository->temp_acquire("git_blob_$which");
4032 if ($m->{"mode_$which"} =~ /^120/) {
4033 print $fh 'link ' or croak $!;
4034 $self->change_file_prop($fbat,'svn:special','*');
4035 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4036 $self->change_file_prop($fbat,'svn:special',undef);
4038 my $blob = $m->{"sha1_$which"};
4039 return ($fh,) if ($blob =~ /^0{40}$/);
4040 my $size = $::_repository->cat_blob($blob, $fh);
4041 croak "Failed to read object $blob" if ($size < 0);
4042 $fh->flush == 0 or croak $!;
4043 seek $fh, 0, 0 or croak $!;
4045 my $exp = ::md5sum($fh);
4046 seek $fh, 0, 0 or croak $!;
4047 return ($fh, $exp);
4050 sub chg_file {
4051 my ($self, $fbat, $m) = @_;
4052 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4053 $self->change_file_prop($fbat,'svn:executable','*');
4054 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4055 $self->change_file_prop($fbat,'svn:executable',undef);
4057 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4058 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4059 my $pool = SVN::Pool->new;
4060 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4061 if (-s $fh_a) {
4062 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4063 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4064 if (defined $res) {
4065 die "Unexpected result from send_txstream: $res\n",
4066 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4068 } else {
4069 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4070 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4071 if ($got ne $exp_b);
4073 Git::temp_release($fh_b, 1);
4074 Git::temp_release($fh_a, 1);
4075 $pool->clear;
4078 sub D {
4079 my ($self, $m) = @_;
4080 my ($dir, $file) = split_path($m->{file_b});
4081 my $pbat = $self->ensure_path($dir);
4082 print "\tD\t$m->{file_b}\n" unless $::_q;
4083 $self->delete_entry($m->{file_b}, $pbat);
4086 sub close_edit {
4087 my ($self) = @_;
4088 my ($p,$bat) = ($self->{pool}, $self->{bat});
4089 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4090 next if $_ eq '';
4091 $self->close_directory($bat->{$_}, $p);
4093 $self->close_directory($bat->{''}, $p);
4094 $self->SUPER::close_edit($p);
4095 $p->clear;
4098 sub abort_edit {
4099 my ($self) = @_;
4100 $self->SUPER::abort_edit($self->{pool});
4103 sub DESTROY {
4104 my $self = shift;
4105 $self->SUPER::DESTROY(@_);
4106 $self->{pool}->clear;
4109 # this drives the editor
4110 sub apply_diff {
4111 my ($self) = @_;
4112 my $mods = $self->{mods};
4113 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4114 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4115 my $f = $m->{chg};
4116 if (defined $o{$f}) {
4117 $self->$f($m);
4118 } else {
4119 fatal("Invalid change type: $f");
4122 $self->rmdirs if $_rmdir;
4123 if (@$mods == 0) {
4124 $self->abort_edit;
4125 } else {
4126 $self->close_edit;
4128 return scalar @$mods;
4131 package Git::SVN::Ra;
4132 use vars qw/@ISA $config_dir $_log_window_size/;
4133 use strict;
4134 use warnings;
4135 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4137 BEGIN {
4138 # enforce temporary pool usage for some simple functions
4139 no strict 'refs';
4140 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4141 get_file/) {
4142 my $SUPER = "SUPER::$f";
4143 *$f = sub {
4144 my $self = shift;
4145 my $pool = SVN::Pool->new;
4146 my @ret = $self->$SUPER(@_,$pool);
4147 $pool->clear;
4148 wantarray ? @ret : $ret[0];
4153 sub _auth_providers () {
4155 SVN::Client::get_simple_provider(),
4156 SVN::Client::get_ssl_server_trust_file_provider(),
4157 SVN::Client::get_simple_prompt_provider(
4158 \&Git::SVN::Prompt::simple, 2),
4159 SVN::Client::get_ssl_client_cert_file_provider(),
4160 SVN::Client::get_ssl_client_cert_prompt_provider(
4161 \&Git::SVN::Prompt::ssl_client_cert, 2),
4162 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4163 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4164 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4165 SVN::Client::get_username_provider(),
4166 SVN::Client::get_ssl_server_trust_prompt_provider(
4167 \&Git::SVN::Prompt::ssl_server_trust),
4168 SVN::Client::get_username_prompt_provider(
4169 \&Git::SVN::Prompt::username, 2)
4173 sub escape_uri_only {
4174 my ($uri) = @_;
4175 my @tmp;
4176 foreach (split m{/}, $uri) {
4177 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4178 push @tmp, $_;
4180 join('/', @tmp);
4183 sub escape_url {
4184 my ($url) = @_;
4185 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4186 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4187 $url = "$scheme://$domain$uri";
4189 $url;
4192 sub new {
4193 my ($class, $url) = @_;
4194 $url =~ s!/+$!!;
4195 return $RA if ($RA && $RA->{url} eq $url);
4197 SVN::_Core::svn_config_ensure($config_dir, undef);
4198 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4199 my $config = SVN::Core::config_get_config($config_dir);
4200 $RA = undef;
4201 my $dont_store_passwords = 1;
4202 my $conf_t = ${$config}{'config'};
4204 no warnings 'once';
4205 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4206 # produces warnings that variables are used only once.
4207 # I had not found the better way to shut them up, so
4208 # the warnings of type 'once' are disabled in this block.
4209 if (SVN::_Core::svn_config_get_bool($conf_t,
4210 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4211 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4212 1) == 0) {
4213 SVN::_Core::svn_auth_set_parameter($baton,
4214 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4215 bless (\$dont_store_passwords, "_p_void"));
4217 if (SVN::_Core::svn_config_get_bool($conf_t,
4218 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4219 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4220 1) == 0) {
4221 $Git::SVN::Prompt::_no_auth_cache = 1;
4223 } # no warnings 'once'
4224 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4225 config => $config,
4226 pool => SVN::Pool->new,
4227 auth_provider_callbacks => $callbacks);
4228 $self->{url} = $url;
4229 $self->{svn_path} = $url;
4230 $self->{repos_root} = $self->get_repos_root;
4231 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4232 $self->{cache} = { check_path => { r => 0, data => {} },
4233 get_dir => { r => 0, data => {} } };
4234 $RA = bless $self, $class;
4237 sub check_path {
4238 my ($self, $path, $r) = @_;
4239 my $cache = $self->{cache}->{check_path};
4240 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4241 return $cache->{data}->{$path};
4243 my $pool = SVN::Pool->new;
4244 my $t = $self->SUPER::check_path($path, $r, $pool);
4245 $pool->clear;
4246 if ($r != $cache->{r}) {
4247 %{$cache->{data}} = ();
4248 $cache->{r} = $r;
4250 $cache->{data}->{$path} = $t;
4253 sub get_dir {
4254 my ($self, $dir, $r) = @_;
4255 my $cache = $self->{cache}->{get_dir};
4256 if ($r == $cache->{r}) {
4257 if (my $x = $cache->{data}->{$dir}) {
4258 return wantarray ? @$x : $x->[0];
4261 my $pool = SVN::Pool->new;
4262 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4263 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4264 $pool->clear;
4265 if ($r != $cache->{r}) {
4266 %{$cache->{data}} = ();
4267 $cache->{r} = $r;
4269 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4270 wantarray ? (\%dirents, $r, $props) : \%dirents;
4273 sub DESTROY {
4274 # do not call the real DESTROY since we store ourselves in $RA
4277 # get_log(paths, start, end, limit,
4278 # discover_changed_paths, strict_node_history, receiver)
4279 sub get_log {
4280 my ($self, @args) = @_;
4281 my $pool = SVN::Pool->new;
4283 # the limit parameter was not supported in SVN 1.1.x, so we
4284 # drop it. Therefore, the receiver callback passed to it
4285 # is made aware of this limitation by being wrapped if
4286 # the limit passed to is being wrapped.
4287 if ($SVN::Core::VERSION le '1.2.0') {
4288 my $limit = splice(@args, 3, 1);
4289 if ($limit > 0) {
4290 my $receiver = pop @args;
4291 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4294 my $ret = $self->SUPER::get_log(@args, $pool);
4295 $pool->clear;
4296 $ret;
4299 sub trees_match {
4300 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4301 my $ctx = SVN::Client->new(auth => _auth_providers);
4302 my $out = IO::File->new_tmpfile;
4304 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4305 # $ctx->diff(), so we'll create a default one
4306 my $pool = SVN::Pool->new_default_sub;
4308 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4309 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4310 $out->flush;
4311 my $ret = (($out->stat)[7] == 0);
4312 close $out or croak $!;
4314 $ret;
4317 sub get_commit_editor {
4318 my ($self, $log, $cb, $pool) = @_;
4319 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4320 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4323 sub gs_do_update {
4324 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4325 my $new = ($rev_a == $rev_b);
4326 my $path = $gs->{path};
4328 if ($new && -e $gs->{index}) {
4329 unlink $gs->{index} or die
4330 "Couldn't unlink index: $gs->{index}: $!\n";
4332 my $pool = SVN::Pool->new;
4333 $editor->set_path_strip($path);
4334 my (@pc) = split m#/#, $path;
4335 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4336 1, $editor, $pool);
4337 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4339 # Since we can't rely on svn_ra_reparent being available, we'll
4340 # just have to do some magic with set_path to make it so
4341 # we only want a partial path.
4342 my $sp = '';
4343 my $final = join('/', @pc);
4344 while (@pc) {
4345 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4346 $sp .= '/' if length $sp;
4347 $sp .= shift @pc;
4349 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4351 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4353 $reporter->finish_report($pool);
4354 $pool->clear;
4355 $editor->{git_commit_ok};
4358 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4359 # svn_ra_reparent didn't work before 1.4)
4360 sub gs_do_switch {
4361 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4362 my $path = $gs->{path};
4363 my $pool = SVN::Pool->new;
4365 my $full_url = $self->{url};
4366 my $old_url = $full_url;
4367 $full_url .= '/' . escape_uri_only($path) if length $path;
4368 my ($ra, $reparented);
4370 if ($old_url =~ m#^svn(\+ssh)?://#) {
4371 $_[0] = undef;
4372 $self = undef;
4373 $RA = undef;
4374 $ra = Git::SVN::Ra->new($full_url);
4375 $ra_invalid = 1;
4376 } elsif ($old_url ne $full_url) {
4377 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4378 $self->{url} = $full_url;
4379 $reparented = 1;
4382 $ra ||= $self;
4383 $url_b = escape_url($url_b);
4384 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4385 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4386 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4387 $reporter->finish_report($pool);
4389 if ($reparented) {
4390 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4391 $self->{url} = $old_url;
4394 $pool->clear;
4395 $editor->{git_commit_ok};
4398 sub longest_common_path {
4399 my ($gsv, $globs) = @_;
4400 my %common;
4401 my $common_max = scalar @$gsv;
4403 foreach my $gs (@$gsv) {
4404 my @tmp = split m#/#, $gs->{path};
4405 my $p = '';
4406 foreach (@tmp) {
4407 $p .= length($p) ? "/$_" : $_;
4408 $common{$p} ||= 0;
4409 $common{$p}++;
4412 $globs ||= [];
4413 $common_max += scalar @$globs;
4414 foreach my $glob (@$globs) {
4415 my @tmp = split m#/#, $glob->{path}->{left};
4416 my $p = '';
4417 foreach (@tmp) {
4418 $p .= length($p) ? "/$_" : $_;
4419 $common{$p} ||= 0;
4420 $common{$p}++;
4424 my $longest_path = '';
4425 foreach (sort {length $b <=> length $a} keys %common) {
4426 if ($common{$_} == $common_max) {
4427 $longest_path = $_;
4428 last;
4431 $longest_path;
4434 sub gs_fetch_loop_common {
4435 my ($self, $base, $head, $gsv, $globs) = @_;
4436 return if ($base > $head);
4437 my $inc = $_log_window_size;
4438 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4439 my $longest_path = longest_common_path($gsv, $globs);
4440 my $ra_url = $self->{url};
4441 while (1) {
4442 my %revs;
4443 my $err;
4444 my $err_handler = $SVN::Error::handler;
4445 $SVN::Error::handler = sub {
4446 ($err) = @_;
4447 skip_unknown_revs($err);
4449 sub _cb {
4450 my ($paths, $r, $author, $date, $log) = @_;
4451 [ dup_changed_paths($paths),
4452 { author => $author, date => $date, log => $log } ];
4454 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4455 sub { $revs{$_[1]} = _cb(@_) });
4456 if ($err) {
4457 print "Checked through r$max\r";
4459 if ($err && $max >= $head) {
4460 print STDERR "Path '$longest_path' ",
4461 "was probably deleted:\n",
4462 $err->expanded_message,
4463 "\nWill attempt to follow ",
4464 "revisions r$min .. r$max ",
4465 "committed before the deletion\n";
4466 my $hi = $max;
4467 while (--$hi >= $min) {
4468 my $ok;
4469 $self->get_log([$longest_path], $min, $hi,
4470 0, 1, 1, sub {
4471 $ok ||= $_[1];
4472 $revs{$_[1]} = _cb(@_) });
4473 if ($ok) {
4474 print STDERR "r$min .. r$ok OK\n";
4475 last;
4479 $SVN::Error::handler = $err_handler;
4481 my %exists = map { $_->{path} => $_ } @$gsv;
4482 foreach my $r (sort {$a <=> $b} keys %revs) {
4483 my ($paths, $logged) = @{$revs{$r}};
4485 foreach my $gs ($self->match_globs(\%exists, $paths,
4486 $globs, $r)) {
4487 if ($gs->rev_map_max >= $r) {
4488 next;
4490 next unless $gs->match_paths($paths, $r);
4491 $gs->{logged_rev_props} = $logged;
4492 if (my $last_commit = $gs->last_commit) {
4493 $gs->assert_index_clean($last_commit);
4495 my $log_entry = $gs->do_fetch($paths, $r);
4496 if ($log_entry) {
4497 $gs->do_git_commit($log_entry);
4499 $INDEX_FILES{$gs->{index}} = 1;
4501 foreach my $g (@$globs) {
4502 my $k = "svn-remote.$g->{remote}." .
4503 "$g->{t}-maxRev";
4504 Git::SVN::tmp_config($k, $r);
4506 if ($ra_invalid) {
4507 $_[0] = undef;
4508 $self = undef;
4509 $RA = undef;
4510 $self = Git::SVN::Ra->new($ra_url);
4511 $ra_invalid = undef;
4514 # pre-fill the .rev_db since it'll eventually get filled in
4515 # with '0' x40 if something new gets committed
4516 foreach my $gs (@$gsv) {
4517 next if $gs->rev_map_max >= $max;
4518 next if defined $gs->rev_map_get($max);
4519 $gs->rev_map_set($max, 0 x40);
4521 foreach my $g (@$globs) {
4522 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4523 Git::SVN::tmp_config($k, $max);
4525 last if $max >= $head;
4526 $min = $max + 1;
4527 $max += $inc;
4528 $max = $head if ($max > $head);
4530 Git::SVN::gc();
4533 sub get_dir_globbed {
4534 my ($self, $left, $depth, $r) = @_;
4536 my @x = eval { $self->get_dir($left, $r) };
4537 return unless scalar @x == 3;
4538 my $dirents = $x[0];
4539 my @finalents;
4540 foreach my $de (keys %$dirents) {
4541 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4542 if ($depth > 1) {
4543 my @args = ("$left/$de", $depth - 1, $r);
4544 foreach my $dir ($self->get_dir_globbed(@args)) {
4545 push @finalents, "$de/$dir";
4547 } else {
4548 push @finalents, $de;
4551 @finalents;
4554 sub match_globs {
4555 my ($self, $exists, $paths, $globs, $r) = @_;
4557 sub get_dir_check {
4558 my ($self, $exists, $g, $r) = @_;
4560 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4561 $g->{path}->{depth},
4562 $r);
4564 foreach my $de (@dirs) {
4565 my $p = $g->{path}->full_path($de);
4566 next if $exists->{$p};
4567 next if (length $g->{path}->{right} &&
4568 ($self->check_path($p, $r) !=
4569 $SVN::Node::dir));
4570 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4571 $g->{ref}->full_path($de), 1);
4574 foreach my $g (@$globs) {
4575 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4576 if ($path->{action} =~ /^[AR]$/) {
4577 get_dir_check($self, $exists, $g, $r);
4580 foreach (keys %$paths) {
4581 if (/$g->{path}->{left_regex}/ &&
4582 !/$g->{path}->{regex}/) {
4583 next if $paths->{$_}->{action} !~ /^[AR]$/;
4584 get_dir_check($self, $exists, $g, $r);
4586 next unless /$g->{path}->{regex}/;
4587 my $p = $1;
4588 my $pathname = $g->{path}->full_path($p);
4589 next if $exists->{$pathname};
4590 next if ($self->check_path($pathname, $r) !=
4591 $SVN::Node::dir);
4592 $exists->{$pathname} = Git::SVN->init(
4593 $self->{url}, $pathname, undef,
4594 $g->{ref}->full_path($p), 1);
4596 my $c = '';
4597 foreach (split m#/#, $g->{path}->{left}) {
4598 $c .= "/$_";
4599 next unless ($paths->{$c} &&
4600 ($paths->{$c}->{action} =~ /^[AR]$/));
4601 get_dir_check($self, $exists, $g, $r);
4604 values %$exists;
4607 sub minimize_url {
4608 my ($self) = @_;
4609 return $self->{url} if ($self->{url} eq $self->{repos_root});
4610 my $url = $self->{repos_root};
4611 my @components = split(m!/!, $self->{svn_path});
4612 my $c = '';
4613 do {
4614 $url .= "/$c" if length $c;
4615 eval { (ref $self)->new($url)->get_latest_revnum };
4616 } while ($@ && ($c = shift @components));
4617 $url;
4620 sub can_do_switch {
4621 my $self = shift;
4622 unless (defined $can_do_switch) {
4623 my $pool = SVN::Pool->new;
4624 my $rep = eval {
4625 $self->do_switch(1, '', 0, $self->{url},
4626 SVN::Delta::Editor->new, $pool);
4628 if ($@) {
4629 $can_do_switch = 0;
4630 } else {
4631 $rep->abort_report($pool);
4632 $can_do_switch = 1;
4634 $pool->clear;
4636 $can_do_switch;
4639 sub skip_unknown_revs {
4640 my ($err) = @_;
4641 my $errno = $err->apr_err();
4642 # Maybe the branch we're tracking didn't
4643 # exist when the repo started, so it's
4644 # not an error if it doesn't, just continue
4646 # Wonderfully consistent library, eh?
4647 # 160013 - svn:// and file://
4648 # 175002 - http(s)://
4649 # 175007 - http(s):// (this repo required authorization, too...)
4650 # More codes may be discovered later...
4651 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4652 my $err_key = $err->expanded_message;
4653 # revision numbers change every time, filter them out
4654 $err_key =~ s/\d+/\0/g;
4655 $err_key = "$errno\0$err_key";
4656 unless ($ignored_err{$err_key}) {
4657 warn "W: Ignoring error from SVN, path probably ",
4658 "does not exist: ($errno): ",
4659 $err->expanded_message,"\n";
4660 warn "W: Do not be alarmed at the above message ",
4661 "git-svn is just searching aggressively for ",
4662 "old history.\n",
4663 "This may take a while on large repositories\n";
4664 $ignored_err{$err_key} = 1;
4666 return;
4668 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4671 # svn_log_changed_path_t objects passed to get_log are likely to be
4672 # overwritten even if only the refs are copied to an external variable,
4673 # so we should dup the structures in their entirety. Using an externally
4674 # passed pool (instead of our temporary and quickly cleared pool in
4675 # Git::SVN::Ra) does not help matters at all...
4676 sub dup_changed_paths {
4677 my ($paths) = @_;
4678 return undef unless $paths;
4679 my %ret;
4680 foreach my $p (keys %$paths) {
4681 my $i = $paths->{$p};
4682 my %s = map { $_ => $i->$_ }
4683 qw/copyfrom_path copyfrom_rev action/;
4684 $ret{$p} = \%s;
4686 \%ret;
4689 package Git::SVN::Log;
4690 use strict;
4691 use warnings;
4692 use POSIX qw/strftime/;
4693 use Time::Local;
4694 use constant commit_log_separator => ('-' x 72) . "\n";
4695 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4696 %rusers $show_commit $incremental/;
4697 my $l_fmt;
4699 sub cmt_showable {
4700 my ($c) = @_;
4701 return 1 if defined $c->{r};
4703 # big commit message got truncated by the 16k pretty buffer in rev-list
4704 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4705 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4706 @{$c->{l}} = ();
4707 my @log = command(qw/cat-file commit/, $c->{c});
4709 # shift off the headers
4710 shift @log while ($log[0] ne '');
4711 shift @log;
4713 # TODO: make $c->{l} not have a trailing newline in the future
4714 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4716 (undef, $c->{r}, undef) = ::extract_metadata(
4717 (grep(/^git-svn-id: /, @log))[-1]);
4719 return defined $c->{r};
4722 sub log_use_color {
4723 return $color || Git->repository->get_colorbool('color.diff');
4726 sub git_svn_log_cmd {
4727 my ($r_min, $r_max, @args) = @_;
4728 my $head = 'HEAD';
4729 my (@files, @log_opts);
4730 foreach my $x (@args) {
4731 if ($x eq '--' || @files) {
4732 push @files, $x;
4733 } else {
4734 if (::verify_ref("$x^0")) {
4735 $head = $x;
4736 } else {
4737 push @log_opts, $x;
4742 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4743 $gs ||= Git::SVN->_new;
4744 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4745 $gs->refname);
4746 push @cmd, '-r' unless $non_recursive;
4747 push @cmd, qw/--raw --name-status/ if $verbose;
4748 push @cmd, '--color' if log_use_color();
4749 push @cmd, @log_opts;
4750 if (defined $r_max && $r_max == $r_min) {
4751 push @cmd, '--max-count=1';
4752 if (my $c = $gs->rev_map_get($r_max)) {
4753 push @cmd, $c;
4755 } elsif (defined $r_max) {
4756 if ($r_max < $r_min) {
4757 ($r_min, $r_max) = ($r_max, $r_min);
4759 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4760 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4761 # If there are no commits in the range, both $c_max and $c_min
4762 # will be undefined. If there is at least 1 commit in the
4763 # range, both will be defined.
4764 return () if !defined $c_min || !defined $c_max;
4765 if ($c_min eq $c_max) {
4766 push @cmd, '--max-count=1', $c_min;
4767 } else {
4768 push @cmd, '--boundary', "$c_min..$c_max";
4771 return (@cmd, @files);
4774 # adapted from pager.c
4775 sub config_pager {
4776 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4777 if (!defined $pager) {
4778 $pager = 'less';
4779 } elsif (length $pager == 0 || $pager eq 'cat') {
4780 $pager = undef;
4782 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4785 sub run_pager {
4786 return unless -t *STDOUT && defined $pager;
4787 pipe my ($rfd, $wfd) or return;
4788 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4789 if (!$pid) {
4790 open STDOUT, '>&', $wfd or
4791 ::fatal "Can't redirect to stdout: $!";
4792 return;
4794 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4795 $ENV{LESS} ||= 'FRSX';
4796 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4799 sub format_svn_date {
4800 # some systmes don't handle or mishandle %z, so be creative.
4801 my $t = shift || time;
4802 my $gm = timelocal(gmtime($t));
4803 my $sign = qw( + + - )[ $t <=> $gm ];
4804 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4805 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4808 sub parse_git_date {
4809 my ($t, $tz) = @_;
4810 # Date::Parse isn't in the standard Perl distro :(
4811 if ($tz =~ s/^\+//) {
4812 $t += tz_to_s_offset($tz);
4813 } elsif ($tz =~ s/^\-//) {
4814 $t -= tz_to_s_offset($tz);
4816 return $t;
4819 sub set_local_timezone {
4820 if (defined $TZ) {
4821 $ENV{TZ} = $TZ;
4822 } else {
4823 delete $ENV{TZ};
4827 sub tz_to_s_offset {
4828 my ($tz) = @_;
4829 $tz =~ s/(\d\d)$//;
4830 return ($1 * 60) + ($tz * 3600);
4833 sub get_author_info {
4834 my ($dest, $author, $t, $tz) = @_;
4835 $author =~ s/(?:^\s*|\s*$)//g;
4836 $dest->{a_raw} = $author;
4837 my $au;
4838 if ($::_authors) {
4839 $au = $rusers{$author} || undef;
4841 if (!$au) {
4842 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4844 $dest->{t} = $t;
4845 $dest->{tz} = $tz;
4846 $dest->{a} = $au;
4847 $dest->{t_utc} = parse_git_date($t, $tz);
4850 sub process_commit {
4851 my ($c, $r_min, $r_max, $defer) = @_;
4852 if (defined $r_min && defined $r_max) {
4853 if ($r_min == $c->{r} && $r_min == $r_max) {
4854 show_commit($c);
4855 return 0;
4857 return 1 if $r_min == $r_max;
4858 if ($r_min < $r_max) {
4859 # we need to reverse the print order
4860 return 0 if (defined $limit && --$limit < 0);
4861 push @$defer, $c;
4862 return 1;
4864 if ($r_min != $r_max) {
4865 return 1 if ($r_min < $c->{r});
4866 return 1 if ($r_max > $c->{r});
4869 return 0 if (defined $limit && --$limit < 0);
4870 show_commit($c);
4871 return 1;
4874 sub show_commit {
4875 my $c = shift;
4876 if ($oneline) {
4877 my $x = "\n";
4878 if (my $l = $c->{l}) {
4879 while ($l->[0] =~ /^\s*$/) { shift @$l }
4880 $x = $l->[0];
4882 $l_fmt ||= 'A' . length($c->{r});
4883 print 'r',pack($l_fmt, $c->{r}),' | ';
4884 print "$c->{c} | " if $show_commit;
4885 print $x;
4886 } else {
4887 show_commit_normal($c);
4891 sub show_commit_changed_paths {
4892 my ($c) = @_;
4893 return unless $c->{changed};
4894 print "Changed paths:\n", @{$c->{changed}};
4897 sub show_commit_normal {
4898 my ($c) = @_;
4899 print commit_log_separator, "r$c->{r} | ";
4900 print "$c->{c} | " if $show_commit;
4901 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4902 my $nr_line = 0;
4904 if (my $l = $c->{l}) {
4905 while ($l->[$#$l] eq "\n" && $#$l > 0
4906 && $l->[($#$l - 1)] eq "\n") {
4907 pop @$l;
4909 $nr_line = scalar @$l;
4910 if (!$nr_line) {
4911 print "1 line\n\n\n";
4912 } else {
4913 if ($nr_line == 1) {
4914 $nr_line = '1 line';
4915 } else {
4916 $nr_line .= ' lines';
4918 print $nr_line, "\n";
4919 show_commit_changed_paths($c);
4920 print "\n";
4921 print $_ foreach @$l;
4923 } else {
4924 print "1 line\n";
4925 show_commit_changed_paths($c);
4926 print "\n";
4929 foreach my $x (qw/raw stat diff/) {
4930 if ($c->{$x}) {
4931 print "\n";
4932 print $_ foreach @{$c->{$x}}
4937 sub cmd_show_log {
4938 my (@args) = @_;
4939 my ($r_min, $r_max);
4940 my $r_last = -1; # prevent dupes
4941 set_local_timezone();
4942 if (defined $::_revision) {
4943 if ($::_revision =~ /^(\d+):(\d+)$/) {
4944 ($r_min, $r_max) = ($1, $2);
4945 } elsif ($::_revision =~ /^\d+$/) {
4946 $r_min = $r_max = $::_revision;
4947 } else {
4948 ::fatal "-r$::_revision is not supported, use ",
4949 "standard 'git log' arguments instead";
4953 config_pager();
4954 @args = git_svn_log_cmd($r_min, $r_max, @args);
4955 if (!@args) {
4956 print commit_log_separator unless $incremental || $oneline;
4957 return;
4959 my $log = command_output_pipe(@args);
4960 run_pager();
4961 my (@k, $c, $d, $stat);
4962 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4963 while (<$log>) {
4964 if (/^${esc_color}commit -?($::sha1_short)/o) {
4965 my $cmt = $1;
4966 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4967 $r_last = $c->{r};
4968 process_commit($c, $r_min, $r_max, \@k) or
4969 goto out;
4971 $d = undef;
4972 $c = { c => $cmt };
4973 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4974 get_author_info($c, $1, $2, $3);
4975 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4976 # ignore
4977 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4978 push @{$c->{raw}}, $_;
4979 } elsif (/^${esc_color}[ACRMDT]\t/) {
4980 # we could add $SVN->{svn_path} here, but that requires
4981 # remote access at the moment (repo_path_split)...
4982 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4983 push @{$c->{changed}}, $_;
4984 } elsif (/^${esc_color}diff /o) {
4985 $d = 1;
4986 push @{$c->{diff}}, $_;
4987 } elsif ($d) {
4988 push @{$c->{diff}}, $_;
4989 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4990 $esc_color*[\+\-]*$esc_color$/x) {
4991 $stat = 1;
4992 push @{$c->{stat}}, $_;
4993 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4994 push @{$c->{stat}}, $_;
4995 $stat = undef;
4996 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4997 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4998 } elsif (s/^${esc_color} //o) {
4999 push @{$c->{l}}, $_;
5002 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5003 $r_last = $c->{r};
5004 process_commit($c, $r_min, $r_max, \@k);
5006 if (@k) {
5007 ($r_min, $r_max) = ($r_max, $r_min);
5008 process_commit($_, $r_min, $r_max) foreach reverse @k;
5010 out:
5011 close $log;
5012 print commit_log_separator unless $incremental || $oneline;
5015 sub cmd_blame {
5016 my $path = pop;
5018 config_pager();
5019 run_pager();
5021 my ($fh, $ctx, $rev);
5023 if ($_git_format) {
5024 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5025 while (my $line = <$fh>) {
5026 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5027 # Uncommitted edits show up as a rev ID of
5028 # all zeros, which we can't look up with
5029 # cmt_metadata
5030 if ($1 !~ /^0+$/) {
5031 (undef, $rev, undef) =
5032 ::cmt_metadata($1);
5033 $rev = '0' if (!$rev);
5034 } else {
5035 $rev = '0';
5037 $rev = sprintf('%-10s', $rev);
5038 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5040 print $line;
5042 } else {
5043 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5044 '--', $path);
5045 my ($sha1);
5046 my %authors;
5047 my @buffer;
5048 my %dsha; #distinct sha keys
5050 while (my $line = <$fh>) {
5051 push @buffer, $line;
5052 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5053 $dsha{$1} = 1;
5057 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5059 foreach my $line (@buffer) {
5060 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5061 $rev = $s2r->{$1};
5062 $rev = '0' if (!$rev)
5064 elsif ($line =~ /^author (.*)/) {
5065 $authors{$rev} = $1;
5066 $authors{$rev} =~ s/\s/_/g;
5068 elsif ($line =~ /^\t(.*)$/) {
5069 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5073 command_close_pipe($fh, $ctx);
5076 package Git::SVN::Migration;
5077 # these version numbers do NOT correspond to actual version numbers
5078 # of git nor git-svn. They are just relative.
5080 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5082 # v1 layout: .git/$id/info/url, refs/remotes/$id
5084 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5086 # v3 layout: .git/svn/$id, refs/remotes/$id
5087 # - info/url may remain for backwards compatibility
5088 # - this is what we migrate up to this layout automatically,
5089 # - this will be used by git svn init on single branches
5090 # v3.1 layout (auto migrated):
5091 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5092 # for backwards compatibility
5094 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5095 # - this is only created for newly multi-init-ed
5096 # repositories. Similar in spirit to the
5097 # --use-separate-remotes option in git-clone (now default)
5098 # - we do not automatically migrate to this (following
5099 # the example set by core git)
5101 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5102 # - newer, more-efficient format that uses 24-bytes per record
5103 # with no filler space.
5104 # - use xxd -c24 < .rev_map.$UUID to view and debug
5105 # - This is a one-way migration, repositories updated to the
5106 # new format will not be able to use old git-svn without
5107 # rebuilding the .rev_db. Rebuilding the rev_db is not
5108 # possible if noMetadata or useSvmProps are set; but should
5109 # be no problem for users that use the (sensible) defaults.
5110 use strict;
5111 use warnings;
5112 use Carp qw/croak/;
5113 use File::Path qw/mkpath/;
5114 use File::Basename qw/dirname basename/;
5115 use vars qw/$_minimize/;
5117 sub migrate_from_v0 {
5118 my $git_dir = $ENV{GIT_DIR};
5119 return undef unless -d $git_dir;
5120 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5121 my $migrated = 0;
5122 while (<$fh>) {
5123 chomp;
5124 my ($id, $orig_ref) = ($_, $_);
5125 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5126 next unless -f "$git_dir/$id/info/url";
5127 my $new_ref = "refs/remotes/$id";
5128 if (::verify_ref("$new_ref^0")) {
5129 print STDERR "W: $orig_ref is probably an old ",
5130 "branch used by an ancient version of ",
5131 "git-svn.\n",
5132 "However, $new_ref also exists.\n",
5133 "We will not be able ",
5134 "to use this branch until this ",
5135 "ambiguity is resolved.\n";
5136 next;
5138 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5139 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5140 command_noisy('update-ref', $new_ref, $orig_ref);
5141 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5142 $migrated++;
5144 command_close_pipe($fh, $ctx);
5145 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5146 $migrated;
5149 sub migrate_from_v1 {
5150 my $git_dir = $ENV{GIT_DIR};
5151 my $migrated = 0;
5152 return $migrated unless -d $git_dir;
5153 my $svn_dir = "$git_dir/svn";
5155 # just in case somebody used 'svn' as their $id at some point...
5156 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5158 print STDERR "Migrating from a git-svn v1 layout...\n";
5159 mkpath([$svn_dir]);
5160 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5161 "$svn_dir\n\t(required for this version ",
5162 "($::VERSION) of git-svn) does not exist.\n";
5163 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5164 while (<$fh>) {
5165 my $x = $_;
5166 next unless $x =~ s#^refs/remotes/##;
5167 chomp $x;
5168 next unless -f "$git_dir/$x/info/url";
5169 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5170 next unless $u;
5171 my $dn = dirname("$git_dir/svn/$x");
5172 mkpath([$dn]) unless -d $dn;
5173 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5174 mkpath(["$git_dir/svn/svn"]);
5175 print STDERR " - $git_dir/$x/info => ",
5176 "$git_dir/svn/$x/info\n";
5177 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5178 croak "$!: $x";
5179 # don't worry too much about these, they probably
5180 # don't exist with repos this old (save for index,
5181 # and we can easily regenerate that)
5182 foreach my $f (qw/unhandled.log index .rev_db/) {
5183 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5185 } else {
5186 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5187 rename "$git_dir/$x", "$git_dir/svn/$x" or
5188 croak "$!: $x";
5190 $migrated++;
5192 command_close_pipe($fh, $ctx);
5193 print STDERR "Done migrating from a git-svn v1 layout\n";
5194 $migrated;
5197 sub read_old_urls {
5198 my ($l_map, $pfx, $path) = @_;
5199 my @dir;
5200 foreach (<$path/*>) {
5201 if (-r "$_/info/url") {
5202 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5203 my $ref_id = $pfx . basename $_;
5204 my $url = ::file_to_s("$_/info/url");
5205 $l_map->{$ref_id} = $url;
5206 } elsif (-d $_) {
5207 push @dir, $_;
5210 foreach (@dir) {
5211 my $x = $_;
5212 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5213 read_old_urls($l_map, $x, $_);
5217 sub migrate_from_v2 {
5218 my @cfg = command(qw/config -l/);
5219 return if grep /^svn-remote\..+\.url=/, @cfg;
5220 my %l_map;
5221 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5222 my $migrated = 0;
5224 foreach my $ref_id (sort keys %l_map) {
5225 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5226 if ($@) {
5227 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5229 $migrated++;
5231 $migrated;
5234 sub minimize_connections {
5235 my $r = Git::SVN::read_all_remotes();
5236 my $new_urls = {};
5237 my $root_repos = {};
5238 foreach my $repo_id (keys %$r) {
5239 my $url = $r->{$repo_id}->{url} or next;
5240 my $fetch = $r->{$repo_id}->{fetch} or next;
5241 my $ra = Git::SVN::Ra->new($url);
5243 # skip existing cases where we already connect to the root
5244 if (($ra->{url} eq $ra->{repos_root}) ||
5245 ($ra->{repos_root} eq $repo_id)) {
5246 $root_repos->{$ra->{url}} = $repo_id;
5247 next;
5250 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5251 my $root_path = $ra->{url};
5252 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5253 foreach my $path (keys %$fetch) {
5254 my $ref_id = $fetch->{$path};
5255 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5257 # make sure we can read when connecting to
5258 # a higher level of a repository
5259 my ($last_rev, undef) = $gs->last_rev_commit;
5260 if (!defined $last_rev) {
5261 $last_rev = eval {
5262 $root_ra->get_latest_revnum;
5264 next if $@;
5266 my $new = $root_path;
5267 $new .= length $path ? "/$path" : '';
5268 eval {
5269 $root_ra->get_log([$new], $last_rev, $last_rev,
5270 0, 0, 1, sub { });
5272 next if $@;
5273 $new_urls->{$ra->{repos_root}}->{$new} =
5274 { ref_id => $ref_id,
5275 old_repo_id => $repo_id,
5276 old_path => $path };
5280 my @emptied;
5281 foreach my $url (keys %$new_urls) {
5282 # see if we can re-use an existing [svn-remote "repo_id"]
5283 # instead of creating a(n ugly) new section:
5284 my $repo_id = $root_repos->{$url} || $url;
5286 my $fetch = $new_urls->{$url};
5287 foreach my $path (keys %$fetch) {
5288 my $x = $fetch->{$path};
5289 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5290 my $pfx = "svn-remote.$x->{old_repo_id}";
5292 my $old_fetch = quotemeta("$x->{old_path}:".
5293 "refs/remotes/$x->{ref_id}");
5294 command_noisy(qw/config --unset/,
5295 "$pfx.fetch", '^'. $old_fetch . '$');
5296 delete $r->{$x->{old_repo_id}}->
5297 {fetch}->{$x->{old_path}};
5298 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5299 command_noisy(qw/config --unset/,
5300 "$pfx.url");
5301 push @emptied, $x->{old_repo_id}
5305 if (@emptied) {
5306 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5307 print STDERR <<EOF;
5308 The following [svn-remote] sections in your config file ($file) are empty
5309 and can be safely removed:
5311 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5315 sub migration_check {
5316 migrate_from_v0();
5317 migrate_from_v1();
5318 migrate_from_v2();
5319 minimize_connections() if $_minimize;
5322 package Git::IndexInfo;
5323 use strict;
5324 use warnings;
5325 use Git qw/command_input_pipe command_close_pipe/;
5327 sub new {
5328 my ($class) = @_;
5329 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5330 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5333 sub remove {
5334 my ($self, $path) = @_;
5335 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5336 return ++$self->{nr};
5338 undef;
5341 sub update {
5342 my ($self, $mode, $hash, $path) = @_;
5343 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5344 return ++$self->{nr};
5346 undef;
5349 sub DESTROY {
5350 my ($self) = @_;
5351 command_close_pipe($self->{gui}, $self->{ctx});
5354 package Git::SVN::GlobSpec;
5355 use strict;
5356 use warnings;
5358 sub new {
5359 my ($class, $glob) = @_;
5360 my $re = $glob;
5361 $re =~ s!/+$!!g; # no need for trailing slashes
5362 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5363 my $temp = $re;
5364 my ($left, $right) = ($1, $3);
5365 $re = $2;
5366 my $depth = $re =~ tr/*/*/;
5367 if ($depth != $temp =~ tr/*/*/) {
5368 die "Only one set of wildcard directories " .
5369 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5371 if ($depth == 0) {
5372 die "One '*' is needed for glob: '$glob'\n";
5374 $re =~ s!\*!\[^/\]*!g;
5375 $re = quotemeta($left) . "($re)" . quotemeta($right);
5376 if (length $left && !($left =~ s!/+$!!g)) {
5377 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5379 if (length $right && !($right =~ s!^/+!!g)) {
5380 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5382 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5383 bless { left => $left, right => $right, left_regex => $left_re,
5384 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5387 sub full_path {
5388 my ($self, $path) = @_;
5389 return (length $self->{left} ? "$self->{left}/" : '') .
5390 $path . (length $self->{right} ? "/$self->{right}" : '');
5393 __END__
5395 Data structures:
5398 $remotes = { # returned by read_all_remotes()
5399 'svn' => {
5400 # svn-remote.svn.url=https://svn.musicpd.org
5401 url => 'https://svn.musicpd.org',
5402 # svn-remote.svn.fetch=mpd/trunk:trunk
5403 fetch => {
5404 'mpd/trunk' => 'trunk',
5406 # svn-remote.svn.tags=mpd/tags/*:tags/*
5407 tags => {
5408 path => {
5409 left => 'mpd/tags',
5410 right => '',
5411 regex => qr!mpd/tags/([^/]+)$!,
5412 glob => 'tags/*',
5414 ref => {
5415 left => 'tags',
5416 right => '',
5417 regex => qr!tags/([^/]+)$!,
5418 glob => 'tags/*',
5424 $log_entry hashref as returned by libsvn_log_entry()
5426 log => 'whitespace-formatted log entry
5427 ', # trailing newline is preserved
5428 revision => '8', # integer
5429 date => '2004-02-24T17:01:44.108345Z', # commit date
5430 author => 'committer name'
5434 # this is generated by generate_diff();
5435 @mods = array of diff-index line hashes, each element represents one line
5436 of diff-index output
5438 diff-index line ($m hash)
5440 mode_a => first column of diff-index output, no leading ':',
5441 mode_b => second column of diff-index output,
5442 sha1_b => sha1sum of the final blob,
5443 chg => change type [MCRADT],
5444 file_a => original file name of a file (iff chg is 'C' or 'R')
5445 file_b => new/current file name of a file (any chg)
5449 # retval of read_url_paths{,_all}();
5450 $l_map = {
5451 # repository root url
5452 'https://svn.musicpd.org' => {
5453 # repository path # GIT_SVN_ID
5454 'mpd/trunk' => 'trunk',
5455 'mpd/tags/0.11.5' => 'tags/0.11.5',
5459 Notes:
5460 I don't trust the each() function on unless I created %hash myself
5461 because the internal iterator may not have started at base.