add --html-path to get the location of installed HTML docs
[git/dscho.git] / git-svn.perl
blobd9197989d2e063ecf0bbbac143a046f8de79ce52
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format, $_commit_url, $_tag);
70 $Git::SVN::_follow_parent = 1;
71 $_q ||= 0;
72 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
73 'config-dir=s' => \$Git::SVN::Ra::config_dir,
74 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
75 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
76 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
77 'authors-file|A=s' => \$_authors,
78 'repack:i' => \$Git::SVN::_repack,
79 'noMetadata' => \$Git::SVN::_no_metadata,
80 'useSvmProps' => \$Git::SVN::_use_svm_props,
81 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
82 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
83 'no-checkout' => \$_no_checkout,
84 'quiet|q+' => \$_q,
85 'repack-flags|repack-args|repack-opts=s' =>
86 \$Git::SVN::_repack_flags,
87 'use-log-author' => \$Git::SVN::_use_log_author,
88 'add-author-from' => \$Git::SVN::_add_author_from,
89 'localtime' => \$Git::SVN::_localtime,
90 %remote_opts );
92 my ($_trunk, $_tags, $_branches, $_stdlayout);
93 my %icv;
94 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
95 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
96 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
97 'stdlayout|s' => \$_stdlayout,
98 'minimize-url|m' => \$Git::SVN::_minimize_url,
99 'no-metadata' => sub { $icv{noMetadata} = 1 },
100 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
101 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
102 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
103 %remote_opts );
104 my %cmt_opts = ( 'edit|e' => \$_edit,
105 'rmdir' => \$SVN::Git::Editor::_rmdir,
106 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
107 'l=i' => \$SVN::Git::Editor::_rename_limit,
108 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
111 my %cmd = (
112 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
113 { 'revision|r=s' => \$_revision,
114 'fetch-all|all' => \$_fetch_all,
115 %fc_opts } ],
116 clone => [ \&cmd_clone, "Initialize and fetch revisions",
117 { 'revision|r=s' => \$_revision,
118 %fc_opts, %init_opts } ],
119 init => [ \&cmd_init, "Initialize a repo for tracking" .
120 " (requires URL argument)",
121 \%init_opts ],
122 'multi-init' => [ \&cmd_multi_init,
123 "Deprecated alias for ".
124 "'$0 init -T<trunk> -b<branches> -t<tags>'",
125 \%init_opts ],
126 dcommit => [ \&cmd_dcommit,
127 'Commit several diffs to merge with upstream',
128 { 'merge|m|M' => \$_merge,
129 'strategy|s=s' => \$_strategy,
130 'verbose|v' => \$_verbose,
131 'dry-run|n' => \$_dry_run,
132 'fetch-all|all' => \$_fetch_all,
133 'commit-url=s' => \$_commit_url,
134 'revision|r=i' => \$_revision,
135 'no-rebase' => \$_no_rebase,
136 %cmt_opts, %fc_opts } ],
137 branch => [ \&cmd_branch,
138 'Create a branch in the SVN repository',
139 { 'message|m=s' => \$_message,
140 'dry-run|n' => \$_dry_run,
141 'tag|t' => \$_tag } ],
142 tag => [ sub { $_tag = 1; cmd_branch(@_) },
143 'Create a tag in the SVN repository',
144 { 'message|m=s' => \$_message,
145 'dry-run|n' => \$_dry_run } ],
146 'set-tree' => [ \&cmd_set_tree,
147 "Set an SVN repository to a git tree-ish",
148 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
149 'create-ignore' => [ \&cmd_create_ignore,
150 'Create a .gitignore per svn:ignore',
151 { 'revision|r=i' => \$_revision
152 } ],
153 'propget' => [ \&cmd_propget,
154 'Print the value of a property on a file or directory',
155 { 'revision|r=i' => \$_revision } ],
156 'proplist' => [ \&cmd_proplist,
157 'List all properties of a file or directory',
158 { 'revision|r=i' => \$_revision } ],
159 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
160 { 'revision|r=i' => \$_revision
161 } ],
162 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
163 { 'revision|r=i' => \$_revision
164 } ],
165 'multi-fetch' => [ \&cmd_multi_fetch,
166 "Deprecated alias for $0 fetch --all",
167 { 'revision|r=s' => \$_revision, %fc_opts } ],
168 'migrate' => [ sub { },
169 # no-op, we automatically run this anyways,
170 'Migrate configuration/metadata/layout from
171 previous versions of git-svn',
172 { 'minimize' => \$Git::SVN::Migration::_minimize,
173 %remote_opts } ],
174 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
175 { 'limit=i' => \$Git::SVN::Log::limit,
176 'revision|r=s' => \$_revision,
177 'verbose|v' => \$Git::SVN::Log::verbose,
178 'incremental' => \$Git::SVN::Log::incremental,
179 'oneline' => \$Git::SVN::Log::oneline,
180 'show-commit' => \$Git::SVN::Log::show_commit,
181 'non-recursive' => \$Git::SVN::Log::non_recursive,
182 'authors-file|A=s' => \$_authors,
183 'color' => \$Git::SVN::Log::color,
184 'pager=s' => \$Git::SVN::Log::pager
185 } ],
186 'find-rev' => [ \&cmd_find_rev,
187 "Translate between SVN revision numbers and tree-ish",
188 {} ],
189 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
190 { 'merge|m|M' => \$_merge,
191 'verbose|v' => \$_verbose,
192 'strategy|s=s' => \$_strategy,
193 'local|l' => \$_local,
194 'fetch-all|all' => \$_fetch_all,
195 'dry-run|n' => \$_dry_run,
196 %fc_opts } ],
197 'commit-diff' => [ \&cmd_commit_diff,
198 'Commit a diff between two trees',
199 { 'message|m=s' => \$_message,
200 'file|F=s' => \$_file,
201 'revision|r=s' => \$_revision,
202 %cmt_opts } ],
203 'info' => [ \&cmd_info,
204 "Show info about the latest SVN revision
205 on the current branch",
206 { 'url' => \$_url, } ],
207 'blame' => [ \&Git::SVN::Log::cmd_blame,
208 "Show what revision and author last modified each line of a file",
209 { 'git-format' => \$_git_format } ],
212 my $cmd;
213 for (my $i = 0; $i < @ARGV; $i++) {
214 if (defined $cmd{$ARGV[$i]}) {
215 $cmd = $ARGV[$i];
216 splice @ARGV, $i, 1;
217 last;
221 # make sure we're always running at the top-level working directory
222 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
223 unless (-d $ENV{GIT_DIR}) {
224 if ($git_dir_user_set) {
225 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
226 "but it is not a directory\n";
228 my $git_dir = delete $ENV{GIT_DIR};
229 my $cdup = undef;
230 git_cmd_try {
231 $cdup = command_oneline(qw/rev-parse --show-cdup/);
232 $git_dir = '.' unless ($cdup);
233 chomp $cdup if ($cdup);
234 $cdup = "." unless ($cdup && length $cdup);
235 } "Already at toplevel, but $git_dir not found\n";
236 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
237 unless (-d $git_dir) {
238 die "$git_dir still not found after going to ",
239 "'$cdup'\n";
241 $ENV{GIT_DIR} = $git_dir;
243 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
246 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
248 read_repo_config(\%opts);
249 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
250 Getopt::Long::Configure('pass_through');
252 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
253 'minimize-connections' => \$Git::SVN::Migration::_minimize,
254 'id|i=s' => \$Git::SVN::default_ref_id,
255 'svn-remote|remote|R=s' => sub {
256 $Git::SVN::no_reuse_existing = 1;
257 $Git::SVN::default_repo_id = $_[1] });
258 exit 1 if (!$rv && $cmd && $cmd ne 'log');
260 usage(0) if $_help;
261 version() if $_version;
262 usage(1) unless defined $cmd;
263 load_authors() if $_authors;
265 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
266 Git::SVN::Migration::migration_check();
268 Git::SVN::init_vars();
269 eval {
270 Git::SVN::verify_remotes_sanity();
271 $cmd{$cmd}->[0]->(@ARGV);
273 fatal $@ if $@;
274 post_fetch_checkout();
275 exit 0;
277 ####################### primary functions ######################
278 sub usage {
279 my $exit = shift || 0;
280 my $fd = $exit ? \*STDERR : \*STDOUT;
281 print $fd <<"";
282 git-svn - bidirectional operations between a single Subversion tree and git
283 Usage: git svn <command> [options] [arguments]\n
285 print $fd "Available commands:\n" unless $cmd;
287 foreach (sort keys %cmd) {
288 next if $cmd && $cmd ne $_;
289 next if /^multi-/; # don't show deprecated commands
290 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
291 foreach (sort keys %{$cmd{$_}->[2]}) {
292 # mixed-case options are for .git/config only
293 next if /[A-Z]/ && /^[a-z]+$/i;
294 # prints out arguments as they should be passed:
295 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
296 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
297 "--$_" : "-$_" }
298 split /\|/,$_)," $x\n";
301 print $fd <<"";
302 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
303 arbitrary identifier if you're tracking multiple SVN branches/repositories in
304 one git repository and want to keep them separate. See git-svn(1) for more
305 information.
307 exit $exit;
310 sub version {
311 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
312 exit 0;
315 sub do_git_init_db {
316 unless (-d $ENV{GIT_DIR}) {
317 my @init_db = ('init');
318 push @init_db, "--template=$_template" if defined $_template;
319 if (defined $_shared) {
320 if ($_shared =~ /[a-z]/) {
321 push @init_db, "--shared=$_shared";
322 } else {
323 push @init_db, "--shared";
326 command_noisy(@init_db);
327 $_repository = Git->repository(Repository => ".git");
329 my $set;
330 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
331 foreach my $i (keys %icv) {
332 die "'$set' and '$i' cannot both be set\n" if $set;
333 next unless defined $icv{$i};
334 command_noisy('config', "$pfx.$i", $icv{$i});
335 $set = $i;
339 sub init_subdir {
340 my $repo_path = shift or return;
341 mkpath([$repo_path]) unless -d $repo_path;
342 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
343 $ENV{GIT_DIR} = '.git';
344 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
347 sub cmd_clone {
348 my ($url, $path) = @_;
349 if (!defined $path &&
350 (defined $_trunk || defined $_branches || defined $_tags ||
351 defined $_stdlayout) &&
352 $url !~ m#^[a-z\+]+://#) {
353 $path = $url;
355 $path = basename($url) if !defined $path || !length $path;
356 cmd_init($url, $path);
357 Git::SVN::fetch_all($Git::SVN::default_repo_id);
360 sub cmd_init {
361 if (defined $_stdlayout) {
362 $_trunk = 'trunk' if (!defined $_trunk);
363 $_tags = 'tags' if (!defined $_tags);
364 $_branches = 'branches' if (!defined $_branches);
366 if (defined $_trunk || defined $_branches || defined $_tags) {
367 return cmd_multi_init(@_);
369 my $url = shift or die "SVN repository location required ",
370 "as a command-line argument\n";
371 init_subdir(@_);
372 do_git_init_db();
374 Git::SVN->init($url);
377 sub cmd_fetch {
378 if (grep /^\d+=./, @_) {
379 die "'<rev>=<commit>' fetch arguments are ",
380 "no longer supported.\n";
382 my ($remote) = @_;
383 if (@_ > 1) {
384 die "Usage: $0 fetch [--all] [svn-remote]\n";
386 $remote ||= $Git::SVN::default_repo_id;
387 if ($_fetch_all) {
388 cmd_multi_fetch();
389 } else {
390 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
394 sub cmd_set_tree {
395 my (@commits) = @_;
396 if ($_stdin || !@commits) {
397 print "Reading from stdin...\n";
398 @commits = ();
399 while (<STDIN>) {
400 if (/\b($sha1_short)\b/o) {
401 unshift @commits, $1;
405 my @revs;
406 foreach my $c (@commits) {
407 my @tmp = command('rev-parse',$c);
408 if (scalar @tmp == 1) {
409 push @revs, $tmp[0];
410 } elsif (scalar @tmp > 1) {
411 push @revs, reverse(command('rev-list',@tmp));
412 } else {
413 fatal "Failed to rev-parse $c";
416 my $gs = Git::SVN->new;
417 my ($r_last, $cmt_last) = $gs->last_rev_commit;
418 $gs->fetch;
419 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
420 fatal "There are new revisions that were fetched ",
421 "and need to be merged (or acknowledged) ",
422 "before committing.\nlast rev: $r_last\n",
423 " current: $gs->{last_rev}";
425 $gs->set_tree($_) foreach @revs;
426 print "Done committing ",scalar @revs," revisions to SVN\n";
427 unlink $gs->{index};
430 sub cmd_dcommit {
431 my $head = shift;
432 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
433 'Cannot dcommit with a dirty index. Commit your changes first, '
434 . "or stash them with `git stash'.\n";
435 $head ||= 'HEAD';
436 my @refs;
437 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
438 unless ($gs) {
439 die "Unable to determine upstream SVN information from ",
440 "$head history.\nPerhaps the repository is empty.";
443 if (defined $_commit_url) {
444 $url = $_commit_url;
445 } else {
446 $url = eval { command_oneline('config', '--get',
447 "svn-remote.$gs->{repo_id}.commiturl") };
448 if (!$url) {
449 $url = $gs->full_url
453 my $last_rev = $_revision if defined $_revision;
454 if ($url) {
455 print "Committing to $url ...\n";
457 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
458 if ($_no_rebase && scalar(@$linear_refs) > 1) {
459 warn "Attempting to commit more than one change while ",
460 "--no-rebase is enabled.\n",
461 "If these changes depend on each other, re-running ",
462 "without --no-rebase may be required."
464 my $expect_url = $url;
465 Git::SVN::remove_username($expect_url);
466 while (1) {
467 my $d = shift @$linear_refs or last;
468 unless (defined $last_rev) {
469 (undef, $last_rev, undef) = cmt_metadata("$d~1");
470 unless (defined $last_rev) {
471 fatal "Unable to extract revision information ",
472 "from commit $d~1";
475 if ($_dry_run) {
476 print "diff-tree $d~1 $d\n";
477 } else {
478 my $cmt_rev;
479 my %ed_opts = ( r => $last_rev,
480 log => get_commit_entry($d)->{log},
481 ra => Git::SVN::Ra->new($url),
482 config => SVN::Core::config_get_config(
483 $Git::SVN::Ra::config_dir
485 tree_a => "$d~1",
486 tree_b => $d,
487 editor_cb => sub {
488 print "Committed r$_[0]\n";
489 $cmt_rev = $_[0];
491 svn_path => '');
492 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
493 print "No changes\n$d~1 == $d\n";
494 } elsif ($parents->{$d} && @{$parents->{$d}}) {
495 $gs->{inject_parents_dcommit}->{$cmt_rev} =
496 $parents->{$d};
498 $_fetch_all ? $gs->fetch_all : $gs->fetch;
499 $last_rev = $cmt_rev;
500 next if $_no_rebase;
502 # we always want to rebase against the current HEAD,
503 # not any head that was passed to us
504 my @diff = command('diff-tree', $d,
505 $gs->refname, '--');
506 my @finish;
507 if (@diff) {
508 @finish = rebase_cmd();
509 print STDERR "W: $d and ", $gs->refname,
510 " differ, using @finish:\n",
511 join("\n", @diff), "\n";
512 } else {
513 print "No changes between current HEAD and ",
514 $gs->refname,
515 "\nResetting to the latest ",
516 $gs->refname, "\n";
517 @finish = qw/reset --mixed/;
519 command_noisy(@finish, $gs->refname);
520 if (@diff) {
521 @refs = ();
522 my ($url_, $rev_, $uuid_, $gs_) =
523 working_head_info($head, \@refs);
524 my ($linear_refs_, $parents_) =
525 linearize_history($gs_, \@refs);
526 if (scalar(@$linear_refs) !=
527 scalar(@$linear_refs_)) {
528 fatal "# of revisions changed ",
529 "\nbefore:\n",
530 join("\n", @$linear_refs),
531 "\n\nafter:\n",
532 join("\n", @$linear_refs_), "\n",
533 'If you are attempting to commit ',
534 "merges, try running:\n\t",
535 'git rebase --interactive',
536 '--preserve-merges ',
537 $gs->refname,
538 "\nBefore dcommitting";
540 if ($url_ ne $expect_url) {
541 fatal "URL mismatch after rebase: ",
542 "$url_ != $expect_url";
544 if ($uuid_ ne $uuid) {
545 fatal "uuid mismatch after rebase: ",
546 "$uuid_ != $uuid";
548 # remap parents
549 my (%p, @l, $i);
550 for ($i = 0; $i < scalar @$linear_refs; $i++) {
551 my $new = $linear_refs_->[$i] or next;
552 $p{$new} =
553 $parents->{$linear_refs->[$i]};
554 push @l, $new;
556 $parents = \%p;
557 $linear_refs = \@l;
561 unlink $gs->{index};
564 sub cmd_branch {
565 my ($branch_name, $head) = @_;
567 unless (defined $branch_name && length $branch_name) {
568 die(($_tag ? "tag" : "branch") . " name required\n");
570 $head ||= 'HEAD';
572 my ($src, $rev, undef, $gs) = working_head_info($head);
574 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
575 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
576 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
577 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
579 my $ctx = SVN::Client->new(
580 auth => Git::SVN::Ra::_auth_providers(),
581 log_msg => sub {
582 ${ $_[0] } = defined $_message
583 ? $_message
584 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
585 . $branch_name;
589 eval {
590 $ctx->ls($dst, 'HEAD', 0);
591 } and die "branch ${branch_name} already exists\n";
593 print "Copying ${src} at r${rev} to ${dst}...\n";
594 $ctx->copy($src, $rev, $dst)
595 unless $_dry_run;
597 $gs->fetch_all;
600 sub cmd_find_rev {
601 my $revision_or_hash = shift or die "SVN or git revision required ",
602 "as a command-line argument\n";
603 my $result;
604 if ($revision_or_hash =~ /^r\d+$/) {
605 my $head = shift;
606 $head ||= 'HEAD';
607 my @refs;
608 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
609 unless ($gs) {
610 die "Unable to determine upstream SVN information from ",
611 "$head history\n";
613 my $desired_revision = substr($revision_or_hash, 1);
614 $result = $gs->rev_map_get($desired_revision, $uuid);
615 } else {
616 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
617 $result = $rev;
619 print "$result\n" if $result;
622 sub cmd_rebase {
623 command_noisy(qw/update-index --refresh/);
624 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
625 unless ($gs) {
626 die "Unable to determine upstream SVN information from ",
627 "working tree history\n";
629 if ($_dry_run) {
630 print "Remote Branch: " . $gs->refname . "\n";
631 print "SVN URL: " . $url . "\n";
632 return;
634 if (command(qw/diff-index HEAD --/)) {
635 print STDERR "Cannot rebase with uncommited changes:\n";
636 command_noisy('status');
637 exit 1;
639 unless ($_local) {
640 # rebase will checkout for us, so no need to do it explicitly
641 $_no_checkout = 'true';
642 $_fetch_all ? $gs->fetch_all : $gs->fetch;
644 command_noisy(rebase_cmd(), $gs->refname);
647 sub cmd_show_ignore {
648 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
649 $gs ||= Git::SVN->new;
650 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
651 $gs->prop_walk($gs->{path}, $r, sub {
652 my ($gs, $path, $props) = @_;
653 print STDOUT "\n# $path\n";
654 my $s = $props->{'svn:ignore'} or return;
655 $s =~ s/[\r\n]+/\n/g;
656 chomp $s;
657 $s =~ s#^#$path#gm;
658 print STDOUT "$s\n";
662 sub cmd_show_externals {
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:externals'} 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_create_ignore {
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 # $path is of the form /path/to/dir/
684 $path = '.' . $path;
685 # SVN can have attributes on empty directories,
686 # which git won't track
687 mkpath([$path]) unless -d $path;
688 my $ignore = $path . '.gitignore';
689 my $s = $props->{'svn:ignore'} or return;
690 open(GITIGNORE, '>', $ignore)
691 or fatal("Failed to open `$ignore' for writing: $!");
692 $s =~ s/[\r\n]+/\n/g;
693 chomp $s;
694 # Prefix all patterns so that the ignore doesn't apply
695 # to sub-directories.
696 $s =~ s#^#/#gm;
697 print GITIGNORE "$s\n";
698 close(GITIGNORE)
699 or fatal("Failed to close `$ignore': $!");
700 command_noisy('add', '-f', $ignore);
704 sub canonicalize_path {
705 my ($path) = @_;
706 my $dot_slash_added = 0;
707 if (substr($path, 0, 1) ne "/") {
708 $path = "./" . $path;
709 $dot_slash_added = 1;
711 # File::Spec->canonpath doesn't collapse x/../y into y (for a
712 # good reason), so let's do this manually.
713 $path =~ s#/+#/#g;
714 $path =~ s#/\.(?:/|$)#/#g;
715 $path =~ s#/[^/]+/\.\.##g;
716 $path =~ s#/$##g;
717 $path =~ s#^\./## if $dot_slash_added;
718 $path =~ s#^/##;
719 $path =~ s#^\.$##;
720 return $path;
723 # get_svnprops(PATH)
724 # ------------------
725 # Helper for cmd_propget and cmd_proplist below.
726 sub get_svnprops {
727 my $path = shift;
728 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
729 $gs ||= Git::SVN->new;
731 # prefix THE PATH by the sub-directory from which the user
732 # invoked us.
733 $path = $cmd_dir_prefix . $path;
734 fatal("No such file or directory: $path") unless -e $path;
735 my $is_dir = -d $path ? 1 : 0;
736 $path = $gs->{path} . '/' . $path;
738 # canonicalize the path (otherwise libsvn will abort or fail to
739 # find the file)
740 $path = canonicalize_path($path);
742 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
743 my $props;
744 if ($is_dir) {
745 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
747 else {
748 (undef, $props) = $gs->ra->get_file($path, $r, undef);
750 return $props;
753 # cmd_propget (PROP, PATH)
754 # ------------------------
755 # Print the SVN property PROP for PATH.
756 sub cmd_propget {
757 my ($prop, $path) = @_;
758 $path = '.' if not defined $path;
759 usage(1) if not defined $prop;
760 my $props = get_svnprops($path);
761 if (not defined $props->{$prop}) {
762 fatal("`$path' does not have a `$prop' SVN property.");
764 print $props->{$prop} . "\n";
767 # cmd_proplist (PATH)
768 # -------------------
769 # Print the list of SVN properties for PATH.
770 sub cmd_proplist {
771 my $path = shift;
772 $path = '.' if not defined $path;
773 my $props = get_svnprops($path);
774 print "Properties on '$path':\n";
775 foreach (sort keys %{$props}) {
776 print " $_\n";
780 sub cmd_multi_init {
781 my $url = shift;
782 unless (defined $_trunk || defined $_branches || defined $_tags) {
783 usage(1);
786 # there are currently some bugs that prevent multi-init/multi-fetch
787 # setups from working well without this.
788 $Git::SVN::_minimize_url = 1;
790 $_prefix = '' unless defined $_prefix;
791 if (defined $url) {
792 $url =~ s#/+$##;
793 init_subdir(@_);
795 do_git_init_db();
796 if (defined $_trunk) {
797 my $trunk_ref = $_prefix . 'trunk';
798 # try both old-style and new-style lookups:
799 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
800 unless ($gs_trunk) {
801 my ($trunk_url, $trunk_path) =
802 complete_svn_url($url, $_trunk);
803 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
804 undef, $trunk_ref);
807 return unless defined $_branches || defined $_tags;
808 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
809 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
810 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
813 sub cmd_multi_fetch {
814 my $remotes = Git::SVN::read_all_remotes();
815 foreach my $repo_id (sort keys %$remotes) {
816 if ($remotes->{$repo_id}->{url}) {
817 Git::SVN::fetch_all($repo_id, $remotes);
822 # this command is special because it requires no metadata
823 sub cmd_commit_diff {
824 my ($ta, $tb, $url) = @_;
825 my $usage = "Usage: $0 commit-diff -r<revision> ".
826 "<tree-ish> <tree-ish> [<URL>]";
827 fatal($usage) if (!defined $ta || !defined $tb);
828 my $svn_path = '';
829 if (!defined $url) {
830 my $gs = eval { Git::SVN->new };
831 if (!$gs) {
832 fatal("Needed URL or usable git-svn --id in ",
833 "the command-line\n", $usage);
835 $url = $gs->{url};
836 $svn_path = $gs->{path};
838 unless (defined $_revision) {
839 fatal("-r|--revision is a required argument\n", $usage);
841 if (defined $_message && defined $_file) {
842 fatal("Both --message/-m and --file/-F specified ",
843 "for the commit message.\n",
844 "I have no idea what you mean");
846 if (defined $_file) {
847 $_message = file_to_s($_file);
848 } else {
849 $_message ||= get_commit_entry($tb)->{log};
851 my $ra ||= Git::SVN::Ra->new($url);
852 my $r = $_revision;
853 if ($r eq 'HEAD') {
854 $r = $ra->get_latest_revnum;
855 } elsif ($r !~ /^\d+$/) {
856 die "revision argument: $r not understood by git-svn\n";
858 my %ed_opts = ( r => $r,
859 log => $_message,
860 ra => $ra,
861 tree_a => $ta,
862 tree_b => $tb,
863 editor_cb => sub { print "Committed r$_[0]\n" },
864 svn_path => $svn_path );
865 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
866 print "No changes\n$ta == $tb\n";
870 sub escape_uri_only {
871 my ($uri) = @_;
872 my @tmp;
873 foreach (split m{/}, $uri) {
874 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
875 push @tmp, $_;
877 join('/', @tmp);
880 sub escape_url {
881 my ($url) = @_;
882 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
883 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
884 $url = "$scheme://$domain$uri";
886 $url;
889 sub cmd_info {
890 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
891 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
892 if (exists $_[1]) {
893 die "Too many arguments specified\n";
896 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
898 if (!$file_type && !$diff_status) {
899 print STDERR "svn: '$path' is not under version control\n";
900 exit 1;
903 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
904 unless ($gs) {
905 die "Unable to determine upstream SVN information from ",
906 "working tree history\n";
909 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
910 $path = "." if $path eq "";
912 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
914 if ($_url) {
915 print escape_url($full_url), "\n";
916 return;
919 my $result = "Path: $path\n";
920 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
921 $result .= "URL: " . escape_url($full_url) . "\n";
923 eval {
924 my $repos_root = $gs->repos_root;
925 Git::SVN::remove_username($repos_root);
926 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
928 if ($@) {
929 $result .= "Repository Root: (offline)\n";
931 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
932 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
933 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
935 $result .= "Node Kind: " .
936 ($file_type eq "dir" ? "directory" : "file") . "\n";
938 my $schedule = $diff_status eq "A"
939 ? "add"
940 : ($diff_status eq "D" ? "delete" : "normal");
941 $result .= "Schedule: $schedule\n";
943 if ($diff_status eq "A") {
944 print $result, "\n";
945 return;
948 my ($lc_author, $lc_rev, $lc_date_utc);
949 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
950 my $log = command_output_pipe(@args);
951 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
952 while (<$log>) {
953 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
954 $lc_author = $1;
955 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
956 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
957 (undef, $lc_rev, undef) = ::extract_metadata($1);
960 close $log;
962 Git::SVN::Log::set_local_timezone();
964 $result .= "Last Changed Author: $lc_author\n";
965 $result .= "Last Changed Rev: $lc_rev\n";
966 $result .= "Last Changed Date: " .
967 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
969 if ($file_type ne "dir") {
970 my $text_last_updated_date =
971 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
972 $result .=
973 "Text Last Updated: " .
974 Git::SVN::Log::format_svn_date($text_last_updated_date) .
975 "\n";
976 my $checksum;
977 if ($diff_status eq "D") {
978 my ($fh, $ctx) =
979 command_output_pipe(qw(cat-file blob), "HEAD:$path");
980 if ($file_type eq "link") {
981 my $file_name = <$fh>;
982 $checksum = md5sum("link $file_name");
983 } else {
984 $checksum = md5sum($fh);
986 command_close_pipe($fh, $ctx);
987 } elsif ($file_type eq "link") {
988 my $file_name =
989 command(qw(cat-file blob), "HEAD:$path");
990 $checksum =
991 md5sum("link " . $file_name);
992 } else {
993 open FILE, "<", $path or die $!;
994 $checksum = md5sum(\*FILE);
995 close FILE or die $!;
997 $result .= "Checksum: " . $checksum . "\n";
1000 print $result, "\n";
1003 ########################### utility functions #########################
1005 sub rebase_cmd {
1006 my @cmd = qw/rebase/;
1007 push @cmd, '-v' if $_verbose;
1008 push @cmd, qw/--merge/ if $_merge;
1009 push @cmd, "--strategy=$_strategy" if $_strategy;
1010 @cmd;
1013 sub post_fetch_checkout {
1014 return if $_no_checkout;
1015 my $gs = $Git::SVN::_head or return;
1016 return if verify_ref('refs/heads/master^0');
1018 my $valid_head = verify_ref('HEAD^0');
1019 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1020 return if ($valid_head || !verify_ref('HEAD^0'));
1022 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1023 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1024 return if -f $index;
1026 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1027 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1028 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1029 print STDERR "Checked out HEAD:\n ",
1030 $gs->full_url, " r", $gs->last_rev, "\n";
1033 sub complete_svn_url {
1034 my ($url, $path) = @_;
1035 $path =~ s#/+$##;
1036 if ($path !~ m#^[a-z\+]+://#) {
1037 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1038 fatal("E: '$path' is not a complete URL ",
1039 "and a separate URL is not specified");
1041 return ($url, $path);
1043 return ($path, '');
1046 sub complete_url_ls_init {
1047 my ($ra, $repo_path, $switch, $pfx) = @_;
1048 unless ($repo_path) {
1049 print STDERR "W: $switch not specified\n";
1050 return;
1052 $repo_path =~ s#/+$##;
1053 if ($repo_path =~ m#^[a-z\+]+://#) {
1054 $ra = Git::SVN::Ra->new($repo_path);
1055 $repo_path = '';
1056 } else {
1057 $repo_path =~ s#^/+##;
1058 unless ($ra) {
1059 fatal("E: '$repo_path' is not a complete URL ",
1060 "and a separate URL is not specified");
1063 my $url = $ra->{url};
1064 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1065 my $k = "svn-remote.$gs->{repo_id}.url";
1066 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1067 if ($orig_url && ($orig_url ne $gs->{url})) {
1068 die "$k already set: $orig_url\n",
1069 "wanted to set to: $gs->{url}\n";
1071 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1072 my $remote_path = "$ra->{svn_path}/$repo_path";
1073 $remote_path =~ s#/+#/#g;
1074 $remote_path =~ s#^/##g;
1075 $remote_path .= "/*" if $remote_path !~ /\*/;
1076 my ($n) = ($switch =~ /^--(\w+)/);
1077 if (length $pfx && $pfx !~ m#/$#) {
1078 die "--prefix='$pfx' must have a trailing slash '/'\n";
1080 command_noisy('config',
1081 "svn-remote.$gs->{repo_id}.$n",
1082 "$remote_path:refs/remotes/$pfx*" .
1083 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1086 sub verify_ref {
1087 my ($ref) = @_;
1088 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1089 { STDERR => 0 }); };
1092 sub get_tree_from_treeish {
1093 my ($treeish) = @_;
1094 # $treeish can be a symbolic ref, too:
1095 my $type = command_oneline(qw/cat-file -t/, $treeish);
1096 my $expected;
1097 while ($type eq 'tag') {
1098 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1100 if ($type eq 'commit') {
1101 $expected = (grep /^tree /, command(qw/cat-file commit/,
1102 $treeish))[0];
1103 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1104 die "Unable to get tree from $treeish\n" unless $expected;
1105 } elsif ($type eq 'tree') {
1106 $expected = $treeish;
1107 } else {
1108 die "$treeish is a $type, expected tree, tag or commit\n";
1110 return $expected;
1113 sub get_commit_entry {
1114 my ($treeish) = shift;
1115 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1116 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1117 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1118 open my $log_fh, '>', $commit_editmsg or croak $!;
1120 my $type = command_oneline(qw/cat-file -t/, $treeish);
1121 if ($type eq 'commit' || $type eq 'tag') {
1122 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1123 $type, $treeish);
1124 my $in_msg = 0;
1125 my $author;
1126 my $saw_from = 0;
1127 my $msgbuf = "";
1128 while (<$msg_fh>) {
1129 if (!$in_msg) {
1130 $in_msg = 1 if (/^\s*$/);
1131 $author = $1 if (/^author (.*>)/);
1132 } elsif (/^git-svn-id: /) {
1133 # skip this for now, we regenerate the
1134 # correct one on re-fetch anyways
1135 # TODO: set *:merge properties or like...
1136 } else {
1137 if (/^From:/ || /^Signed-off-by:/) {
1138 $saw_from = 1;
1140 $msgbuf .= $_;
1143 $msgbuf =~ s/\s+$//s;
1144 if ($Git::SVN::_add_author_from && defined($author)
1145 && !$saw_from) {
1146 $msgbuf .= "\n\nFrom: $author";
1148 print $log_fh $msgbuf or croak $!;
1149 command_close_pipe($msg_fh, $ctx);
1151 close $log_fh or croak $!;
1153 if ($_edit || ($type eq 'tree')) {
1154 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1155 # TODO: strip out spaces, comments, like git-commit.sh
1156 system($editor, $commit_editmsg);
1158 rename $commit_editmsg, $commit_msg or croak $!;
1160 # SVN requires messages to be UTF-8 when entering the repo
1161 local $/;
1162 open $log_fh, '<', $commit_msg or croak $!;
1163 binmode $log_fh;
1164 chomp($log_entry{log} = <$log_fh>);
1166 if (my $enc = Git::config('i18n.commitencoding')) {
1167 require Encode;
1168 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1170 close $log_fh or croak $!;
1172 unlink $commit_msg;
1173 \%log_entry;
1176 sub s_to_file {
1177 my ($str, $file, $mode) = @_;
1178 open my $fd,'>',$file or croak $!;
1179 print $fd $str,"\n" or croak $!;
1180 close $fd or croak $!;
1181 chmod ($mode &~ umask, $file) if (defined $mode);
1184 sub file_to_s {
1185 my $file = shift;
1186 open my $fd,'<',$file or croak "$!: file: $file\n";
1187 local $/;
1188 my $ret = <$fd>;
1189 close $fd or croak $!;
1190 $ret =~ s/\s*$//s;
1191 return $ret;
1194 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1195 sub load_authors {
1196 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1197 my $log = $cmd eq 'log';
1198 while (<$authors>) {
1199 chomp;
1200 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1201 my ($user, $name, $email) = ($1, $2, $3);
1202 if ($log) {
1203 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1204 } else {
1205 $users{$user} = [$name, $email];
1208 close $authors or croak $!;
1211 # convert GetOpt::Long specs for use by git-config
1212 sub read_repo_config {
1213 return unless -d $ENV{GIT_DIR};
1214 my $opts = shift;
1215 my @config_only;
1216 foreach my $o (keys %$opts) {
1217 # if we have mixedCase and a long option-only, then
1218 # it's a config-only variable that we don't need for
1219 # the command-line.
1220 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1221 my $v = $opts->{$o};
1222 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1223 $key =~ s/-//g;
1224 my $arg = 'git config';
1225 $arg .= ' --int' if ($o =~ /[:=]i$/);
1226 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1227 if (ref $v eq 'ARRAY') {
1228 chomp(my @tmp = `$arg --get-all svn.$key`);
1229 @$v = @tmp if @tmp;
1230 } else {
1231 chomp(my $tmp = `$arg --get svn.$key`);
1232 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1233 $$v = $tmp;
1237 delete @$opts{@config_only} if @config_only;
1240 sub extract_metadata {
1241 my $id = shift or return (undef, undef, undef);
1242 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1243 \s([a-f\d\-]+)$/x);
1244 if (!defined $rev || !$uuid || !$url) {
1245 # some of the original repositories I made had
1246 # identifiers like this:
1247 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1249 return ($url, $rev, $uuid);
1252 sub cmt_metadata {
1253 return extract_metadata((grep(/^git-svn-id: /,
1254 command(qw/cat-file commit/, shift)))[-1]);
1257 sub working_head_info {
1258 my ($head, $refs) = @_;
1259 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1260 my ($fh, $ctx) = command_output_pipe(@args, $head);
1261 my $hash;
1262 my %max;
1263 while (<$fh>) {
1264 if ( m{^commit ($::sha1)$} ) {
1265 unshift @$refs, $hash if $hash and $refs;
1266 $hash = $1;
1267 next;
1269 next unless s{^\s*(git-svn-id:)}{$1};
1270 my ($url, $rev, $uuid) = extract_metadata($_);
1271 if (defined $url && defined $rev) {
1272 next if $max{$url} and $max{$url} < $rev;
1273 if (my $gs = Git::SVN->find_by_url($url)) {
1274 my $c = $gs->rev_map_get($rev, $uuid);
1275 if ($c && $c eq $hash) {
1276 close $fh; # break the pipe
1277 return ($url, $rev, $uuid, $gs);
1278 } else {
1279 $max{$url} ||= $gs->rev_map_max;
1284 command_close_pipe($fh, $ctx);
1285 (undef, undef, undef, undef);
1288 sub read_commit_parents {
1289 my ($parents, $c) = @_;
1290 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1291 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1292 @{$parents->{$c}} = split(/ /, $p);
1295 sub linearize_history {
1296 my ($gs, $refs) = @_;
1297 my %parents;
1298 foreach my $c (@$refs) {
1299 read_commit_parents(\%parents, $c);
1302 my @linear_refs;
1303 my %skip = ();
1304 my $last_svn_commit = $gs->last_commit;
1305 foreach my $c (reverse @$refs) {
1306 next if $c eq $last_svn_commit;
1307 last if $skip{$c};
1309 unshift @linear_refs, $c;
1310 $skip{$c} = 1;
1312 # we only want the first parent to diff against for linear
1313 # history, we save the rest to inject when we finalize the
1314 # svn commit
1315 my $fp_a = verify_ref("$c~1");
1316 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1317 if (!$fp_a || !$fp_b) {
1318 die "Commit $c\n",
1319 "has no parent commit, and therefore ",
1320 "nothing to diff against.\n",
1321 "You should be working from a repository ",
1322 "originally created by git-svn\n";
1324 if ($fp_a ne $fp_b) {
1325 die "$c~1 = $fp_a, however parsing commit $c ",
1326 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1329 foreach my $p (@{$parents{$c}}) {
1330 $skip{$p} = 1;
1333 (\@linear_refs, \%parents);
1336 sub find_file_type_and_diff_status {
1337 my ($path) = @_;
1338 return ('dir', '') if $path eq '';
1340 my $diff_output =
1341 command_oneline(qw(diff --cached --name-status --), $path) || "";
1342 my $diff_status = (split(' ', $diff_output))[0] || "";
1344 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1346 return (undef, undef) if !$diff_status && !$ls_tree;
1348 if ($diff_status eq "A") {
1349 return ("link", $diff_status) if -l $path;
1350 return ("dir", $diff_status) if -d $path;
1351 return ("file", $diff_status);
1354 my $mode = (split(' ', $ls_tree))[0] || "";
1356 return ("link", $diff_status) if $mode eq "120000";
1357 return ("dir", $diff_status) if $mode eq "040000";
1358 return ("file", $diff_status);
1361 sub md5sum {
1362 my $arg = shift;
1363 my $ref = ref $arg;
1364 my $md5 = Digest::MD5->new();
1365 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1366 $md5->addfile($arg) or croak $!;
1367 } elsif ($ref eq 'SCALAR') {
1368 $md5->add($$arg) or croak $!;
1369 } elsif (!$ref) {
1370 $md5->add($arg) or croak $!;
1371 } else {
1372 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1374 return $md5->hexdigest();
1377 package Git::SVN;
1378 use strict;
1379 use warnings;
1380 use Fcntl qw/:DEFAULT :seek/;
1381 use constant rev_map_fmt => 'NH40';
1382 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1383 $_repack $_repack_flags $_use_svm_props $_head
1384 $_use_svnsync_props $no_reuse_existing $_minimize_url
1385 $_use_log_author $_add_author_from $_localtime/;
1386 use Carp qw/croak/;
1387 use File::Path qw/mkpath/;
1388 use File::Copy qw/copy/;
1389 use IPC::Open3;
1391 my ($_gc_nr, $_gc_period);
1393 # properties that we do not log:
1394 my %SKIP_PROP;
1395 BEGIN {
1396 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1397 svn:special svn:executable
1398 svn:entry:committed-rev
1399 svn:entry:last-author
1400 svn:entry:uuid
1401 svn:entry:committed-date/;
1403 # some options are read globally, but can be overridden locally
1404 # per [svn-remote "..."] section. Command-line options will *NOT*
1405 # override options set in an [svn-remote "..."] section
1406 no strict 'refs';
1407 for my $option (qw/follow_parent no_metadata use_svm_props
1408 use_svnsync_props/) {
1409 my $key = $option;
1410 $key =~ tr/_//d;
1411 my $prop = "-$option";
1412 *$option = sub {
1413 my ($self) = @_;
1414 return $self->{$prop} if exists $self->{$prop};
1415 my $k = "svn-remote.$self->{repo_id}.$key";
1416 eval { command_oneline(qw/config --get/, $k) };
1417 if ($@) {
1418 $self->{$prop} = ${"Git::SVN::_$option"};
1419 } else {
1420 my $v = command_oneline(qw/config --bool/,$k);
1421 $self->{$prop} = $v eq 'false' ? 0 : 1;
1423 return $self->{$prop};
1429 my (%LOCKFILES, %INDEX_FILES);
1430 END {
1431 unlink keys %LOCKFILES if %LOCKFILES;
1432 unlink keys %INDEX_FILES if %INDEX_FILES;
1435 sub resolve_local_globs {
1436 my ($url, $fetch, $glob_spec) = @_;
1437 return unless defined $glob_spec;
1438 my $ref = $glob_spec->{ref};
1439 my $path = $glob_spec->{path};
1440 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1441 next unless m#^refs/remotes/$ref->{regex}$#;
1442 my $p = $1;
1443 my $pathname = desanitize_refname($path->full_path($p));
1444 my $refname = desanitize_refname($ref->full_path($p));
1445 if (my $existing = $fetch->{$pathname}) {
1446 if ($existing ne $refname) {
1447 die "Refspec conflict:\n",
1448 "existing: refs/remotes/$existing\n",
1449 " globbed: refs/remotes/$refname\n";
1451 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1452 $u =~ s!^\Q$url\E(/|$)!! or die
1453 "refs/remotes/$refname: '$url' not found in '$u'\n";
1454 if ($pathname ne $u) {
1455 warn "W: Refspec glob conflict ",
1456 "(ref: refs/remotes/$refname):\n",
1457 "expected path: $pathname\n",
1458 " real path: $u\n",
1459 "Continuing ahead with $u\n";
1460 next;
1462 } else {
1463 $fetch->{$pathname} = $refname;
1468 sub parse_revision_argument {
1469 my ($base, $head) = @_;
1470 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1471 return ($base, $head);
1473 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1474 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1475 return ($head, $head) if ($::_revision eq 'HEAD');
1476 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1477 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1478 die "revision argument: $::_revision not understood by git-svn\n";
1481 sub fetch_all {
1482 my ($repo_id, $remotes) = @_;
1483 if (ref $repo_id) {
1484 my $gs = $repo_id;
1485 $repo_id = undef;
1486 $repo_id = $gs->{repo_id};
1488 $remotes ||= read_all_remotes();
1489 my $remote = $remotes->{$repo_id} or
1490 die "[svn-remote \"$repo_id\"] unknown\n";
1491 my $fetch = $remote->{fetch};
1492 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1493 my (@gs, @globs);
1494 my $ra = Git::SVN::Ra->new($url);
1495 my $uuid = $ra->get_uuid;
1496 my $head = $ra->get_latest_revnum;
1497 my $base = defined $fetch ? $head : 0;
1499 # read the max revs for wildcard expansion (branches/*, tags/*)
1500 foreach my $t (qw/branches tags/) {
1501 defined $remote->{$t} or next;
1502 push @globs, $remote->{$t};
1503 my $max_rev = eval { tmp_config(qw/--int --get/,
1504 "svn-remote.$repo_id.${t}-maxRev") };
1505 if (defined $max_rev && ($max_rev < $base)) {
1506 $base = $max_rev;
1507 } elsif (!defined $max_rev) {
1508 $base = 0;
1512 if ($fetch) {
1513 foreach my $p (sort keys %$fetch) {
1514 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1515 my $lr = $gs->rev_map_max;
1516 if (defined $lr) {
1517 $base = $lr if ($lr < $base);
1519 push @gs, $gs;
1523 ($base, $head) = parse_revision_argument($base, $head);
1524 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1527 sub read_all_remotes {
1528 my $r = {};
1529 my $use_svm_props = eval { command_oneline(qw/config --bool
1530 svn.useSvmProps/) };
1531 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1532 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1533 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1534 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1535 die("svn-remote.$remote: remote ref '$_remote_ref' "
1536 . "must start with 'refs/remotes/'\n")
1537 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1538 my $remote_ref = $1;
1539 $local_ref =~ s{^/}{};
1540 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1541 $r->{$remote}->{svm} = {} if $use_svm_props;
1542 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1543 $r->{$1}->{svm} = {};
1544 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1545 $r->{$1}->{url} = $2;
1546 } elsif (m!^(.+)\.(branches|tags)=
1547 (.*):refs/remotes/(.+)\s*$/!x) {
1548 my ($p, $g) = ($3, $4);
1549 my $rs = $r->{$1}->{$2} = {
1550 t => $2,
1551 remote => $1,
1552 path => Git::SVN::GlobSpec->new($p),
1553 ref => Git::SVN::GlobSpec->new($g) };
1554 if (length($rs->{ref}->{right}) != 0) {
1555 die "The '*' glob character must be the last ",
1556 "character of '$g'\n";
1561 map {
1562 if (defined $r->{$_}->{svm}) {
1563 my $svm;
1564 eval {
1565 my $section = "svn-remote.$_";
1566 $svm = {
1567 source => tmp_config('--get',
1568 "$section.svm-source"),
1569 replace => tmp_config('--get',
1570 "$section.svm-replace"),
1573 $r->{$_}->{svm} = $svm;
1575 } keys %$r;
1580 sub init_vars {
1581 $_gc_nr = $_gc_period = 1000;
1582 if (defined $_repack || defined $_repack_flags) {
1583 warn "Repack options are obsolete; they have no effect.\n";
1587 sub verify_remotes_sanity {
1588 return unless -d $ENV{GIT_DIR};
1589 my %seen;
1590 foreach (command(qw/config -l/)) {
1591 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1592 if ($seen{$1}) {
1593 die "Remote ref refs/remote/$1 is tracked by",
1594 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1595 "Please resolve this ambiguity in ",
1596 "your git configuration file before ",
1597 "continuing\n";
1599 $seen{$1} = $_;
1604 sub find_existing_remote {
1605 my ($url, $remotes) = @_;
1606 return undef if $no_reuse_existing;
1607 my $existing;
1608 foreach my $repo_id (keys %$remotes) {
1609 my $u = $remotes->{$repo_id}->{url} or next;
1610 next if $u ne $url;
1611 $existing = $repo_id;
1612 last;
1614 $existing;
1617 sub init_remote_config {
1618 my ($self, $url, $no_write) = @_;
1619 $url =~ s!/+$!!; # strip trailing slash
1620 my $r = read_all_remotes();
1621 my $existing = find_existing_remote($url, $r);
1622 if ($existing) {
1623 unless ($no_write) {
1624 print STDERR "Using existing ",
1625 "[svn-remote \"$existing\"]\n";
1627 $self->{repo_id} = $existing;
1628 } elsif ($_minimize_url) {
1629 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1630 $existing = find_existing_remote($min_url, $r);
1631 if ($existing) {
1632 unless ($no_write) {
1633 print STDERR "Using existing ",
1634 "[svn-remote \"$existing\"]\n";
1636 $self->{repo_id} = $existing;
1638 if ($min_url ne $url) {
1639 unless ($no_write) {
1640 print STDERR "Using higher level of URL: ",
1641 "$url => $min_url\n";
1643 my $old_path = $self->{path};
1644 $self->{path} = $url;
1645 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1646 if (length $old_path) {
1647 $self->{path} .= "/$old_path";
1649 $url = $min_url;
1652 my $orig_url;
1653 if (!$existing) {
1654 # verify that we aren't overwriting anything:
1655 $orig_url = eval {
1656 command_oneline('config', '--get',
1657 "svn-remote.$self->{repo_id}.url")
1659 if ($orig_url && ($orig_url ne $url)) {
1660 die "svn-remote.$self->{repo_id}.url already set: ",
1661 "$orig_url\nwanted to set to: $url\n";
1664 my ($xrepo_id, $xpath) = find_ref($self->refname);
1665 if (defined $xpath) {
1666 die "svn-remote.$xrepo_id.fetch already set to track ",
1667 "$xpath:refs/remotes/", $self->refname, "\n";
1669 unless ($no_write) {
1670 command_noisy('config',
1671 "svn-remote.$self->{repo_id}.url", $url);
1672 $self->{path} =~ s{^/}{};
1673 command_noisy('config', '--add',
1674 "svn-remote.$self->{repo_id}.fetch",
1675 "$self->{path}:".$self->refname);
1677 $self->{url} = $url;
1680 sub find_by_url { # repos_root and, path are optional
1681 my ($class, $full_url, $repos_root, $path) = @_;
1683 return undef unless defined $full_url;
1684 remove_username($full_url);
1685 remove_username($repos_root) if defined $repos_root;
1686 my $remotes = read_all_remotes();
1687 if (defined $full_url && defined $repos_root && !defined $path) {
1688 $path = $full_url;
1689 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1691 foreach my $repo_id (keys %$remotes) {
1692 my $u = $remotes->{$repo_id}->{url} or next;
1693 remove_username($u);
1694 next if defined $repos_root && $repos_root ne $u;
1696 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1697 foreach (qw/branches tags/) {
1698 resolve_local_globs($u, $fetch,
1699 $remotes->{$repo_id}->{$_});
1701 my $p = $path;
1702 my $rwr = rewrite_root({repo_id => $repo_id});
1703 my $svm = $remotes->{$repo_id}->{svm}
1704 if defined $remotes->{$repo_id}->{svm};
1705 unless (defined $p) {
1706 $p = $full_url;
1707 my $z = $u;
1708 my $prefix = '';
1709 if ($rwr) {
1710 $z = $rwr;
1711 remove_username($z);
1712 } elsif (defined $svm) {
1713 $z = $svm->{source};
1714 $prefix = $svm->{replace};
1715 $prefix =~ s#^\Q$u\E(?:/|$)##;
1716 $prefix =~ s#/$##;
1718 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1720 foreach my $f (keys %$fetch) {
1721 next if $f ne $p;
1722 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1725 undef;
1728 sub init {
1729 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1730 my $self = _new($class, $repo_id, $ref_id, $path);
1731 if (defined $url) {
1732 $self->init_remote_config($url, $no_write);
1734 $self;
1737 sub find_ref {
1738 my ($ref_id) = @_;
1739 foreach (command(qw/config -l/)) {
1740 next unless m!^svn-remote\.(.+)\.fetch=
1741 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1742 my ($repo_id, $path, $ref) = ($1, $2, $3);
1743 if ($ref eq $ref_id) {
1744 $path = '' if ($path =~ m#^\./?#);
1745 return ($repo_id, $path);
1748 (undef, undef, undef);
1751 sub new {
1752 my ($class, $ref_id, $repo_id, $path) = @_;
1753 if (defined $ref_id && !defined $repo_id && !defined $path) {
1754 ($repo_id, $path) = find_ref($ref_id);
1755 if (!defined $repo_id) {
1756 die "Could not find a \"svn-remote.*.fetch\" key ",
1757 "in the repository configuration matching: ",
1758 "refs/remotes/$ref_id\n";
1761 my $self = _new($class, $repo_id, $ref_id, $path);
1762 if (!defined $self->{path} || !length $self->{path}) {
1763 my $fetch = command_oneline('config', '--get',
1764 "svn-remote.$repo_id.fetch",
1765 ":refs/remotes/$ref_id\$") or
1766 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1767 "\":refs/remotes/$ref_id\$\" in config\n";
1768 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1770 $self->{url} = command_oneline('config', '--get',
1771 "svn-remote.$repo_id.url") or
1772 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1773 $self->rebuild;
1774 $self;
1777 sub refname {
1778 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1780 # It cannot end with a slash /, we'll throw up on this because
1781 # SVN can't have directories with a slash in their name, either:
1782 if ($refname =~ m{/$}) {
1783 die "ref: '$refname' ends with a trailing slash, this is ",
1784 "not permitted by git nor Subversion\n";
1787 # It cannot have ASCII control character space, tilde ~, caret ^,
1788 # colon :, question-mark ?, asterisk *, space, or open bracket [
1789 # anywhere.
1791 # Additionally, % must be escaped because it is used for escaping
1792 # and we want our escaped refname to be reversible
1793 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1795 # no slash-separated component can begin with a dot .
1796 # /.* becomes /%2E*
1797 $refname =~ s{/\.}{/%2E}g;
1799 # It cannot have two consecutive dots .. anywhere
1800 # .. becomes %2E%2E
1801 $refname =~ s{\.\.}{%2E%2E}g;
1803 return $refname;
1806 sub desanitize_refname {
1807 my ($refname) = @_;
1808 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1809 return $refname;
1812 sub svm_uuid {
1813 my ($self) = @_;
1814 return $self->{svm}->{uuid} if $self->svm;
1815 $self->ra;
1816 unless ($self->{svm}) {
1817 die "SVM UUID not cached, and reading remotely failed\n";
1819 $self->{svm}->{uuid};
1822 sub svm {
1823 my ($self) = @_;
1824 return $self->{svm} if $self->{svm};
1825 my $svm;
1826 # see if we have it in our config, first:
1827 eval {
1828 my $section = "svn-remote.$self->{repo_id}";
1829 $svm = {
1830 source => tmp_config('--get', "$section.svm-source"),
1831 uuid => tmp_config('--get', "$section.svm-uuid"),
1832 replace => tmp_config('--get', "$section.svm-replace"),
1835 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1836 $self->{svm} = $svm;
1838 $self->{svm};
1841 sub _set_svm_vars {
1842 my ($self, $ra) = @_;
1843 return $ra if $self->svm;
1845 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1846 "(svm:source, svm:uuid) ",
1847 "from the following URLs:\n" );
1848 sub read_svm_props {
1849 my ($self, $ra, $path, $r) = @_;
1850 my $props = ($ra->get_dir($path, $r))[2];
1851 my $src = $props->{'svm:source'};
1852 my $uuid = $props->{'svm:uuid'};
1853 return undef if (!$src || !$uuid);
1855 chomp($src, $uuid);
1857 $uuid =~ m{^[0-9a-f\-]{30,}$}
1858 or die "doesn't look right - svm:uuid is '$uuid'\n";
1860 # the '!' is used to mark the repos_root!/relative/path
1861 $src =~ s{/?!/?}{/};
1862 $src =~ s{/+$}{}; # no trailing slashes please
1863 # username is of no interest
1864 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1866 my $replace = $ra->{url};
1867 $replace .= "/$path" if length $path;
1869 my $section = "svn-remote.$self->{repo_id}";
1870 tmp_config("$section.svm-source", $src);
1871 tmp_config("$section.svm-replace", $replace);
1872 tmp_config("$section.svm-uuid", $uuid);
1873 $self->{svm} = {
1874 source => $src,
1875 uuid => $uuid,
1876 replace => $replace
1880 my $r = $ra->get_latest_revnum;
1881 my $path = $self->{path};
1882 my %tried;
1883 while (length $path) {
1884 unless ($tried{"$self->{url}/$path"}) {
1885 return $ra if $self->read_svm_props($ra, $path, $r);
1886 $tried{"$self->{url}/$path"} = 1;
1888 $path =~ s#/?[^/]+$##;
1890 die "Path: '$path' should be ''\n" if $path ne '';
1891 return $ra if $self->read_svm_props($ra, $path, $r);
1892 $tried{"$self->{url}/$path"} = 1;
1894 if ($ra->{repos_root} eq $self->{url}) {
1895 die @err, (map { " $_\n" } keys %tried), "\n";
1898 # nope, make sure we're connected to the repository root:
1899 my $ok;
1900 my @tried_b;
1901 $path = $ra->{svn_path};
1902 $ra = Git::SVN::Ra->new($ra->{repos_root});
1903 while (length $path) {
1904 unless ($tried{"$ra->{url}/$path"}) {
1905 $ok = $self->read_svm_props($ra, $path, $r);
1906 last if $ok;
1907 $tried{"$ra->{url}/$path"} = 1;
1909 $path =~ s#/?[^/]+$##;
1911 die "Path: '$path' should be ''\n" if $path ne '';
1912 $ok ||= $self->read_svm_props($ra, $path, $r);
1913 $tried{"$ra->{url}/$path"} = 1;
1914 if (!$ok) {
1915 die @err, (map { " $_\n" } keys %tried), "\n";
1917 Git::SVN::Ra->new($self->{url});
1920 sub svnsync {
1921 my ($self) = @_;
1922 return $self->{svnsync} if $self->{svnsync};
1924 if ($self->no_metadata) {
1925 die "Can't have both 'noMetadata' and ",
1926 "'useSvnsyncProps' options set!\n";
1928 if ($self->rewrite_root) {
1929 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1930 "options set!\n";
1933 my $svnsync;
1934 # see if we have it in our config, first:
1935 eval {
1936 my $section = "svn-remote.$self->{repo_id}";
1938 my $url = tmp_config('--get', "$section.svnsync-url");
1939 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1940 die "doesn't look right - svn:sync-from-url is '$url'\n";
1942 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1943 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1944 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1946 $svnsync = { url => $url, uuid => $uuid }
1948 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1949 return $self->{svnsync} = $svnsync;
1952 my $err = "useSvnsyncProps set, but failed to read " .
1953 "svnsync property: svn:sync-from-";
1954 my $rp = $self->ra->rev_proplist(0);
1956 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1957 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1958 die "doesn't look right - svn:sync-from-url is '$url'\n";
1960 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1961 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1962 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1964 my $section = "svn-remote.$self->{repo_id}";
1965 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1966 tmp_config('--add', "$section.svnsync-url", $url);
1967 return $self->{svnsync} = { url => $url, uuid => $uuid };
1970 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1971 # remote lookup (useful for 'git svn log').
1972 sub ra_uuid {
1973 my ($self) = @_;
1974 unless ($self->{ra_uuid}) {
1975 my $key = "svn-remote.$self->{repo_id}.uuid";
1976 my $uuid = eval { tmp_config('--get', $key) };
1977 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1978 $self->{ra_uuid} = $uuid;
1979 } else {
1980 die "ra_uuid called without URL\n" unless $self->{url};
1981 $self->{ra_uuid} = $self->ra->get_uuid;
1982 tmp_config('--add', $key, $self->{ra_uuid});
1985 $self->{ra_uuid};
1988 sub _set_repos_root {
1989 my ($self, $repos_root) = @_;
1990 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1991 $repos_root ||= $self->ra->{repos_root};
1992 tmp_config($k, $repos_root);
1993 $repos_root;
1996 sub repos_root {
1997 my ($self) = @_;
1998 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1999 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2002 sub ra {
2003 my ($self) = shift;
2004 my $ra = Git::SVN::Ra->new($self->{url});
2005 $self->_set_repos_root($ra->{repos_root});
2006 if ($self->use_svm_props && !$self->{svm}) {
2007 if ($self->no_metadata) {
2008 die "Can't have both 'noMetadata' and ",
2009 "'useSvmProps' options set!\n";
2010 } elsif ($self->use_svnsync_props) {
2011 die "Can't have both 'useSvnsyncProps' and ",
2012 "'useSvmProps' options set!\n";
2014 $ra = $self->_set_svm_vars($ra);
2015 $self->{-want_revprops} = 1;
2017 $ra;
2020 sub rel_path {
2021 my ($self) = @_;
2022 my $repos_root = $self->ra->{repos_root};
2023 return $self->{path} if ($self->{url} eq $repos_root);
2024 my $url = $self->{url} .
2025 (length $self->{path} ? "/$self->{path}" : $self->{path});
2026 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2027 $url;
2030 # prop_walk(PATH, REV, SUB)
2031 # -------------------------
2032 # Recursively traverse PATH at revision REV and invoke SUB for each
2033 # directory that contains a SVN property. SUB will be invoked as
2034 # follows: &SUB(gs, path, props); where `gs' is this instance of
2035 # Git::SVN, `path' the path to the directory where the properties
2036 # `props' were found. The `path' will be relative to point of checkout,
2037 # that is, if url://repo/trunk is the current Git branch, and that
2038 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2039 # as `path' (note the trailing `/').
2040 sub prop_walk {
2041 my ($self, $path, $rev, $sub) = @_;
2043 $path =~ s#^/##;
2044 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2045 $path =~ s#^/*#/#g;
2046 my $p = $path;
2047 # Strip the irrelevant part of the path.
2048 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2049 # Ensure the path is terminated by a `/'.
2050 $p =~ s#/*$#/#;
2052 # The properties contain all the internal SVN stuff nobody
2053 # (usually) cares about.
2054 my $interesting_props = 0;
2055 foreach (keys %{$props}) {
2056 # If it doesn't start with `svn:', it must be a
2057 # user-defined property.
2058 ++$interesting_props and next if $_ !~ /^svn:/;
2059 # FIXME: Fragile, if SVN adds new public properties,
2060 # this needs to be updated.
2061 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2062 |eol-style|mime-type
2063 |externals|needs-lock)$/x;
2065 &$sub($self, $p, $props) if $interesting_props;
2067 foreach (sort keys %$dirent) {
2068 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2069 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2073 sub last_rev { ($_[0]->last_rev_commit)[0] }
2074 sub last_commit { ($_[0]->last_rev_commit)[1] }
2076 # returns the newest SVN revision number and newest commit SHA1
2077 sub last_rev_commit {
2078 my ($self) = @_;
2079 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2080 return ($self->{last_rev}, $self->{last_commit});
2082 my $c = ::verify_ref($self->refname.'^0');
2083 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2084 my $rev = (::cmt_metadata($c))[1];
2085 if (defined $rev) {
2086 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2087 return ($rev, $c);
2090 my $map_path = $self->map_path;
2091 unless (-e $map_path) {
2092 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2093 return (undef, undef);
2095 my ($rev, $commit) = $self->rev_map_max(1);
2096 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2097 return ($rev, $commit);
2100 sub get_fetch_range {
2101 my ($self, $min, $max) = @_;
2102 $max ||= $self->ra->get_latest_revnum;
2103 $min ||= $self->rev_map_max;
2104 (++$min, $max);
2107 sub tmp_config {
2108 my (@args) = @_;
2109 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2110 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2111 if (! -f $config && -f $old_def_config) {
2112 rename $old_def_config, $config or
2113 die "Failed rename $old_def_config => $config: $!\n";
2115 my $old_config = $ENV{GIT_CONFIG};
2116 $ENV{GIT_CONFIG} = $config;
2117 $@ = undef;
2118 my @ret = eval {
2119 unless (-f $config) {
2120 mkfile($config);
2121 open my $fh, '>', $config or
2122 die "Can't open $config: $!\n";
2123 print $fh "; This file is used internally by ",
2124 "git-svn\n" or die
2125 "Couldn't write to $config: $!\n";
2126 print $fh "; You should not have to edit it\n" or
2127 die "Couldn't write to $config: $!\n";
2128 close $fh or die "Couldn't close $config: $!\n";
2130 command('config', @args);
2132 my $err = $@;
2133 if (defined $old_config) {
2134 $ENV{GIT_CONFIG} = $old_config;
2135 } else {
2136 delete $ENV{GIT_CONFIG};
2138 die $err if $err;
2139 wantarray ? @ret : $ret[0];
2142 sub tmp_index_do {
2143 my ($self, $sub) = @_;
2144 my $old_index = $ENV{GIT_INDEX_FILE};
2145 $ENV{GIT_INDEX_FILE} = $self->{index};
2146 $@ = undef;
2147 my @ret = eval {
2148 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2149 mkpath([$dir]) unless -d $dir;
2150 &$sub;
2152 my $err = $@;
2153 if (defined $old_index) {
2154 $ENV{GIT_INDEX_FILE} = $old_index;
2155 } else {
2156 delete $ENV{GIT_INDEX_FILE};
2158 die $err if $err;
2159 wantarray ? @ret : $ret[0];
2162 sub assert_index_clean {
2163 my ($self, $treeish) = @_;
2165 $self->tmp_index_do(sub {
2166 command_noisy('read-tree', $treeish) unless -e $self->{index};
2167 my $x = command_oneline('write-tree');
2168 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2169 /^tree ($::sha1)/mo);
2170 return if $y eq $x;
2172 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2173 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2174 command_noisy('read-tree', $treeish);
2175 $x = command_oneline('write-tree');
2176 if ($y ne $x) {
2177 ::fatal "trees ($treeish) $y != $x\n",
2178 "Something is seriously wrong...";
2183 sub get_commit_parents {
2184 my ($self, $log_entry) = @_;
2185 my (%seen, @ret, @tmp);
2186 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2187 if (my $ip = $self->{inject_parents}) {
2188 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2189 push @tmp, $commit;
2192 if (my $cur = ::verify_ref($self->refname.'^0')) {
2193 push @tmp, $cur;
2195 if (my $ipd = $self->{inject_parents_dcommit}) {
2196 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2197 push @tmp, @$commit;
2200 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2201 while (my $p = shift @tmp) {
2202 next if $seen{$p};
2203 $seen{$p} = 1;
2204 push @ret, $p;
2205 # MAXPARENT is defined to 16 in commit-tree.c:
2206 last if @ret >= 16;
2208 if (@tmp) {
2209 die "r$log_entry->{revision}: No room for parents:\n\t",
2210 join("\n\t", @tmp), "\n";
2212 @ret;
2215 sub rewrite_root {
2216 my ($self) = @_;
2217 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2218 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2219 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2220 if ($rwr) {
2221 $rwr =~ s#/+$##;
2222 if ($rwr !~ m#^[a-z\+]+://#) {
2223 die "$rwr is not a valid URL (key: $k)\n";
2226 $self->{-rewrite_root} = $rwr;
2229 sub metadata_url {
2230 my ($self) = @_;
2231 ($self->rewrite_root || $self->{url}) .
2232 (length $self->{path} ? '/' . $self->{path} : '');
2235 sub full_url {
2236 my ($self) = @_;
2237 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2241 sub set_commit_header_env {
2242 my ($log_entry) = @_;
2243 my %env;
2244 foreach my $ned (qw/NAME EMAIL DATE/) {
2245 foreach my $ac (qw/AUTHOR COMMITTER/) {
2246 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2250 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2251 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2252 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2254 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2255 ? $log_entry->{commit_name}
2256 : $log_entry->{name};
2257 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2258 ? $log_entry->{commit_email}
2259 : $log_entry->{email};
2260 \%env;
2263 sub restore_commit_header_env {
2264 my ($env) = @_;
2265 foreach my $ned (qw/NAME EMAIL DATE/) {
2266 foreach my $ac (qw/AUTHOR COMMITTER/) {
2267 my $k = "GIT_${ac}_${ned}";
2268 if (defined $env->{$k}) {
2269 $ENV{$k} = $env->{$k};
2270 } else {
2271 delete $ENV{$k};
2277 sub gc {
2278 command_noisy('gc', '--auto');
2281 sub do_git_commit {
2282 my ($self, $log_entry) = @_;
2283 my $lr = $self->last_rev;
2284 if (defined $lr && $lr >= $log_entry->{revision}) {
2285 die "Last fetched revision of ", $self->refname,
2286 " was r$lr, but we are about to fetch: ",
2287 "r$log_entry->{revision}!\n";
2289 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2290 croak "$log_entry->{revision} = $c already exists! ",
2291 "Why are we refetching it?\n";
2293 my $old_env = set_commit_header_env($log_entry);
2294 my $tree = $log_entry->{tree};
2295 if (!defined $tree) {
2296 $tree = $self->tmp_index_do(sub {
2297 command_oneline('write-tree') });
2299 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2301 my @exec = ('git', 'commit-tree', $tree);
2302 foreach ($self->get_commit_parents($log_entry)) {
2303 push @exec, '-p', $_;
2305 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2306 or croak $!;
2307 binmode $msg_fh;
2309 # we always get UTF-8 from SVN, but we may want our commits in
2310 # a different encoding.
2311 if (my $enc = Git::config('i18n.commitencoding')) {
2312 require Encode;
2313 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2315 print $msg_fh $log_entry->{log} or croak $!;
2316 restore_commit_header_env($old_env);
2317 unless ($self->no_metadata) {
2318 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2319 or croak $!;
2321 $msg_fh->flush == 0 or croak $!;
2322 close $msg_fh or croak $!;
2323 chomp(my $commit = do { local $/; <$out_fh> });
2324 close $out_fh or croak $!;
2325 waitpid $pid, 0;
2326 croak $? if $?;
2327 if ($commit !~ /^$::sha1$/o) {
2328 die "Failed to commit, invalid sha1: $commit\n";
2331 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2333 $self->{last_rev} = $log_entry->{revision};
2334 $self->{last_commit} = $commit;
2335 print "r$log_entry->{revision}" unless $::_q > 1;
2336 if (defined $log_entry->{svm_revision}) {
2337 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2338 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2339 0, $self->svm_uuid);
2341 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2342 if (--$_gc_nr == 0) {
2343 $_gc_nr = $_gc_period;
2344 gc();
2346 return $commit;
2349 sub match_paths {
2350 my ($self, $paths, $r) = @_;
2351 return 1 if $self->{path} eq '';
2352 if (my $path = $paths->{"/$self->{path}"}) {
2353 return ($path->{action} eq 'D') ? 0 : 1;
2355 my $repos_root = $self->ra->{repos_root};
2356 my $extended_path = $self->{url} . '/' . $self->{path};
2357 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2358 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2359 if (grep /$self->{path_regex}/, keys %$paths) {
2360 return 1;
2362 my $c = '';
2363 foreach (split m#/#, $self->{path}) {
2364 $c .= "/$_";
2365 next unless ($paths->{$c} &&
2366 ($paths->{$c}->{action} =~ /^[AR]$/));
2367 if ($self->ra->check_path($self->{path}, $r) ==
2368 $SVN::Node::dir) {
2369 return 1;
2372 return 0;
2375 sub find_parent_branch {
2376 my ($self, $paths, $rev) = @_;
2377 return undef unless $self->follow_parent;
2378 unless (defined $paths) {
2379 my $err_handler = $SVN::Error::handler;
2380 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2381 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2382 $paths =
2383 Git::SVN::Ra::dup_changed_paths($_[0]) });
2384 $SVN::Error::handler = $err_handler;
2386 return undef unless defined $paths;
2388 # look for a parent from another branch:
2389 my @b_path_components = split m#/#, $self->rel_path;
2390 my @a_path_components;
2391 my $i;
2392 while (@b_path_components) {
2393 $i = $paths->{'/'.join('/', @b_path_components)};
2394 last if $i && defined $i->{copyfrom_path};
2395 unshift(@a_path_components, pop(@b_path_components));
2397 return undef unless defined $i && defined $i->{copyfrom_path};
2398 my $branch_from = $i->{copyfrom_path};
2399 if (@a_path_components) {
2400 print STDERR "branch_from: $branch_from => ";
2401 $branch_from .= '/'.join('/', @a_path_components);
2402 print STDERR $branch_from, "\n";
2404 my $r = $i->{copyfrom_rev};
2405 my $repos_root = $self->ra->{repos_root};
2406 my $url = $self->ra->{url};
2407 my $new_url = $repos_root . $branch_from;
2408 print STDERR "Found possible branch point: ",
2409 "$new_url => ", $self->full_url, ", $r\n";
2410 $branch_from =~ s#^/##;
2411 my $gs = $self->other_gs($new_url, $url, $repos_root,
2412 $branch_from, $r, $self->{ref_id});
2413 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2415 my ($base, $head);
2416 if (!defined $r0 || !defined $parent) {
2417 ($base, $head) = parse_revision_argument(0, $r);
2418 } else {
2419 if ($r0 < $r) {
2420 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2421 0, 1, sub { $base = $_[1] - 1 });
2424 if (defined $base && $base <= $r) {
2425 $gs->fetch($base, $r);
2427 ($r0, $parent) = $gs->find_rev_before($r, 1);
2429 if (defined $r0 && defined $parent) {
2430 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2431 my $ed;
2432 if ($self->ra->can_do_switch) {
2433 $self->assert_index_clean($parent);
2434 print STDERR "Following parent with do_switch\n";
2435 # do_switch works with svn/trunk >= r22312, but that
2436 # is not included with SVN 1.4.3 (the latest version
2437 # at the moment), so we can't rely on it
2438 $self->{last_rev} = $r0;
2439 $self->{last_commit} = $parent;
2440 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2441 $gs->ra->gs_do_switch($r0, $rev, $gs,
2442 $self->full_url, $ed)
2443 or die "SVN connection failed somewhere...\n";
2444 } elsif ($self->ra->trees_match($new_url, $r0,
2445 $self->full_url, $rev)) {
2446 print STDERR "Trees match:\n",
2447 " $new_url\@$r0\n",
2448 " ${\$self->full_url}\@$rev\n",
2449 "Following parent with no changes\n";
2450 $self->tmp_index_do(sub {
2451 command_noisy('read-tree', $parent);
2453 $self->{last_commit} = $parent;
2454 } else {
2455 print STDERR "Following parent with do_update\n";
2456 $ed = SVN::Git::Fetcher->new($self);
2457 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2458 or die "SVN connection failed somewhere...\n";
2460 print STDERR "Successfully followed parent\n";
2461 return $self->make_log_entry($rev, [$parent], $ed);
2463 return undef;
2466 sub do_fetch {
2467 my ($self, $paths, $rev) = @_;
2468 my $ed;
2469 my ($last_rev, @parents);
2470 if (my $lc = $self->last_commit) {
2471 # we can have a branch that was deleted, then re-added
2472 # under the same name but copied from another path, in
2473 # which case we'll have multiple parents (we don't
2474 # want to break the original ref, nor lose copypath info):
2475 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2476 push @{$log_entry->{parents}}, $lc;
2477 return $log_entry;
2479 $ed = SVN::Git::Fetcher->new($self);
2480 $last_rev = $self->{last_rev};
2481 $ed->{c} = $lc;
2482 @parents = ($lc);
2483 } else {
2484 $last_rev = $rev;
2485 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2486 return $log_entry;
2488 $ed = SVN::Git::Fetcher->new($self);
2490 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2491 die "SVN connection failed somewhere...\n";
2493 $self->make_log_entry($rev, \@parents, $ed);
2496 sub get_untracked {
2497 my ($self, $ed) = @_;
2498 my @out;
2499 my $h = $ed->{empty};
2500 foreach (sort keys %$h) {
2501 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2502 push @out, " $act: " . uri_encode($_);
2503 warn "W: $act: $_\n";
2505 foreach my $t (qw/dir_prop file_prop/) {
2506 $h = $ed->{$t} or next;
2507 foreach my $path (sort keys %$h) {
2508 my $ppath = $path eq '' ? '.' : $path;
2509 foreach my $prop (sort keys %{$h->{$path}}) {
2510 next if $SKIP_PROP{$prop};
2511 my $v = $h->{$path}->{$prop};
2512 my $t_ppath_prop = "$t: " .
2513 uri_encode($ppath) . ' ' .
2514 uri_encode($prop);
2515 if (defined $v) {
2516 push @out, " +$t_ppath_prop " .
2517 uri_encode($v);
2518 } else {
2519 push @out, " -$t_ppath_prop";
2524 foreach my $t (qw/absent_file absent_directory/) {
2525 $h = $ed->{$t} or next;
2526 foreach my $parent (sort keys %$h) {
2527 foreach my $path (sort @{$h->{$parent}}) {
2528 push @out, " $t: " .
2529 uri_encode("$parent/$path");
2530 warn "W: $t: $parent/$path ",
2531 "Insufficient permissions?\n";
2535 \@out;
2538 # parse_svn_date(DATE)
2539 # --------------------
2540 # Given a date (in UTC) from Subversion, return a string in the format
2541 # "<TZ Offset> <local date/time>" that Git will use.
2543 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2544 # is true we'll convert it to the local timezone instead.
2545 sub parse_svn_date {
2546 my $date = shift || return '+0000 1970-01-01 00:00:00';
2547 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2548 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2549 croak "Unable to parse date: $date\n";
2550 my $parsed_date; # Set next.
2552 if ($Git::SVN::_localtime) {
2553 # Translate the Subversion datetime to an epoch time.
2554 # Begin by switching ourselves to $date's timezone, UTC.
2555 my $old_env_TZ = $ENV{TZ};
2556 $ENV{TZ} = 'UTC';
2558 my $epoch_in_UTC =
2559 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2561 # Determine our local timezone (including DST) at the
2562 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2563 # value of TZ, if any, at the time we were run.
2564 if (defined $Git::SVN::Log::TZ) {
2565 $ENV{TZ} = $Git::SVN::Log::TZ;
2566 } else {
2567 delete $ENV{TZ};
2570 my $our_TZ =
2571 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2573 # This converts $epoch_in_UTC into our local timezone.
2574 my ($sec, $min, $hour, $mday, $mon, $year,
2575 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2577 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2578 $our_TZ, $year + 1900, $mon + 1,
2579 $mday, $hour, $min, $sec);
2581 # Reset us to the timezone in effect when we entered
2582 # this routine.
2583 if (defined $old_env_TZ) {
2584 $ENV{TZ} = $old_env_TZ;
2585 } else {
2586 delete $ENV{TZ};
2588 } else {
2589 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2592 return $parsed_date;
2595 sub other_gs {
2596 my ($self, $new_url, $url, $repos_root,
2597 $branch_from, $r, $old_ref_id) = @_;
2598 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2599 unless ($gs) {
2600 my $ref_id = $old_ref_id;
2601 $ref_id =~ s/\@\d+$//;
2602 $ref_id .= "\@$r";
2603 # just grow a tail if we're not unique enough :x
2604 $ref_id .= '-' while find_ref($ref_id);
2605 print STDERR "Initializing parent: $ref_id\n";
2606 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2607 if ($u =~ s#^\Q$url\E(/|$)##) {
2608 $p = $u;
2609 $u = $url;
2610 $repo_id = $self->{repo_id};
2612 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2617 sub check_author {
2618 my ($author) = @_;
2619 if (!defined $author || length $author == 0) {
2620 $author = '(no author)';
2621 } elsif (defined $::_authors && ! defined $::users{$author}) {
2622 die "Author: $author not defined in $::_authors file\n";
2624 $author;
2627 sub make_log_entry {
2628 my ($self, $rev, $parents, $ed) = @_;
2629 my $untracked = $self->get_untracked($ed);
2631 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2632 print $un "r$rev\n" or croak $!;
2633 print $un $_, "\n" foreach @$untracked;
2634 my %log_entry = ( parents => $parents || [], revision => $rev,
2635 log => '');
2637 my $headrev;
2638 my $logged = delete $self->{logged_rev_props};
2639 if (!$logged || $self->{-want_revprops}) {
2640 my $rp = $self->ra->rev_proplist($rev);
2641 foreach (sort keys %$rp) {
2642 my $v = $rp->{$_};
2643 if (/^svn:(author|date|log)$/) {
2644 $log_entry{$1} = $v;
2645 } elsif ($_ eq 'svm:headrev') {
2646 $headrev = $v;
2647 } else {
2648 print $un " rev_prop: ", uri_encode($_), ' ',
2649 uri_encode($v), "\n";
2652 } else {
2653 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2655 close $un or croak $!;
2657 $log_entry{date} = parse_svn_date($log_entry{date});
2658 $log_entry{log} .= "\n";
2659 my $author = $log_entry{author} = check_author($log_entry{author});
2660 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2661 : ($author, undef);
2663 my ($commit_name, $commit_email) = ($name, $email);
2664 if ($_use_log_author) {
2665 my $name_field;
2666 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2667 $name_field = $1;
2668 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2669 $name_field = $1;
2671 if (!defined $name_field) {
2672 if (!defined $email) {
2673 $email = $name;
2675 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2676 ($name, $email) = ($1, $2);
2677 } elsif ($name_field =~ /(.*)@/) {
2678 ($name, $email) = ($1, $name_field);
2679 } else {
2680 ($name, $email) = ($name_field, $name_field);
2683 if (defined $headrev && $self->use_svm_props) {
2684 if ($self->rewrite_root) {
2685 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2686 "options set!\n";
2688 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2689 # we don't want "SVM: initializing mirror for junk" ...
2690 return undef if $r == 0;
2691 my $svm = $self->svm;
2692 if ($uuid ne $svm->{uuid}) {
2693 die "UUID mismatch on SVM path:\n",
2694 "expected: $svm->{uuid}\n",
2695 " got: $uuid\n";
2697 my $full_url = $self->full_url;
2698 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2699 die "Failed to replace '$svm->{replace}' with ",
2700 "'$svm->{source}' in $full_url\n";
2701 # throw away username for storing in records
2702 remove_username($full_url);
2703 $log_entry{metadata} = "$full_url\@$r $uuid";
2704 $log_entry{svm_revision} = $r;
2705 $email ||= "$author\@$uuid";
2706 $commit_email ||= "$author\@$uuid";
2707 } elsif ($self->use_svnsync_props) {
2708 my $full_url = $self->svnsync->{url};
2709 $full_url .= "/$self->{path}" if length $self->{path};
2710 remove_username($full_url);
2711 my $uuid = $self->svnsync->{uuid};
2712 $log_entry{metadata} = "$full_url\@$rev $uuid";
2713 $email ||= "$author\@$uuid";
2714 $commit_email ||= "$author\@$uuid";
2715 } else {
2716 my $url = $self->metadata_url;
2717 remove_username($url);
2718 $log_entry{metadata} = "$url\@$rev " .
2719 $self->ra->get_uuid;
2720 $email ||= "$author\@" . $self->ra->get_uuid;
2721 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2723 $log_entry{name} = $name;
2724 $log_entry{email} = $email;
2725 $log_entry{commit_name} = $commit_name;
2726 $log_entry{commit_email} = $commit_email;
2727 \%log_entry;
2730 sub fetch {
2731 my ($self, $min_rev, $max_rev, @parents) = @_;
2732 my ($last_rev, $last_commit) = $self->last_rev_commit;
2733 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2734 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2737 sub set_tree_cb {
2738 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2739 $self->{inject_parents} = { $rev => $tree };
2740 $self->fetch(undef, undef);
2743 sub set_tree {
2744 my ($self, $tree) = (shift, shift);
2745 my $log_entry = ::get_commit_entry($tree);
2746 unless ($self->{last_rev}) {
2747 ::fatal("Must have an existing revision to commit");
2749 my %ed_opts = ( r => $self->{last_rev},
2750 log => $log_entry->{log},
2751 ra => $self->ra,
2752 tree_a => $self->{last_commit},
2753 tree_b => $tree,
2754 editor_cb => sub {
2755 $self->set_tree_cb($log_entry, $tree, @_) },
2756 svn_path => $self->{path} );
2757 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2758 print "No changes\nr$self->{last_rev} = $tree\n";
2762 sub rebuild_from_rev_db {
2763 my ($self, $path) = @_;
2764 my $r = -1;
2765 open my $fh, '<', $path or croak "open: $!";
2766 binmode $fh or croak "binmode: $!";
2767 while (<$fh>) {
2768 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2769 chomp($_);
2770 ++$r;
2771 next if $_ eq ('0' x 40);
2772 $self->rev_map_set($r, $_);
2773 print "r$r = $_\n";
2775 close $fh or croak "close: $!";
2776 unlink $path or croak "unlink: $!";
2779 sub rebuild {
2780 my ($self) = @_;
2781 my $map_path = $self->map_path;
2782 my $partial = (-e $map_path && ! -z $map_path);
2783 return unless ::verify_ref($self->refname.'^0');
2784 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2785 my $rev_db = $self->rev_db_path;
2786 $self->rebuild_from_rev_db($rev_db);
2787 if ($self->use_svm_props) {
2788 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2789 $self->rebuild_from_rev_db($svm_rev_db);
2791 $self->unlink_rev_db_symlink;
2792 return;
2794 print "Rebuilding $map_path ...\n" if (!$partial);
2795 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2796 (undef, undef));
2797 my ($log, $ctx) =
2798 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2799 ($head ? "$head.." : "") . $self->refname,
2800 '--');
2801 my $metadata_url = $self->metadata_url;
2802 remove_username($metadata_url);
2803 my $svn_uuid = $self->ra_uuid;
2804 my $c;
2805 while (<$log>) {
2806 if ( m{^commit ($::sha1)$} ) {
2807 $c = $1;
2808 next;
2810 next unless s{^\s*(git-svn-id:)}{$1};
2811 my ($url, $rev, $uuid) = ::extract_metadata($_);
2812 remove_username($url);
2814 # ignore merges (from set-tree)
2815 next if (!defined $rev || !$uuid);
2817 # if we merged or otherwise started elsewhere, this is
2818 # how we break out of it
2819 if (($uuid ne $svn_uuid) ||
2820 ($metadata_url && $url && ($url ne $metadata_url))) {
2821 next;
2823 if ($partial && $head) {
2824 print "Partial-rebuilding $map_path ...\n";
2825 print "Currently at $base_rev = $head\n";
2826 $head = undef;
2829 $self->rev_map_set($rev, $c);
2830 print "r$rev = $c\n";
2832 command_close_pipe($log, $ctx);
2833 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2834 my $rev_db_path = $self->rev_db_path;
2835 if (-f $self->rev_db_path) {
2836 unlink $self->rev_db_path or croak "unlink: $!";
2838 $self->unlink_rev_db_symlink;
2841 # rev_map:
2842 # Tie::File seems to be prone to offset errors if revisions get sparse,
2843 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2844 # one of my favorite modules is out :< Next up would be one of the DBM
2845 # modules, but I'm not sure which is most portable...
2847 # This is the replacement for the rev_db format, which was too big
2848 # and inefficient for large repositories with a lot of sparse history
2849 # (mainly tags)
2851 # The format is this:
2852 # - 24 bytes for every record,
2853 # * 4 bytes for the integer representing an SVN revision number
2854 # * 20 bytes representing the sha1 of a git commit
2855 # - No empty padding records like the old format
2856 # (except the last record, which can be overwritten)
2857 # - new records are written append-only since SVN revision numbers
2858 # increase monotonically
2859 # - lookups on SVN revision number are done via a binary search
2860 # - Piping the file to xxd -c24 is a good way of dumping it for
2861 # viewing or editing (piped back through xxd -r), should the need
2862 # ever arise.
2863 # - The last record can be padding revision with an all-zero sha1
2864 # This is used to optimize fetch performance when using multiple
2865 # "fetch" directives in .git/config
2867 # These files are disposable unless noMetadata or useSvmProps is set
2869 sub _rev_map_set {
2870 my ($fh, $rev, $commit) = @_;
2872 binmode $fh or croak "binmode: $!";
2873 my $size = (stat($fh))[7];
2874 ($size % 24) == 0 or croak "inconsistent size: $size";
2876 my $wr_offset = 0;
2877 if ($size > 0) {
2878 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2879 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2880 $read == 24 or croak "read only $read bytes (!= 24)";
2881 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2882 if ($last_commit eq ('0' x40)) {
2883 if ($size >= 48) {
2884 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2885 $read = sysread($fh, $buf, 24) or
2886 croak "read: $!";
2887 $read == 24 or
2888 croak "read only $read bytes (!= 24)";
2889 ($last_rev, $last_commit) =
2890 unpack(rev_map_fmt, $buf);
2891 if ($last_commit eq ('0' x40)) {
2892 croak "inconsistent .rev_map\n";
2895 if ($last_rev >= $rev) {
2896 croak "last_rev is higher!: $last_rev >= $rev";
2898 $wr_offset = -24;
2901 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2902 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2903 croak "write: $!";
2906 sub mkfile {
2907 my ($path) = @_;
2908 unless (-e $path) {
2909 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2910 mkpath([$dir]) unless -d $dir;
2911 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2912 close $fh or die "Couldn't close (create) $path: $!\n";
2916 sub rev_map_set {
2917 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2918 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2919 my $db = $self->map_path($uuid);
2920 my $db_lock = "$db.lock";
2921 my $sig;
2922 if ($update_ref) {
2923 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2924 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2926 mkfile($db);
2928 $LOCKFILES{$db_lock} = 1;
2929 my $sync;
2930 # both of these options make our .rev_db file very, very important
2931 # and we can't afford to lose it because rebuild() won't work
2932 if ($self->use_svm_props || $self->no_metadata) {
2933 $sync = 1;
2934 copy($db, $db_lock) or die "rev_map_set(@_): ",
2935 "Failed to copy: ",
2936 "$db => $db_lock ($!)\n";
2937 } else {
2938 rename $db, $db_lock or die "rev_map_set(@_): ",
2939 "Failed to rename: ",
2940 "$db => $db_lock ($!)\n";
2943 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2944 or croak "Couldn't open $db_lock: $!\n";
2945 _rev_map_set($fh, $rev, $commit);
2946 if ($sync) {
2947 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2948 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2950 close $fh or croak $!;
2951 if ($update_ref) {
2952 $_head = $self;
2953 command_noisy('update-ref', '-m', "r$rev",
2954 $self->refname, $commit);
2956 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2957 "$db_lock => $db ($!)\n";
2958 delete $LOCKFILES{$db_lock};
2959 if ($update_ref) {
2960 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2961 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2962 kill $sig, $$ if defined $sig;
2966 # If want_commit, this will return an array of (rev, commit) where
2967 # commit _must_ be a valid commit in the archive.
2968 # Otherwise, it'll return the max revision (whether or not the
2969 # commit is valid or just a 0x40 placeholder).
2970 sub rev_map_max {
2971 my ($self, $want_commit) = @_;
2972 $self->rebuild;
2973 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2974 $want_commit ? ($r, $c) : $r;
2977 sub rev_map_max_norebuild {
2978 my ($self, $want_commit) = @_;
2979 my $map_path = $self->map_path;
2980 stat $map_path or return $want_commit ? (0, undef) : 0;
2981 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2982 binmode $fh or croak "binmode: $!";
2983 my $size = (stat($fh))[7];
2984 ($size % 24) == 0 or croak "inconsistent size: $size";
2986 if ($size == 0) {
2987 close $fh or croak "close: $!";
2988 return $want_commit ? (0, undef) : 0;
2991 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2992 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2993 my ($r, $c) = unpack(rev_map_fmt, $buf);
2994 if ($want_commit && $c eq ('0' x40)) {
2995 if ($size < 48) {
2996 return $want_commit ? (0, undef) : 0;
2998 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2999 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3000 ($r, $c) = unpack(rev_map_fmt, $buf);
3001 if ($c eq ('0'x40)) {
3002 croak "Penultimate record is all-zeroes in $map_path";
3005 close $fh or croak "close: $!";
3006 $want_commit ? ($r, $c) : $r;
3009 sub rev_map_get {
3010 my ($self, $rev, $uuid) = @_;
3011 my $map_path = $self->map_path($uuid);
3012 return undef unless -e $map_path;
3014 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3015 binmode $fh or croak "binmode: $!";
3016 my $size = (stat($fh))[7];
3017 ($size % 24) == 0 or croak "inconsistent size: $size";
3019 if ($size == 0) {
3020 close $fh or croak "close: $fh";
3021 return undef;
3024 my ($l, $u) = (0, $size - 24);
3025 my ($r, $c, $buf);
3027 while ($l <= $u) {
3028 my $i = int(($l/24 + $u/24) / 2) * 24;
3029 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3030 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3031 my ($r, $c) = unpack('NH40', $buf);
3033 if ($r < $rev) {
3034 $l = $i + 24;
3035 } elsif ($r > $rev) {
3036 $u = $i - 24;
3037 } else { # $r == $rev
3038 close($fh) or croak "close: $!";
3039 return $c eq ('0' x 40) ? undef : $c;
3042 close($fh) or croak "close: $!";
3043 undef;
3046 # Finds the first svn revision that exists on (if $eq_ok is true) or
3047 # before $rev for the current branch. It will not search any lower
3048 # than $min_rev. Returns the git commit hash and svn revision number
3049 # if found, else (undef, undef).
3050 sub find_rev_before {
3051 my ($self, $rev, $eq_ok, $min_rev) = @_;
3052 --$rev unless $eq_ok;
3053 $min_rev ||= 1;
3054 while ($rev >= $min_rev) {
3055 if (my $c = $self->rev_map_get($rev)) {
3056 return ($rev, $c);
3058 --$rev;
3060 return (undef, undef);
3063 # Finds the first svn revision that exists on (if $eq_ok is true) or
3064 # after $rev for the current branch. It will not search any higher
3065 # than $max_rev. Returns the git commit hash and svn revision number
3066 # if found, else (undef, undef).
3067 sub find_rev_after {
3068 my ($self, $rev, $eq_ok, $max_rev) = @_;
3069 ++$rev unless $eq_ok;
3070 $max_rev ||= $self->rev_map_max;
3071 while ($rev <= $max_rev) {
3072 if (my $c = $self->rev_map_get($rev)) {
3073 return ($rev, $c);
3075 ++$rev;
3077 return (undef, undef);
3080 sub _new {
3081 my ($class, $repo_id, $ref_id, $path) = @_;
3082 unless (defined $repo_id && length $repo_id) {
3083 $repo_id = $Git::SVN::default_repo_id;
3085 unless (defined $ref_id && length $ref_id) {
3086 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3088 $_[1] = $repo_id;
3089 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3090 $_[3] = $path = '' unless (defined $path);
3091 mkpath(["$ENV{GIT_DIR}/svn"]);
3092 bless {
3093 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3094 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3095 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3098 # for read-only access of old .rev_db formats
3099 sub unlink_rev_db_symlink {
3100 my ($self) = @_;
3101 my $link = $self->rev_db_path;
3102 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3103 if (-l $link) {
3104 unlink $link or croak "unlink: $link failed!";
3108 sub rev_db_path {
3109 my ($self, $uuid) = @_;
3110 my $db_path = $self->map_path($uuid);
3111 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3112 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3113 $db_path;
3116 # the new replacement for .rev_db
3117 sub map_path {
3118 my ($self, $uuid) = @_;
3119 $uuid ||= $self->ra_uuid;
3120 "$self->{map_root}.$uuid";
3123 sub uri_encode {
3124 my ($f) = @_;
3125 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3129 sub remove_username {
3130 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3133 package Git::SVN::Prompt;
3134 use strict;
3135 use warnings;
3136 require SVN::Core;
3137 use vars qw/$_no_auth_cache $_username/;
3139 sub simple {
3140 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3141 $may_save = undef if $_no_auth_cache;
3142 $default_username = $_username if defined $_username;
3143 if (defined $default_username && length $default_username) {
3144 if (defined $realm && length $realm) {
3145 print STDERR "Authentication realm: $realm\n";
3146 STDERR->flush;
3148 $cred->username($default_username);
3149 } else {
3150 username($cred, $realm, $may_save, $pool);
3152 $cred->password(_read_password("Password for '" .
3153 $cred->username . "': ", $realm));
3154 $cred->may_save($may_save);
3155 $SVN::_Core::SVN_NO_ERROR;
3158 sub ssl_server_trust {
3159 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3160 $may_save = undef if $_no_auth_cache;
3161 print STDERR "Error validating server certificate for '$realm':\n";
3163 no warnings 'once';
3164 # All variables SVN::Auth::SSL::* are used only once,
3165 # so we're shutting up Perl warnings about this.
3166 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3167 print STDERR " - The certificate is not issued ",
3168 "by a trusted authority. Use the\n",
3169 " fingerprint to validate ",
3170 "the certificate manually!\n";
3172 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3173 print STDERR " - The certificate hostname ",
3174 "does not match.\n";
3176 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3177 print STDERR " - The certificate is not yet valid.\n";
3179 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3180 print STDERR " - The certificate has expired.\n";
3182 if ($failures & $SVN::Auth::SSL::OTHER) {
3183 print STDERR " - The certificate has ",
3184 "an unknown error.\n";
3186 } # no warnings 'once'
3187 printf STDERR
3188 "Certificate information:\n".
3189 " - Hostname: %s\n".
3190 " - Valid: from %s until %s\n".
3191 " - Issuer: %s\n".
3192 " - Fingerprint: %s\n",
3193 map $cert_info->$_, qw(hostname valid_from valid_until
3194 issuer_dname fingerprint);
3195 my $choice;
3196 prompt:
3197 print STDERR $may_save ?
3198 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3199 "(R)eject or accept (t)emporarily? ";
3200 STDERR->flush;
3201 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3202 if ($choice =~ /^t$/i) {
3203 $cred->may_save(undef);
3204 } elsif ($choice =~ /^r$/i) {
3205 return -1;
3206 } elsif ($may_save && $choice =~ /^p$/i) {
3207 $cred->may_save($may_save);
3208 } else {
3209 goto prompt;
3211 $cred->accepted_failures($failures);
3212 $SVN::_Core::SVN_NO_ERROR;
3215 sub ssl_client_cert {
3216 my ($cred, $realm, $may_save, $pool) = @_;
3217 $may_save = undef if $_no_auth_cache;
3218 print STDERR "Client certificate filename: ";
3219 STDERR->flush;
3220 chomp(my $filename = <STDIN>);
3221 $cred->cert_file($filename);
3222 $cred->may_save($may_save);
3223 $SVN::_Core::SVN_NO_ERROR;
3226 sub ssl_client_cert_pw {
3227 my ($cred, $realm, $may_save, $pool) = @_;
3228 $may_save = undef if $_no_auth_cache;
3229 $cred->password(_read_password("Password: ", $realm));
3230 $cred->may_save($may_save);
3231 $SVN::_Core::SVN_NO_ERROR;
3234 sub username {
3235 my ($cred, $realm, $may_save, $pool) = @_;
3236 $may_save = undef if $_no_auth_cache;
3237 if (defined $realm && length $realm) {
3238 print STDERR "Authentication realm: $realm\n";
3240 my $username;
3241 if (defined $_username) {
3242 $username = $_username;
3243 } else {
3244 print STDERR "Username: ";
3245 STDERR->flush;
3246 chomp($username = <STDIN>);
3248 $cred->username($username);
3249 $cred->may_save($may_save);
3250 $SVN::_Core::SVN_NO_ERROR;
3253 sub _read_password {
3254 my ($prompt, $realm) = @_;
3255 print STDERR $prompt;
3256 STDERR->flush;
3257 require Term::ReadKey;
3258 Term::ReadKey::ReadMode('noecho');
3259 my $password = '';
3260 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3261 last if $key =~ /[\012\015]/; # \n\r
3262 $password .= $key;
3264 Term::ReadKey::ReadMode('restore');
3265 print STDERR "\n";
3266 STDERR->flush;
3267 $password;
3270 package SVN::Git::Fetcher;
3271 use vars qw/@ISA/;
3272 use strict;
3273 use warnings;
3274 use Carp qw/croak/;
3275 use File::Temp qw/tempfile/;
3276 use IO::File qw//;
3277 use vars qw/$_ignore_regex/;
3279 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3280 sub new {
3281 my ($class, $git_svn, $switch_path) = @_;
3282 my $self = SVN::Delta::Editor->new;
3283 bless $self, $class;
3284 if (exists $git_svn->{last_commit}) {
3285 $self->{c} = $git_svn->{last_commit};
3286 $self->{empty_symlinks} =
3287 _mark_empty_symlinks($git_svn, $switch_path);
3289 $self->{empty} = {};
3290 $self->{dir_prop} = {};
3291 $self->{file_prop} = {};
3292 $self->{absent_dir} = {};
3293 $self->{absent_file} = {};
3294 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3295 $self;
3298 # this uses the Ra object, so it must be called before do_{switch,update},
3299 # not inside them (when the Git::SVN::Fetcher object is passed) to
3300 # do_{switch,update}
3301 sub _mark_empty_symlinks {
3302 my ($git_svn, $switch_path) = @_;
3303 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3304 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3306 my %ret;
3307 my ($rev, $cmt) = $git_svn->last_rev_commit;
3308 return {} unless ($rev && $cmt);
3310 # allow the warning to be printed for each revision we fetch to
3311 # ensure the user sees it. The user can also disable the workaround
3312 # on the repository even while git svn is running and the next
3313 # revision fetched will skip this expensive function.
3314 my $printed_warning;
3315 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3316 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3317 local $/ = "\0";
3318 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3319 $pfx .= '/' if length($pfx);
3320 while (<$ls>) {
3321 chomp;
3322 s/\A100644 blob $empty_blob\t//o or next;
3323 unless ($printed_warning) {
3324 print STDERR "Scanning for empty symlinks, ",
3325 "this may take a while if you have ",
3326 "many empty files\n",
3327 "You may disable this with `",
3328 "git config svn.brokenSymlinkWorkaround ",
3329 "false'.\n",
3330 "This may be done in a different ",
3331 "terminal without restarting ",
3332 "git svn\n";
3333 $printed_warning = 1;
3335 my $path = $_;
3336 my (undef, $props) =
3337 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3338 if ($props->{'svn:special'}) {
3339 $ret{$path} = 1;
3342 command_close_pipe($ls, $ctx);
3343 \%ret;
3346 # returns true if a given path is inside a ".git" directory
3347 sub in_dot_git {
3348 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3351 # return value: 0 -- don't ignore, 1 -- ignore
3352 sub is_path_ignored {
3353 my ($path) = @_;
3354 return 1 if in_dot_git($path);
3355 return 0 unless defined($_ignore_regex);
3356 return 1 if $path =~ m!$_ignore_regex!o;
3357 return 0;
3360 sub set_path_strip {
3361 my ($self, $path) = @_;
3362 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3365 sub open_root {
3366 { path => '' };
3369 sub open_directory {
3370 my ($self, $path, $pb, $rev) = @_;
3371 { path => $path };
3374 sub git_path {
3375 my ($self, $path) = @_;
3376 if ($self->{path_strip}) {
3377 $path =~ s!$self->{path_strip}!! or
3378 die "Failed to strip path '$path' ($self->{path_strip})\n";
3380 $path;
3383 sub delete_entry {
3384 my ($self, $path, $rev, $pb) = @_;
3385 return undef if is_path_ignored($path);
3387 my $gpath = $self->git_path($path);
3388 return undef if ($gpath eq '');
3390 # remove entire directories.
3391 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3392 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3393 if ($tree) {
3394 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3395 -r --name-only -z/,
3396 $tree);
3397 local $/ = "\0";
3398 while (<$ls>) {
3399 chomp;
3400 my $rmpath = "$gpath/$_";
3401 $self->{gii}->remove($rmpath);
3402 print "\tD\t$rmpath\n" unless $::_q;
3404 print "\tD\t$gpath/\n" unless $::_q;
3405 command_close_pipe($ls, $ctx);
3406 $self->{empty}->{$path} = 0
3407 } else {
3408 $self->{gii}->remove($gpath);
3409 print "\tD\t$gpath\n" unless $::_q;
3411 undef;
3414 sub open_file {
3415 my ($self, $path, $pb, $rev) = @_;
3416 my ($mode, $blob);
3418 goto out if is_path_ignored($path);
3420 my $gpath = $self->git_path($path);
3421 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3422 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3423 unless (defined $mode && defined $blob) {
3424 die "$path was not found in commit $self->{c} (r$rev)\n";
3426 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3427 $mode = '120000';
3429 out:
3430 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3431 pool => SVN::Pool->new, action => 'M' };
3434 sub add_file {
3435 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3436 my $mode;
3438 if (!is_path_ignored($path)) {
3439 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3440 delete $self->{empty}->{$dir};
3441 $mode = '100644';
3443 { path => $path, mode_a => $mode, mode_b => $mode,
3444 pool => SVN::Pool->new, action => 'A' };
3447 sub add_directory {
3448 my ($self, $path, $cp_path, $cp_rev) = @_;
3449 goto out if is_path_ignored($path);
3450 my $gpath = $self->git_path($path);
3451 if ($gpath eq '') {
3452 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3453 -r --name-only -z/,
3454 $self->{c});
3455 local $/ = "\0";
3456 while (<$ls>) {
3457 chomp;
3458 $self->{gii}->remove($_);
3459 print "\tD\t$_\n" unless $::_q;
3461 command_close_pipe($ls, $ctx);
3462 $self->{empty}->{$path} = 0;
3464 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3465 delete $self->{empty}->{$dir};
3466 $self->{empty}->{$path} = 1;
3467 out:
3468 { path => $path };
3471 sub change_dir_prop {
3472 my ($self, $db, $prop, $value) = @_;
3473 return undef if is_path_ignored($db->{path});
3474 $self->{dir_prop}->{$db->{path}} ||= {};
3475 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3476 undef;
3479 sub absent_directory {
3480 my ($self, $path, $pb) = @_;
3481 return undef if is_path_ignored($path);
3482 $self->{absent_dir}->{$pb->{path}} ||= [];
3483 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3484 undef;
3487 sub absent_file {
3488 my ($self, $path, $pb) = @_;
3489 return undef if is_path_ignored($path);
3490 $self->{absent_file}->{$pb->{path}} ||= [];
3491 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3492 undef;
3495 sub change_file_prop {
3496 my ($self, $fb, $prop, $value) = @_;
3497 return undef if is_path_ignored($fb->{path});
3498 if ($prop eq 'svn:executable') {
3499 if ($fb->{mode_b} != 120000) {
3500 $fb->{mode_b} = defined $value ? 100755 : 100644;
3502 } elsif ($prop eq 'svn:special') {
3503 $fb->{mode_b} = defined $value ? 120000 : 100644;
3504 } else {
3505 $self->{file_prop}->{$fb->{path}} ||= {};
3506 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3508 undef;
3511 sub apply_textdelta {
3512 my ($self, $fb, $exp) = @_;
3513 return undef if is_path_ignored($fb->{path});
3514 my $fh = $::_repository->temp_acquire('svn_delta');
3515 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3516 # (but $base does not,) so dup() it for reading in close_file
3517 open my $dup, '<&', $fh or croak $!;
3518 my $base = $::_repository->temp_acquire('git_blob');
3520 if ($fb->{blob}) {
3521 my ($base_is_link, $size);
3523 if ($fb->{mode_a} eq '120000' &&
3524 ! $self->{empty_symlinks}->{$fb->{path}}) {
3525 print $base 'link ' or die "print $!\n";
3526 $base_is_link = 1;
3528 retry:
3529 $size = $::_repository->cat_blob($fb->{blob}, $base);
3530 die "Failed to read object $fb->{blob}" if ($size < 0);
3532 if (defined $exp) {
3533 seek $base, 0, 0 or croak $!;
3534 my $got = ::md5sum($base);
3535 if ($got ne $exp) {
3536 my $err = "Checksum mismatch: ".
3537 "$fb->{path} $fb->{blob}\n" .
3538 "expected: $exp\n" .
3539 " got: $got\n";
3540 if ($base_is_link) {
3541 warn $err,
3542 "Retrying... (possibly ",
3543 "a bad symlink from SVN)\n";
3544 $::_repository->temp_reset($base);
3545 $base_is_link = 0;
3546 goto retry;
3548 die $err;
3552 seek $base, 0, 0 or croak $!;
3553 $fb->{fh} = $fh;
3554 $fb->{base} = $base;
3555 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3558 sub close_file {
3559 my ($self, $fb, $exp) = @_;
3560 return undef if is_path_ignored($fb->{path});
3562 my $hash;
3563 my $path = $self->git_path($fb->{path});
3564 if (my $fh = $fb->{fh}) {
3565 if (defined $exp) {
3566 seek($fh, 0, 0) or croak $!;
3567 my $got = ::md5sum($fh);
3568 if ($got ne $exp) {
3569 die "Checksum mismatch: $path\n",
3570 "expected: $exp\n got: $got\n";
3573 if ($fb->{mode_b} == 120000) {
3574 sysseek($fh, 0, 0) or croak $!;
3575 my $rd = sysread($fh, my $buf, 5);
3577 if (!defined $rd) {
3578 croak "sysread: $!\n";
3579 } elsif ($rd == 0) {
3580 warn "$path has mode 120000",
3581 " but it points to nothing\n",
3582 "converting to an empty file with mode",
3583 " 100644\n";
3584 $fb->{mode_b} = '100644';
3585 } elsif ($buf ne 'link ') {
3586 warn "$path has mode 120000",
3587 " but is not a link\n";
3588 } else {
3589 my $tmp_fh = $::_repository->temp_acquire(
3590 'svn_hash');
3591 my $res;
3592 while ($res = sysread($fh, my $str, 1024)) {
3593 my $out = syswrite($tmp_fh, $str, $res);
3594 defined($out) && $out == $res
3595 or croak("write ",
3596 Git::temp_path($tmp_fh),
3597 ": $!\n");
3599 defined $res or croak $!;
3601 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3602 Git::temp_release($tmp_fh, 1);
3606 $hash = $::_repository->hash_and_insert_object(
3607 Git::temp_path($fh));
3608 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3610 Git::temp_release($fb->{base}, 1);
3611 Git::temp_release($fh, 1);
3612 } else {
3613 $hash = $fb->{blob} or die "no blob information\n";
3615 $fb->{pool}->clear;
3616 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3617 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3618 undef;
3621 sub abort_edit {
3622 my $self = shift;
3623 $self->{nr} = $self->{gii}->{nr};
3624 delete $self->{gii};
3625 $self->SUPER::abort_edit(@_);
3628 sub close_edit {
3629 my $self = shift;
3630 $self->{git_commit_ok} = 1;
3631 $self->{nr} = $self->{gii}->{nr};
3632 delete $self->{gii};
3633 $self->SUPER::close_edit(@_);
3636 package SVN::Git::Editor;
3637 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3638 use strict;
3639 use warnings;
3640 use Carp qw/croak/;
3641 use IO::File;
3643 sub new {
3644 my ($class, $opts) = @_;
3645 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3646 die "$_ required!\n" unless (defined $opts->{$_});
3649 my $pool = SVN::Pool->new;
3650 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3651 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3652 $opts->{r}, $mods);
3654 # $opts->{ra} functions should not be used after this:
3655 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3656 $opts->{editor_cb}, $pool);
3657 my $self = SVN::Delta::Editor->new(@ce, $pool);
3658 bless $self, $class;
3659 foreach (qw/svn_path r tree_a tree_b/) {
3660 $self->{$_} = $opts->{$_};
3662 $self->{url} = $opts->{ra}->{url};
3663 $self->{mods} = $mods;
3664 $self->{types} = $types;
3665 $self->{pool} = $pool;
3666 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3667 $self->{rm} = { };
3668 $self->{path_prefix} = length $self->{svn_path} ?
3669 "$self->{svn_path}/" : '';
3670 $self->{config} = $opts->{config};
3671 return $self;
3674 sub generate_diff {
3675 my ($tree_a, $tree_b) = @_;
3676 my @diff_tree = qw(diff-tree -z -r);
3677 if ($_cp_similarity) {
3678 push @diff_tree, "-C$_cp_similarity";
3679 } else {
3680 push @diff_tree, '-C';
3682 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3683 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3684 push @diff_tree, $tree_a, $tree_b;
3685 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3686 local $/ = "\0";
3687 my $state = 'meta';
3688 my @mods;
3689 while (<$diff_fh>) {
3690 chomp $_; # this gets rid of the trailing "\0"
3691 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3692 ($::sha1)\s($::sha1)\s
3693 ([MTCRAD])\d*$/xo) {
3694 push @mods, { mode_a => $1, mode_b => $2,
3695 sha1_a => $3, sha1_b => $4,
3696 chg => $5 };
3697 if ($5 =~ /^(?:C|R)$/) {
3698 $state = 'file_a';
3699 } else {
3700 $state = 'file_b';
3702 } elsif ($state eq 'file_a') {
3703 my $x = $mods[$#mods] or croak "Empty array\n";
3704 if ($x->{chg} !~ /^(?:C|R)$/) {
3705 croak "Error parsing $_, $x->{chg}\n";
3707 $x->{file_a} = $_;
3708 $state = 'file_b';
3709 } elsif ($state eq 'file_b') {
3710 my $x = $mods[$#mods] or croak "Empty array\n";
3711 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3712 croak "Error parsing $_, $x->{chg}\n";
3714 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3715 croak "Error parsing $_, $x->{chg}\n";
3717 $x->{file_b} = $_;
3718 $state = 'meta';
3719 } else {
3720 croak "Error parsing $_\n";
3723 command_close_pipe($diff_fh, $ctx);
3724 \@mods;
3727 sub check_diff_paths {
3728 my ($ra, $pfx, $rev, $mods) = @_;
3729 my %types;
3730 $pfx .= '/' if length $pfx;
3732 sub type_diff_paths {
3733 my ($ra, $types, $path, $rev) = @_;
3734 my @p = split m#/+#, $path;
3735 my $c = shift @p;
3736 unless (defined $types->{$c}) {
3737 $types->{$c} = $ra->check_path($c, $rev);
3739 while (@p) {
3740 $c .= '/' . shift @p;
3741 next if defined $types->{$c};
3742 $types->{$c} = $ra->check_path($c, $rev);
3746 foreach my $m (@$mods) {
3747 foreach my $f (qw/file_a file_b/) {
3748 next unless defined $m->{$f};
3749 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3750 if (length $pfx.$dir && ! defined $types{$dir}) {
3751 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3755 \%types;
3758 sub split_path {
3759 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3762 sub repo_path {
3763 my ($self, $path) = @_;
3764 $self->{path_prefix}.(defined $path ? $path : '');
3767 sub url_path {
3768 my ($self, $path) = @_;
3769 if ($self->{url} =~ m#^https?://#) {
3770 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3772 $self->{url} . '/' . $self->repo_path($path);
3775 sub rmdirs {
3776 my ($self) = @_;
3777 my $rm = $self->{rm};
3778 delete $rm->{''}; # we never delete the url we're tracking
3779 return unless %$rm;
3781 foreach (keys %$rm) {
3782 my @d = split m#/#, $_;
3783 my $c = shift @d;
3784 $rm->{$c} = 1;
3785 while (@d) {
3786 $c .= '/' . shift @d;
3787 $rm->{$c} = 1;
3790 delete $rm->{$self->{svn_path}};
3791 delete $rm->{''}; # we never delete the url we're tracking
3792 return unless %$rm;
3794 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3795 $self->{tree_b});
3796 local $/ = "\0";
3797 while (<$fh>) {
3798 chomp;
3799 my @dn = split m#/#, $_;
3800 while (pop @dn) {
3801 delete $rm->{join '/', @dn};
3803 unless (%$rm) {
3804 close $fh;
3805 return;
3808 command_close_pipe($fh, $ctx);
3810 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3811 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3812 $self->close_directory($bat->{$d}, $p);
3813 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3814 print "\tD+\t$d/\n" unless $::_q;
3815 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3816 delete $bat->{$d};
3820 sub open_or_add_dir {
3821 my ($self, $full_path, $baton) = @_;
3822 my $t = $self->{types}->{$full_path};
3823 if (!defined $t) {
3824 die "$full_path not known in r$self->{r} or we have a bug!\n";
3827 no warnings 'once';
3828 # SVN::Node::none and SVN::Node::file are used only once,
3829 # so we're shutting up Perl's warnings about them.
3830 if ($t == $SVN::Node::none) {
3831 return $self->add_directory($full_path, $baton,
3832 undef, -1, $self->{pool});
3833 } elsif ($t == $SVN::Node::dir) {
3834 return $self->open_directory($full_path, $baton,
3835 $self->{r}, $self->{pool});
3836 } # no warnings 'once'
3837 print STDERR "$full_path already exists in repository at ",
3838 "r$self->{r} and it is not a directory (",
3839 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3840 } # no warnings 'once'
3841 exit 1;
3844 sub ensure_path {
3845 my ($self, $path) = @_;
3846 my $bat = $self->{bat};
3847 my $repo_path = $self->repo_path($path);
3848 return $bat->{''} unless (length $repo_path);
3849 my @p = split m#/+#, $repo_path;
3850 my $c = shift @p;
3851 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3852 while (@p) {
3853 my $c0 = $c;
3854 $c .= '/' . shift @p;
3855 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3857 return $bat->{$c};
3860 # Subroutine to convert a globbing pattern to a regular expression.
3861 # From perl cookbook.
3862 sub glob2pat {
3863 my $globstr = shift;
3864 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3865 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3866 return '^' . $globstr . '$';
3869 sub check_autoprop {
3870 my ($self, $pattern, $properties, $file, $fbat) = @_;
3871 # Convert the globbing pattern to a regular expression.
3872 my $regex = glob2pat($pattern);
3873 # Check if the pattern matches the file name.
3874 if($file =~ m/($regex)/) {
3875 # Parse the list of properties to set.
3876 my @props = split(/;/, $properties);
3877 foreach my $prop (@props) {
3878 # Parse 'name=value' syntax and set the property.
3879 if ($prop =~ /([^=]+)=(.*)/) {
3880 my ($n,$v) = ($1,$2);
3881 for ($n, $v) {
3882 s/^\s+//; s/\s+$//;
3884 $self->change_file_prop($fbat, $n, $v);
3890 sub apply_autoprops {
3891 my ($self, $file, $fbat) = @_;
3892 my $conf_t = ${$self->{config}}{'config'};
3893 no warnings 'once';
3894 # Check [miscellany]/enable-auto-props in svn configuration.
3895 if (SVN::_Core::svn_config_get_bool(
3896 $conf_t,
3897 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3898 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3899 0)) {
3900 # Auto-props are enabled. Enumerate them to look for matches.
3901 my $callback = sub {
3902 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3904 SVN::_Core::svn_config_enumerate(
3905 $conf_t,
3906 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3907 $callback);
3911 sub A {
3912 my ($self, $m) = @_;
3913 my ($dir, $file) = split_path($m->{file_b});
3914 my $pbat = $self->ensure_path($dir);
3915 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3916 undef, -1);
3917 print "\tA\t$m->{file_b}\n" unless $::_q;
3918 $self->apply_autoprops($file, $fbat);
3919 $self->chg_file($fbat, $m);
3920 $self->close_file($fbat,undef,$self->{pool});
3923 sub C {
3924 my ($self, $m) = @_;
3925 my ($dir, $file) = split_path($m->{file_b});
3926 my $pbat = $self->ensure_path($dir);
3927 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3928 $self->url_path($m->{file_a}), $self->{r});
3929 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3930 $self->chg_file($fbat, $m);
3931 $self->close_file($fbat,undef,$self->{pool});
3934 sub delete_entry {
3935 my ($self, $path, $pbat) = @_;
3936 my $rpath = $self->repo_path($path);
3937 my ($dir, $file) = split_path($rpath);
3938 $self->{rm}->{$dir} = 1;
3939 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3942 sub R {
3943 my ($self, $m) = @_;
3944 my ($dir, $file) = split_path($m->{file_b});
3945 my $pbat = $self->ensure_path($dir);
3946 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3947 $self->url_path($m->{file_a}), $self->{r});
3948 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3949 $self->apply_autoprops($file, $fbat);
3950 $self->chg_file($fbat, $m);
3951 $self->close_file($fbat,undef,$self->{pool});
3953 ($dir, $file) = split_path($m->{file_a});
3954 $pbat = $self->ensure_path($dir);
3955 $self->delete_entry($m->{file_a}, $pbat);
3958 sub M {
3959 my ($self, $m) = @_;
3960 my ($dir, $file) = split_path($m->{file_b});
3961 my $pbat = $self->ensure_path($dir);
3962 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3963 $pbat,$self->{r},$self->{pool});
3964 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3965 $self->chg_file($fbat, $m);
3966 $self->close_file($fbat,undef,$self->{pool});
3969 sub T { shift->M(@_) }
3971 sub change_file_prop {
3972 my ($self, $fbat, $pname, $pval) = @_;
3973 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3976 sub _chg_file_get_blob ($$$$) {
3977 my ($self, $fbat, $m, $which) = @_;
3978 my $fh = $::_repository->temp_acquire("git_blob_$which");
3979 if ($m->{"mode_$which"} =~ /^120/) {
3980 print $fh 'link ' or croak $!;
3981 $self->change_file_prop($fbat,'svn:special','*');
3982 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3983 $self->change_file_prop($fbat,'svn:special',undef);
3985 my $blob = $m->{"sha1_$which"};
3986 return ($fh,) if ($blob =~ /^0{40}$/);
3987 my $size = $::_repository->cat_blob($blob, $fh);
3988 croak "Failed to read object $blob" if ($size < 0);
3989 $fh->flush == 0 or croak $!;
3990 seek $fh, 0, 0 or croak $!;
3992 my $exp = ::md5sum($fh);
3993 seek $fh, 0, 0 or croak $!;
3994 return ($fh, $exp);
3997 sub chg_file {
3998 my ($self, $fbat, $m) = @_;
3999 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4000 $self->change_file_prop($fbat,'svn:executable','*');
4001 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4002 $self->change_file_prop($fbat,'svn:executable',undef);
4004 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4005 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4006 my $pool = SVN::Pool->new;
4007 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4008 if (-s $fh_a) {
4009 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4010 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4011 if (defined $res) {
4012 die "Unexpected result from send_txstream: $res\n",
4013 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4015 } else {
4016 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4017 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4018 if ($got ne $exp_b);
4020 Git::temp_release($fh_b, 1);
4021 Git::temp_release($fh_a, 1);
4022 $pool->clear;
4025 sub D {
4026 my ($self, $m) = @_;
4027 my ($dir, $file) = split_path($m->{file_b});
4028 my $pbat = $self->ensure_path($dir);
4029 print "\tD\t$m->{file_b}\n" unless $::_q;
4030 $self->delete_entry($m->{file_b}, $pbat);
4033 sub close_edit {
4034 my ($self) = @_;
4035 my ($p,$bat) = ($self->{pool}, $self->{bat});
4036 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4037 next if $_ eq '';
4038 $self->close_directory($bat->{$_}, $p);
4040 $self->close_directory($bat->{''}, $p);
4041 $self->SUPER::close_edit($p);
4042 $p->clear;
4045 sub abort_edit {
4046 my ($self) = @_;
4047 $self->SUPER::abort_edit($self->{pool});
4050 sub DESTROY {
4051 my $self = shift;
4052 $self->SUPER::DESTROY(@_);
4053 $self->{pool}->clear;
4056 # this drives the editor
4057 sub apply_diff {
4058 my ($self) = @_;
4059 my $mods = $self->{mods};
4060 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4061 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4062 my $f = $m->{chg};
4063 if (defined $o{$f}) {
4064 $self->$f($m);
4065 } else {
4066 fatal("Invalid change type: $f");
4069 $self->rmdirs if $_rmdir;
4070 if (@$mods == 0) {
4071 $self->abort_edit;
4072 } else {
4073 $self->close_edit;
4075 return scalar @$mods;
4078 package Git::SVN::Ra;
4079 use vars qw/@ISA $config_dir $_log_window_size/;
4080 use strict;
4081 use warnings;
4082 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4084 BEGIN {
4085 # enforce temporary pool usage for some simple functions
4086 no strict 'refs';
4087 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4088 get_file/) {
4089 my $SUPER = "SUPER::$f";
4090 *$f = sub {
4091 my $self = shift;
4092 my $pool = SVN::Pool->new;
4093 my @ret = $self->$SUPER(@_,$pool);
4094 $pool->clear;
4095 wantarray ? @ret : $ret[0];
4100 sub _auth_providers () {
4102 SVN::Client::get_simple_provider(),
4103 SVN::Client::get_ssl_server_trust_file_provider(),
4104 SVN::Client::get_simple_prompt_provider(
4105 \&Git::SVN::Prompt::simple, 2),
4106 SVN::Client::get_ssl_client_cert_file_provider(),
4107 SVN::Client::get_ssl_client_cert_prompt_provider(
4108 \&Git::SVN::Prompt::ssl_client_cert, 2),
4109 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4110 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4111 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4112 SVN::Client::get_username_provider(),
4113 SVN::Client::get_ssl_server_trust_prompt_provider(
4114 \&Git::SVN::Prompt::ssl_server_trust),
4115 SVN::Client::get_username_prompt_provider(
4116 \&Git::SVN::Prompt::username, 2)
4120 sub escape_uri_only {
4121 my ($uri) = @_;
4122 my @tmp;
4123 foreach (split m{/}, $uri) {
4124 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4125 push @tmp, $_;
4127 join('/', @tmp);
4130 sub escape_url {
4131 my ($url) = @_;
4132 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4133 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4134 $url = "$scheme://$domain$uri";
4136 $url;
4139 sub new {
4140 my ($class, $url) = @_;
4141 $url =~ s!/+$!!;
4142 return $RA if ($RA && $RA->{url} eq $url);
4144 SVN::_Core::svn_config_ensure($config_dir, undef);
4145 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4146 my $config = SVN::Core::config_get_config($config_dir);
4147 $RA = undef;
4148 my $dont_store_passwords = 1;
4149 my $conf_t = ${$config}{'config'};
4151 no warnings 'once';
4152 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4153 # produces warnings that variables are used only once.
4154 # I had not found the better way to shut them up, so
4155 # the warnings of type 'once' are disabled in this block.
4156 if (SVN::_Core::svn_config_get_bool($conf_t,
4157 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4158 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4159 1) == 0) {
4160 SVN::_Core::svn_auth_set_parameter($baton,
4161 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4162 bless (\$dont_store_passwords, "_p_void"));
4164 if (SVN::_Core::svn_config_get_bool($conf_t,
4165 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4166 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4167 1) == 0) {
4168 $Git::SVN::Prompt::_no_auth_cache = 1;
4170 } # no warnings 'once'
4171 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4172 config => $config,
4173 pool => SVN::Pool->new,
4174 auth_provider_callbacks => $callbacks);
4175 $self->{url} = $url;
4176 $self->{svn_path} = $url;
4177 $self->{repos_root} = $self->get_repos_root;
4178 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4179 $self->{cache} = { check_path => { r => 0, data => {} },
4180 get_dir => { r => 0, data => {} } };
4181 $RA = bless $self, $class;
4184 sub check_path {
4185 my ($self, $path, $r) = @_;
4186 my $cache = $self->{cache}->{check_path};
4187 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4188 return $cache->{data}->{$path};
4190 my $pool = SVN::Pool->new;
4191 my $t = $self->SUPER::check_path($path, $r, $pool);
4192 $pool->clear;
4193 if ($r != $cache->{r}) {
4194 %{$cache->{data}} = ();
4195 $cache->{r} = $r;
4197 $cache->{data}->{$path} = $t;
4200 sub get_dir {
4201 my ($self, $dir, $r) = @_;
4202 my $cache = $self->{cache}->{get_dir};
4203 if ($r == $cache->{r}) {
4204 if (my $x = $cache->{data}->{$dir}) {
4205 return wantarray ? @$x : $x->[0];
4208 my $pool = SVN::Pool->new;
4209 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4210 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4211 $pool->clear;
4212 if ($r != $cache->{r}) {
4213 %{$cache->{data}} = ();
4214 $cache->{r} = $r;
4216 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4217 wantarray ? (\%dirents, $r, $props) : \%dirents;
4220 sub DESTROY {
4221 # do not call the real DESTROY since we store ourselves in $RA
4224 # get_log(paths, start, end, limit,
4225 # discover_changed_paths, strict_node_history, receiver)
4226 sub get_log {
4227 my ($self, @args) = @_;
4228 my $pool = SVN::Pool->new;
4230 # the limit parameter was not supported in SVN 1.1.x, so we
4231 # drop it. Therefore, the receiver callback passed to it
4232 # is made aware of this limitation by being wrapped if
4233 # the limit passed to is being wrapped.
4234 if ($SVN::Core::VERSION le '1.2.0') {
4235 my $limit = splice(@args, 3, 1);
4236 if ($limit > 0) {
4237 my $receiver = pop @args;
4238 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4241 my $ret = $self->SUPER::get_log(@args, $pool);
4242 $pool->clear;
4243 $ret;
4246 sub trees_match {
4247 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4248 my $ctx = SVN::Client->new(auth => _auth_providers);
4249 my $out = IO::File->new_tmpfile;
4251 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4252 # $ctx->diff(), so we'll create a default one
4253 my $pool = SVN::Pool->new_default_sub;
4255 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4256 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4257 $out->flush;
4258 my $ret = (($out->stat)[7] == 0);
4259 close $out or croak $!;
4261 $ret;
4264 sub get_commit_editor {
4265 my ($self, $log, $cb, $pool) = @_;
4266 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4267 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4270 sub gs_do_update {
4271 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4272 my $new = ($rev_a == $rev_b);
4273 my $path = $gs->{path};
4275 if ($new && -e $gs->{index}) {
4276 unlink $gs->{index} or die
4277 "Couldn't unlink index: $gs->{index}: $!\n";
4279 my $pool = SVN::Pool->new;
4280 $editor->set_path_strip($path);
4281 my (@pc) = split m#/#, $path;
4282 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4283 1, $editor, $pool);
4284 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4286 # Since we can't rely on svn_ra_reparent being available, we'll
4287 # just have to do some magic with set_path to make it so
4288 # we only want a partial path.
4289 my $sp = '';
4290 my $final = join('/', @pc);
4291 while (@pc) {
4292 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4293 $sp .= '/' if length $sp;
4294 $sp .= shift @pc;
4296 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4298 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4300 $reporter->finish_report($pool);
4301 $pool->clear;
4302 $editor->{git_commit_ok};
4305 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4306 # svn_ra_reparent didn't work before 1.4)
4307 sub gs_do_switch {
4308 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4309 my $path = $gs->{path};
4310 my $pool = SVN::Pool->new;
4312 my $full_url = $self->{url};
4313 my $old_url = $full_url;
4314 $full_url .= '/' . escape_uri_only($path) if length $path;
4315 my ($ra, $reparented);
4317 if ($old_url =~ m#^svn(\+ssh)?://#) {
4318 $_[0] = undef;
4319 $self = undef;
4320 $RA = undef;
4321 $ra = Git::SVN::Ra->new($full_url);
4322 $ra_invalid = 1;
4323 } elsif ($old_url ne $full_url) {
4324 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4325 $self->{url} = $full_url;
4326 $reparented = 1;
4329 $ra ||= $self;
4330 $url_b = escape_url($url_b);
4331 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4332 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4333 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4334 $reporter->finish_report($pool);
4336 if ($reparented) {
4337 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4338 $self->{url} = $old_url;
4341 $pool->clear;
4342 $editor->{git_commit_ok};
4345 sub longest_common_path {
4346 my ($gsv, $globs) = @_;
4347 my %common;
4348 my $common_max = scalar @$gsv;
4350 foreach my $gs (@$gsv) {
4351 my @tmp = split m#/#, $gs->{path};
4352 my $p = '';
4353 foreach (@tmp) {
4354 $p .= length($p) ? "/$_" : $_;
4355 $common{$p} ||= 0;
4356 $common{$p}++;
4359 $globs ||= [];
4360 $common_max += scalar @$globs;
4361 foreach my $glob (@$globs) {
4362 my @tmp = split m#/#, $glob->{path}->{left};
4363 my $p = '';
4364 foreach (@tmp) {
4365 $p .= length($p) ? "/$_" : $_;
4366 $common{$p} ||= 0;
4367 $common{$p}++;
4371 my $longest_path = '';
4372 foreach (sort {length $b <=> length $a} keys %common) {
4373 if ($common{$_} == $common_max) {
4374 $longest_path = $_;
4375 last;
4378 $longest_path;
4381 sub gs_fetch_loop_common {
4382 my ($self, $base, $head, $gsv, $globs) = @_;
4383 return if ($base > $head);
4384 my $inc = $_log_window_size;
4385 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4386 my $longest_path = longest_common_path($gsv, $globs);
4387 my $ra_url = $self->{url};
4388 while (1) {
4389 my %revs;
4390 my $err;
4391 my $err_handler = $SVN::Error::handler;
4392 $SVN::Error::handler = sub {
4393 ($err) = @_;
4394 skip_unknown_revs($err);
4396 sub _cb {
4397 my ($paths, $r, $author, $date, $log) = @_;
4398 [ dup_changed_paths($paths),
4399 { author => $author, date => $date, log => $log } ];
4401 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4402 sub { $revs{$_[1]} = _cb(@_) });
4403 if ($err) {
4404 print "Checked through r$max\r";
4406 if ($err && $max >= $head) {
4407 print STDERR "Path '$longest_path' ",
4408 "was probably deleted:\n",
4409 $err->expanded_message,
4410 "\nWill attempt to follow ",
4411 "revisions r$min .. r$max ",
4412 "committed before the deletion\n";
4413 my $hi = $max;
4414 while (--$hi >= $min) {
4415 my $ok;
4416 $self->get_log([$longest_path], $min, $hi,
4417 0, 1, 1, sub {
4418 $ok ||= $_[1];
4419 $revs{$_[1]} = _cb(@_) });
4420 if ($ok) {
4421 print STDERR "r$min .. r$ok OK\n";
4422 last;
4426 $SVN::Error::handler = $err_handler;
4428 my %exists = map { $_->{path} => $_ } @$gsv;
4429 foreach my $r (sort {$a <=> $b} keys %revs) {
4430 my ($paths, $logged) = @{$revs{$r}};
4432 foreach my $gs ($self->match_globs(\%exists, $paths,
4433 $globs, $r)) {
4434 if ($gs->rev_map_max >= $r) {
4435 next;
4437 next unless $gs->match_paths($paths, $r);
4438 $gs->{logged_rev_props} = $logged;
4439 if (my $last_commit = $gs->last_commit) {
4440 $gs->assert_index_clean($last_commit);
4442 my $log_entry = $gs->do_fetch($paths, $r);
4443 if ($log_entry) {
4444 $gs->do_git_commit($log_entry);
4446 $INDEX_FILES{$gs->{index}} = 1;
4448 foreach my $g (@$globs) {
4449 my $k = "svn-remote.$g->{remote}." .
4450 "$g->{t}-maxRev";
4451 Git::SVN::tmp_config($k, $r);
4453 if ($ra_invalid) {
4454 $_[0] = undef;
4455 $self = undef;
4456 $RA = undef;
4457 $self = Git::SVN::Ra->new($ra_url);
4458 $ra_invalid = undef;
4461 # pre-fill the .rev_db since it'll eventually get filled in
4462 # with '0' x40 if something new gets committed
4463 foreach my $gs (@$gsv) {
4464 next if $gs->rev_map_max >= $max;
4465 next if defined $gs->rev_map_get($max);
4466 $gs->rev_map_set($max, 0 x40);
4468 foreach my $g (@$globs) {
4469 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4470 Git::SVN::tmp_config($k, $max);
4472 last if $max >= $head;
4473 $min = $max + 1;
4474 $max += $inc;
4475 $max = $head if ($max > $head);
4477 Git::SVN::gc();
4480 sub get_dir_globbed {
4481 my ($self, $left, $depth, $r) = @_;
4483 my @x = eval { $self->get_dir($left, $r) };
4484 return unless scalar @x == 3;
4485 my $dirents = $x[0];
4486 my @finalents;
4487 foreach my $de (keys %$dirents) {
4488 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4489 if ($depth > 1) {
4490 my @args = ("$left/$de", $depth - 1, $r);
4491 foreach my $dir ($self->get_dir_globbed(@args)) {
4492 push @finalents, "$de/$dir";
4494 } else {
4495 push @finalents, $de;
4498 @finalents;
4501 sub match_globs {
4502 my ($self, $exists, $paths, $globs, $r) = @_;
4504 sub get_dir_check {
4505 my ($self, $exists, $g, $r) = @_;
4507 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4508 $g->{path}->{depth},
4509 $r);
4511 foreach my $de (@dirs) {
4512 my $p = $g->{path}->full_path($de);
4513 next if $exists->{$p};
4514 next if (length $g->{path}->{right} &&
4515 ($self->check_path($p, $r) !=
4516 $SVN::Node::dir));
4517 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4518 $g->{ref}->full_path($de), 1);
4521 foreach my $g (@$globs) {
4522 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4523 if ($path->{action} =~ /^[AR]$/) {
4524 get_dir_check($self, $exists, $g, $r);
4527 foreach (keys %$paths) {
4528 if (/$g->{path}->{left_regex}/ &&
4529 !/$g->{path}->{regex}/) {
4530 next if $paths->{$_}->{action} !~ /^[AR]$/;
4531 get_dir_check($self, $exists, $g, $r);
4533 next unless /$g->{path}->{regex}/;
4534 my $p = $1;
4535 my $pathname = $g->{path}->full_path($p);
4536 next if $exists->{$pathname};
4537 next if ($self->check_path($pathname, $r) !=
4538 $SVN::Node::dir);
4539 $exists->{$pathname} = Git::SVN->init(
4540 $self->{url}, $pathname, undef,
4541 $g->{ref}->full_path($p), 1);
4543 my $c = '';
4544 foreach (split m#/#, $g->{path}->{left}) {
4545 $c .= "/$_";
4546 next unless ($paths->{$c} &&
4547 ($paths->{$c}->{action} =~ /^[AR]$/));
4548 get_dir_check($self, $exists, $g, $r);
4551 values %$exists;
4554 sub minimize_url {
4555 my ($self) = @_;
4556 return $self->{url} if ($self->{url} eq $self->{repos_root});
4557 my $url = $self->{repos_root};
4558 my @components = split(m!/!, $self->{svn_path});
4559 my $c = '';
4560 do {
4561 $url .= "/$c" if length $c;
4562 eval { (ref $self)->new($url)->get_latest_revnum };
4563 } while ($@ && ($c = shift @components));
4564 $url;
4567 sub can_do_switch {
4568 my $self = shift;
4569 unless (defined $can_do_switch) {
4570 my $pool = SVN::Pool->new;
4571 my $rep = eval {
4572 $self->do_switch(1, '', 0, $self->{url},
4573 SVN::Delta::Editor->new, $pool);
4575 if ($@) {
4576 $can_do_switch = 0;
4577 } else {
4578 $rep->abort_report($pool);
4579 $can_do_switch = 1;
4581 $pool->clear;
4583 $can_do_switch;
4586 sub skip_unknown_revs {
4587 my ($err) = @_;
4588 my $errno = $err->apr_err();
4589 # Maybe the branch we're tracking didn't
4590 # exist when the repo started, so it's
4591 # not an error if it doesn't, just continue
4593 # Wonderfully consistent library, eh?
4594 # 160013 - svn:// and file://
4595 # 175002 - http(s)://
4596 # 175007 - http(s):// (this repo required authorization, too...)
4597 # More codes may be discovered later...
4598 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4599 my $err_key = $err->expanded_message;
4600 # revision numbers change every time, filter them out
4601 $err_key =~ s/\d+/\0/g;
4602 $err_key = "$errno\0$err_key";
4603 unless ($ignored_err{$err_key}) {
4604 warn "W: Ignoring error from SVN, path probably ",
4605 "does not exist: ($errno): ",
4606 $err->expanded_message,"\n";
4607 warn "W: Do not be alarmed at the above message ",
4608 "git-svn is just searching aggressively for ",
4609 "old history.\n",
4610 "This may take a while on large repositories\n";
4611 $ignored_err{$err_key} = 1;
4613 return;
4615 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4618 # svn_log_changed_path_t objects passed to get_log are likely to be
4619 # overwritten even if only the refs are copied to an external variable,
4620 # so we should dup the structures in their entirety. Using an externally
4621 # passed pool (instead of our temporary and quickly cleared pool in
4622 # Git::SVN::Ra) does not help matters at all...
4623 sub dup_changed_paths {
4624 my ($paths) = @_;
4625 return undef unless $paths;
4626 my %ret;
4627 foreach my $p (keys %$paths) {
4628 my $i = $paths->{$p};
4629 my %s = map { $_ => $i->$_ }
4630 qw/copyfrom_path copyfrom_rev action/;
4631 $ret{$p} = \%s;
4633 \%ret;
4636 package Git::SVN::Log;
4637 use strict;
4638 use warnings;
4639 use POSIX qw/strftime/;
4640 use Time::Local;
4641 use constant commit_log_separator => ('-' x 72) . "\n";
4642 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4643 %rusers $show_commit $incremental/;
4644 my $l_fmt;
4646 sub cmt_showable {
4647 my ($c) = @_;
4648 return 1 if defined $c->{r};
4650 # big commit message got truncated by the 16k pretty buffer in rev-list
4651 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4652 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4653 @{$c->{l}} = ();
4654 my @log = command(qw/cat-file commit/, $c->{c});
4656 # shift off the headers
4657 shift @log while ($log[0] ne '');
4658 shift @log;
4660 # TODO: make $c->{l} not have a trailing newline in the future
4661 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4663 (undef, $c->{r}, undef) = ::extract_metadata(
4664 (grep(/^git-svn-id: /, @log))[-1]);
4666 return defined $c->{r};
4669 sub log_use_color {
4670 return $color || Git->repository->get_colorbool('color.diff');
4673 sub git_svn_log_cmd {
4674 my ($r_min, $r_max, @args) = @_;
4675 my $head = 'HEAD';
4676 my (@files, @log_opts);
4677 foreach my $x (@args) {
4678 if ($x eq '--' || @files) {
4679 push @files, $x;
4680 } else {
4681 if (::verify_ref("$x^0")) {
4682 $head = $x;
4683 } else {
4684 push @log_opts, $x;
4689 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4690 $gs ||= Git::SVN->_new;
4691 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4692 $gs->refname);
4693 push @cmd, '-r' unless $non_recursive;
4694 push @cmd, qw/--raw --name-status/ if $verbose;
4695 push @cmd, '--color' if log_use_color();
4696 push @cmd, @log_opts;
4697 if (defined $r_max && $r_max == $r_min) {
4698 push @cmd, '--max-count=1';
4699 if (my $c = $gs->rev_map_get($r_max)) {
4700 push @cmd, $c;
4702 } elsif (defined $r_max) {
4703 if ($r_max < $r_min) {
4704 ($r_min, $r_max) = ($r_max, $r_min);
4706 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4707 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4708 # If there are no commits in the range, both $c_max and $c_min
4709 # will be undefined. If there is at least 1 commit in the
4710 # range, both will be defined.
4711 return () if !defined $c_min || !defined $c_max;
4712 if ($c_min eq $c_max) {
4713 push @cmd, '--max-count=1', $c_min;
4714 } else {
4715 push @cmd, '--boundary', "$c_min..$c_max";
4718 return (@cmd, @files);
4721 # adapted from pager.c
4722 sub config_pager {
4723 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4724 if (!defined $pager) {
4725 $pager = 'less';
4726 } elsif (length $pager == 0 || $pager eq 'cat') {
4727 $pager = undef;
4729 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4732 sub run_pager {
4733 return unless -t *STDOUT && defined $pager;
4734 pipe my ($rfd, $wfd) or return;
4735 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4736 if (!$pid) {
4737 open STDOUT, '>&', $wfd or
4738 ::fatal "Can't redirect to stdout: $!";
4739 return;
4741 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4742 $ENV{LESS} ||= 'FRSX';
4743 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4746 sub format_svn_date {
4747 # some systmes don't handle or mishandle %z, so be creative.
4748 my $t = shift || time;
4749 my $gm = timelocal(gmtime($t));
4750 my $sign = qw( + + - )[ $t <=> $gm ];
4751 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4752 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4755 sub parse_git_date {
4756 my ($t, $tz) = @_;
4757 # Date::Parse isn't in the standard Perl distro :(
4758 if ($tz =~ s/^\+//) {
4759 $t += tz_to_s_offset($tz);
4760 } elsif ($tz =~ s/^\-//) {
4761 $t -= tz_to_s_offset($tz);
4763 return $t;
4766 sub set_local_timezone {
4767 if (defined $TZ) {
4768 $ENV{TZ} = $TZ;
4769 } else {
4770 delete $ENV{TZ};
4774 sub tz_to_s_offset {
4775 my ($tz) = @_;
4776 $tz =~ s/(\d\d)$//;
4777 return ($1 * 60) + ($tz * 3600);
4780 sub get_author_info {
4781 my ($dest, $author, $t, $tz) = @_;
4782 $author =~ s/(?:^\s*|\s*$)//g;
4783 $dest->{a_raw} = $author;
4784 my $au;
4785 if ($::_authors) {
4786 $au = $rusers{$author} || undef;
4788 if (!$au) {
4789 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4791 $dest->{t} = $t;
4792 $dest->{tz} = $tz;
4793 $dest->{a} = $au;
4794 $dest->{t_utc} = parse_git_date($t, $tz);
4797 sub process_commit {
4798 my ($c, $r_min, $r_max, $defer) = @_;
4799 if (defined $r_min && defined $r_max) {
4800 if ($r_min == $c->{r} && $r_min == $r_max) {
4801 show_commit($c);
4802 return 0;
4804 return 1 if $r_min == $r_max;
4805 if ($r_min < $r_max) {
4806 # we need to reverse the print order
4807 return 0 if (defined $limit && --$limit < 0);
4808 push @$defer, $c;
4809 return 1;
4811 if ($r_min != $r_max) {
4812 return 1 if ($r_min < $c->{r});
4813 return 1 if ($r_max > $c->{r});
4816 return 0 if (defined $limit && --$limit < 0);
4817 show_commit($c);
4818 return 1;
4821 sub show_commit {
4822 my $c = shift;
4823 if ($oneline) {
4824 my $x = "\n";
4825 if (my $l = $c->{l}) {
4826 while ($l->[0] =~ /^\s*$/) { shift @$l }
4827 $x = $l->[0];
4829 $l_fmt ||= 'A' . length($c->{r});
4830 print 'r',pack($l_fmt, $c->{r}),' | ';
4831 print "$c->{c} | " if $show_commit;
4832 print $x;
4833 } else {
4834 show_commit_normal($c);
4838 sub show_commit_changed_paths {
4839 my ($c) = @_;
4840 return unless $c->{changed};
4841 print "Changed paths:\n", @{$c->{changed}};
4844 sub show_commit_normal {
4845 my ($c) = @_;
4846 print commit_log_separator, "r$c->{r} | ";
4847 print "$c->{c} | " if $show_commit;
4848 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4849 my $nr_line = 0;
4851 if (my $l = $c->{l}) {
4852 while ($l->[$#$l] eq "\n" && $#$l > 0
4853 && $l->[($#$l - 1)] eq "\n") {
4854 pop @$l;
4856 $nr_line = scalar @$l;
4857 if (!$nr_line) {
4858 print "1 line\n\n\n";
4859 } else {
4860 if ($nr_line == 1) {
4861 $nr_line = '1 line';
4862 } else {
4863 $nr_line .= ' lines';
4865 print $nr_line, "\n";
4866 show_commit_changed_paths($c);
4867 print "\n";
4868 print $_ foreach @$l;
4870 } else {
4871 print "1 line\n";
4872 show_commit_changed_paths($c);
4873 print "\n";
4876 foreach my $x (qw/raw stat diff/) {
4877 if ($c->{$x}) {
4878 print "\n";
4879 print $_ foreach @{$c->{$x}}
4884 sub cmd_show_log {
4885 my (@args) = @_;
4886 my ($r_min, $r_max);
4887 my $r_last = -1; # prevent dupes
4888 set_local_timezone();
4889 if (defined $::_revision) {
4890 if ($::_revision =~ /^(\d+):(\d+)$/) {
4891 ($r_min, $r_max) = ($1, $2);
4892 } elsif ($::_revision =~ /^\d+$/) {
4893 $r_min = $r_max = $::_revision;
4894 } else {
4895 ::fatal "-r$::_revision is not supported, use ",
4896 "standard 'git log' arguments instead";
4900 config_pager();
4901 @args = git_svn_log_cmd($r_min, $r_max, @args);
4902 if (!@args) {
4903 print commit_log_separator unless $incremental || $oneline;
4904 return;
4906 my $log = command_output_pipe(@args);
4907 run_pager();
4908 my (@k, $c, $d, $stat);
4909 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4910 while (<$log>) {
4911 if (/^${esc_color}commit -?($::sha1_short)/o) {
4912 my $cmt = $1;
4913 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4914 $r_last = $c->{r};
4915 process_commit($c, $r_min, $r_max, \@k) or
4916 goto out;
4918 $d = undef;
4919 $c = { c => $cmt };
4920 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4921 get_author_info($c, $1, $2, $3);
4922 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4923 # ignore
4924 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4925 push @{$c->{raw}}, $_;
4926 } elsif (/^${esc_color}[ACRMDT]\t/) {
4927 # we could add $SVN->{svn_path} here, but that requires
4928 # remote access at the moment (repo_path_split)...
4929 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4930 push @{$c->{changed}}, $_;
4931 } elsif (/^${esc_color}diff /o) {
4932 $d = 1;
4933 push @{$c->{diff}}, $_;
4934 } elsif ($d) {
4935 push @{$c->{diff}}, $_;
4936 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4937 $esc_color*[\+\-]*$esc_color$/x) {
4938 $stat = 1;
4939 push @{$c->{stat}}, $_;
4940 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4941 push @{$c->{stat}}, $_;
4942 $stat = undef;
4943 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4944 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4945 } elsif (s/^${esc_color} //o) {
4946 push @{$c->{l}}, $_;
4949 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4950 $r_last = $c->{r};
4951 process_commit($c, $r_min, $r_max, \@k);
4953 if (@k) {
4954 ($r_min, $r_max) = ($r_max, $r_min);
4955 process_commit($_, $r_min, $r_max) foreach reverse @k;
4957 out:
4958 close $log;
4959 print commit_log_separator unless $incremental || $oneline;
4962 sub cmd_blame {
4963 my $path = pop;
4965 config_pager();
4966 run_pager();
4968 my ($fh, $ctx, $rev);
4970 if ($_git_format) {
4971 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4972 while (my $line = <$fh>) {
4973 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4974 # Uncommitted edits show up as a rev ID of
4975 # all zeros, which we can't look up with
4976 # cmt_metadata
4977 if ($1 !~ /^0+$/) {
4978 (undef, $rev, undef) =
4979 ::cmt_metadata($1);
4980 $rev = '0' if (!$rev);
4981 } else {
4982 $rev = '0';
4984 $rev = sprintf('%-10s', $rev);
4985 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4987 print $line;
4989 } else {
4990 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4991 '--', $path);
4992 my ($sha1);
4993 my %authors;
4994 while (my $line = <$fh>) {
4995 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4996 $sha1 = $1;
4997 (undef, $rev, undef) = ::cmt_metadata($1);
4998 $rev = '0' if (!$rev);
5000 elsif ($line =~ /^author (.*)/) {
5001 $authors{$rev} = $1;
5002 $authors{$rev} =~ s/\s/_/g;
5004 elsif ($line =~ /^\t(.*)$/) {
5005 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5009 command_close_pipe($fh, $ctx);
5012 package Git::SVN::Migration;
5013 # these version numbers do NOT correspond to actual version numbers
5014 # of git nor git-svn. They are just relative.
5016 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5018 # v1 layout: .git/$id/info/url, refs/remotes/$id
5020 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5022 # v3 layout: .git/svn/$id, refs/remotes/$id
5023 # - info/url may remain for backwards compatibility
5024 # - this is what we migrate up to this layout automatically,
5025 # - this will be used by git svn init on single branches
5026 # v3.1 layout (auto migrated):
5027 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5028 # for backwards compatibility
5030 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5031 # - this is only created for newly multi-init-ed
5032 # repositories. Similar in spirit to the
5033 # --use-separate-remotes option in git-clone (now default)
5034 # - we do not automatically migrate to this (following
5035 # the example set by core git)
5037 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5038 # - newer, more-efficient format that uses 24-bytes per record
5039 # with no filler space.
5040 # - use xxd -c24 < .rev_map.$UUID to view and debug
5041 # - This is a one-way migration, repositories updated to the
5042 # new format will not be able to use old git-svn without
5043 # rebuilding the .rev_db. Rebuilding the rev_db is not
5044 # possible if noMetadata or useSvmProps are set; but should
5045 # be no problem for users that use the (sensible) defaults.
5046 use strict;
5047 use warnings;
5048 use Carp qw/croak/;
5049 use File::Path qw/mkpath/;
5050 use File::Basename qw/dirname basename/;
5051 use vars qw/$_minimize/;
5053 sub migrate_from_v0 {
5054 my $git_dir = $ENV{GIT_DIR};
5055 return undef unless -d $git_dir;
5056 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5057 my $migrated = 0;
5058 while (<$fh>) {
5059 chomp;
5060 my ($id, $orig_ref) = ($_, $_);
5061 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5062 next unless -f "$git_dir/$id/info/url";
5063 my $new_ref = "refs/remotes/$id";
5064 if (::verify_ref("$new_ref^0")) {
5065 print STDERR "W: $orig_ref is probably an old ",
5066 "branch used by an ancient version of ",
5067 "git-svn.\n",
5068 "However, $new_ref also exists.\n",
5069 "We will not be able ",
5070 "to use this branch until this ",
5071 "ambiguity is resolved.\n";
5072 next;
5074 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5075 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5076 command_noisy('update-ref', $new_ref, $orig_ref);
5077 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5078 $migrated++;
5080 command_close_pipe($fh, $ctx);
5081 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5082 $migrated;
5085 sub migrate_from_v1 {
5086 my $git_dir = $ENV{GIT_DIR};
5087 my $migrated = 0;
5088 return $migrated unless -d $git_dir;
5089 my $svn_dir = "$git_dir/svn";
5091 # just in case somebody used 'svn' as their $id at some point...
5092 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5094 print STDERR "Migrating from a git-svn v1 layout...\n";
5095 mkpath([$svn_dir]);
5096 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5097 "$svn_dir\n\t(required for this version ",
5098 "($::VERSION) of git-svn) does not exist.\n";
5099 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5100 while (<$fh>) {
5101 my $x = $_;
5102 next unless $x =~ s#^refs/remotes/##;
5103 chomp $x;
5104 next unless -f "$git_dir/$x/info/url";
5105 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5106 next unless $u;
5107 my $dn = dirname("$git_dir/svn/$x");
5108 mkpath([$dn]) unless -d $dn;
5109 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5110 mkpath(["$git_dir/svn/svn"]);
5111 print STDERR " - $git_dir/$x/info => ",
5112 "$git_dir/svn/$x/info\n";
5113 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5114 croak "$!: $x";
5115 # don't worry too much about these, they probably
5116 # don't exist with repos this old (save for index,
5117 # and we can easily regenerate that)
5118 foreach my $f (qw/unhandled.log index .rev_db/) {
5119 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5121 } else {
5122 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5123 rename "$git_dir/$x", "$git_dir/svn/$x" or
5124 croak "$!: $x";
5126 $migrated++;
5128 command_close_pipe($fh, $ctx);
5129 print STDERR "Done migrating from a git-svn v1 layout\n";
5130 $migrated;
5133 sub read_old_urls {
5134 my ($l_map, $pfx, $path) = @_;
5135 my @dir;
5136 foreach (<$path/*>) {
5137 if (-r "$_/info/url") {
5138 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5139 my $ref_id = $pfx . basename $_;
5140 my $url = ::file_to_s("$_/info/url");
5141 $l_map->{$ref_id} = $url;
5142 } elsif (-d $_) {
5143 push @dir, $_;
5146 foreach (@dir) {
5147 my $x = $_;
5148 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5149 read_old_urls($l_map, $x, $_);
5153 sub migrate_from_v2 {
5154 my @cfg = command(qw/config -l/);
5155 return if grep /^svn-remote\..+\.url=/, @cfg;
5156 my %l_map;
5157 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5158 my $migrated = 0;
5160 foreach my $ref_id (sort keys %l_map) {
5161 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5162 if ($@) {
5163 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5165 $migrated++;
5167 $migrated;
5170 sub minimize_connections {
5171 my $r = Git::SVN::read_all_remotes();
5172 my $new_urls = {};
5173 my $root_repos = {};
5174 foreach my $repo_id (keys %$r) {
5175 my $url = $r->{$repo_id}->{url} or next;
5176 my $fetch = $r->{$repo_id}->{fetch} or next;
5177 my $ra = Git::SVN::Ra->new($url);
5179 # skip existing cases where we already connect to the root
5180 if (($ra->{url} eq $ra->{repos_root}) ||
5181 ($ra->{repos_root} eq $repo_id)) {
5182 $root_repos->{$ra->{url}} = $repo_id;
5183 next;
5186 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5187 my $root_path = $ra->{url};
5188 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5189 foreach my $path (keys %$fetch) {
5190 my $ref_id = $fetch->{$path};
5191 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5193 # make sure we can read when connecting to
5194 # a higher level of a repository
5195 my ($last_rev, undef) = $gs->last_rev_commit;
5196 if (!defined $last_rev) {
5197 $last_rev = eval {
5198 $root_ra->get_latest_revnum;
5200 next if $@;
5202 my $new = $root_path;
5203 $new .= length $path ? "/$path" : '';
5204 eval {
5205 $root_ra->get_log([$new], $last_rev, $last_rev,
5206 0, 0, 1, sub { });
5208 next if $@;
5209 $new_urls->{$ra->{repos_root}}->{$new} =
5210 { ref_id => $ref_id,
5211 old_repo_id => $repo_id,
5212 old_path => $path };
5216 my @emptied;
5217 foreach my $url (keys %$new_urls) {
5218 # see if we can re-use an existing [svn-remote "repo_id"]
5219 # instead of creating a(n ugly) new section:
5220 my $repo_id = $root_repos->{$url} || $url;
5222 my $fetch = $new_urls->{$url};
5223 foreach my $path (keys %$fetch) {
5224 my $x = $fetch->{$path};
5225 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5226 my $pfx = "svn-remote.$x->{old_repo_id}";
5228 my $old_fetch = quotemeta("$x->{old_path}:".
5229 "refs/remotes/$x->{ref_id}");
5230 command_noisy(qw/config --unset/,
5231 "$pfx.fetch", '^'. $old_fetch . '$');
5232 delete $r->{$x->{old_repo_id}}->
5233 {fetch}->{$x->{old_path}};
5234 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5235 command_noisy(qw/config --unset/,
5236 "$pfx.url");
5237 push @emptied, $x->{old_repo_id}
5241 if (@emptied) {
5242 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5243 print STDERR <<EOF;
5244 The following [svn-remote] sections in your config file ($file) are empty
5245 and can be safely removed:
5247 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5251 sub migration_check {
5252 migrate_from_v0();
5253 migrate_from_v1();
5254 migrate_from_v2();
5255 minimize_connections() if $_minimize;
5258 package Git::IndexInfo;
5259 use strict;
5260 use warnings;
5261 use Git qw/command_input_pipe command_close_pipe/;
5263 sub new {
5264 my ($class) = @_;
5265 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5266 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5269 sub remove {
5270 my ($self, $path) = @_;
5271 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5272 return ++$self->{nr};
5274 undef;
5277 sub update {
5278 my ($self, $mode, $hash, $path) = @_;
5279 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5280 return ++$self->{nr};
5282 undef;
5285 sub DESTROY {
5286 my ($self) = @_;
5287 command_close_pipe($self->{gui}, $self->{ctx});
5290 package Git::SVN::GlobSpec;
5291 use strict;
5292 use warnings;
5294 sub new {
5295 my ($class, $glob) = @_;
5296 my $re = $glob;
5297 $re =~ s!/+$!!g; # no need for trailing slashes
5298 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5299 my $temp = $re;
5300 my ($left, $right) = ($1, $3);
5301 $re = $2;
5302 my $depth = $re =~ tr/*/*/;
5303 if ($depth != $temp =~ tr/*/*/) {
5304 die "Only one set of wildcard directories " .
5305 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5307 if ($depth == 0) {
5308 die "One '*' is needed for glob: '$glob'\n";
5310 $re =~ s!\*!\[^/\]*!g;
5311 $re = quotemeta($left) . "($re)" . quotemeta($right);
5312 if (length $left && !($left =~ s!/+$!!g)) {
5313 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5315 if (length $right && !($right =~ s!^/+!!g)) {
5316 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5318 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5319 bless { left => $left, right => $right, left_regex => $left_re,
5320 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5323 sub full_path {
5324 my ($self, $path) = @_;
5325 return (length $self->{left} ? "$self->{left}/" : '') .
5326 $path . (length $self->{right} ? "/$self->{right}" : '');
5329 __END__
5331 Data structures:
5334 $remotes = { # returned by read_all_remotes()
5335 'svn' => {
5336 # svn-remote.svn.url=https://svn.musicpd.org
5337 url => 'https://svn.musicpd.org',
5338 # svn-remote.svn.fetch=mpd/trunk:trunk
5339 fetch => {
5340 'mpd/trunk' => 'trunk',
5342 # svn-remote.svn.tags=mpd/tags/*:tags/*
5343 tags => {
5344 path => {
5345 left => 'mpd/tags',
5346 right => '',
5347 regex => qr!mpd/tags/([^/]+)$!,
5348 glob => 'tags/*',
5350 ref => {
5351 left => 'tags',
5352 right => '',
5353 regex => qr!tags/([^/]+)$!,
5354 glob => 'tags/*',
5360 $log_entry hashref as returned by libsvn_log_entry()
5362 log => 'whitespace-formatted log entry
5363 ', # trailing newline is preserved
5364 revision => '8', # integer
5365 date => '2004-02-24T17:01:44.108345Z', # commit date
5366 author => 'committer name'
5370 # this is generated by generate_diff();
5371 @mods = array of diff-index line hashes, each element represents one line
5372 of diff-index output
5374 diff-index line ($m hash)
5376 mode_a => first column of diff-index output, no leading ':',
5377 mode_b => second column of diff-index output,
5378 sha1_b => sha1sum of the final blob,
5379 chg => change type [MCRADT],
5380 file_a => original file name of a file (iff chg is 'C' or 'R')
5381 file_b => new/current file name of a file (any chg)
5385 # retval of read_url_paths{,_all}();
5386 $l_map = {
5387 # repository root url
5388 'https://svn.musicpd.org' => {
5389 # repository path # GIT_SVN_ID
5390 'mpd/trunk' => 'trunk',
5391 'mpd/tags/0.11.5' => 'tags/0.11.5',
5395 Notes:
5396 I don't trust the each() function on unless I created %hash myself
5397 because the internal iterator may not have started at base.