git-svn: support for funky branch and project names over HTTP(S)
[alt-git.git] / git-svn.perl
blob858c5be107dfb9d60110c2cd1d521cd5ea84c411
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
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41 # import functions from Git into our packages, en masse
42 no strict 'refs';
43 foreach (qw/command command_oneline command_noisy command_output_pipe
44 command_input_pipe command_close_pipe/) {
45 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
46 Git::SVN::Migration Git::SVN::Log Git::SVN),
47 __PACKAGE__) {
48 *{"${package}::$_"} = \&{"Git::$_"};
53 my ($SVN);
55 $sha1 = qr/[a-f\d]{40}/;
56 $sha1_short = qr/[a-f\d]{4,40}/;
57 my ($_stdin, $_help, $_edit,
58 $_message, $_file,
59 $_template, $_shared,
60 $_version, $_fetch_all, $_no_rebase,
61 $_merge, $_strategy, $_dry_run, $_local,
62 $_prefix, $_no_checkout, $_verbose);
63 $Git::SVN::_follow_parent = 1;
64 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
65 'config-dir=s' => \$Git::SVN::Ra::config_dir,
66 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
67 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
68 'authors-file|A=s' => \$_authors,
69 'repack:i' => \$Git::SVN::_repack,
70 'noMetadata' => \$Git::SVN::_no_metadata,
71 'useSvmProps' => \$Git::SVN::_use_svm_props,
72 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
73 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
74 'no-checkout' => \$_no_checkout,
75 'quiet|q' => \$_q,
76 'repack-flags|repack-args|repack-opts=s' =>
77 \$Git::SVN::_repack_flags,
78 %remote_opts );
80 my ($_trunk, $_tags, $_branches, $_stdlayout);
81 my %icv;
82 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
83 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
84 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
85 'stdlayout|s' => \$_stdlayout,
86 'minimize-url|m' => \$Git::SVN::_minimize_url,
87 'no-metadata' => sub { $icv{noMetadata} = 1 },
88 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
89 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
90 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
91 %remote_opts );
92 my %cmt_opts = ( 'edit|e' => \$_edit,
93 'rmdir' => \$SVN::Git::Editor::_rmdir,
94 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
95 'l=i' => \$SVN::Git::Editor::_rename_limit,
96 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
99 my %cmd = (
100 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
101 { 'revision|r=s' => \$_revision,
102 'fetch-all|all' => \$_fetch_all,
103 %fc_opts } ],
104 clone => [ \&cmd_clone, "Initialize and fetch revisions",
105 { 'revision|r=s' => \$_revision,
106 %fc_opts, %init_opts } ],
107 init => [ \&cmd_init, "Initialize a repo for tracking" .
108 " (requires URL argument)",
109 \%init_opts ],
110 'multi-init' => [ \&cmd_multi_init,
111 "Deprecated alias for ".
112 "'$0 init -T<trunk> -b<branches> -t<tags>'",
113 \%init_opts ],
114 dcommit => [ \&cmd_dcommit,
115 'Commit several diffs to merge with upstream',
116 { 'merge|m|M' => \$_merge,
117 'strategy|s=s' => \$_strategy,
118 'verbose|v' => \$_verbose,
119 'dry-run|n' => \$_dry_run,
120 'fetch-all|all' => \$_fetch_all,
121 'no-rebase' => \$_no_rebase,
122 %cmt_opts, %fc_opts } ],
123 'set-tree' => [ \&cmd_set_tree,
124 "Set an SVN repository to a git tree-ish",
125 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
126 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
127 { 'revision|r=i' => \$_revision } ],
128 'multi-fetch' => [ \&cmd_multi_fetch,
129 "Deprecated alias for $0 fetch --all",
130 { 'revision|r=s' => \$_revision, %fc_opts } ],
131 'migrate' => [ sub { },
132 # no-op, we automatically run this anyways,
133 'Migrate configuration/metadata/layout from
134 previous versions of git-svn',
135 { 'minimize' => \$Git::SVN::Migration::_minimize,
136 %remote_opts } ],
137 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
138 { 'limit=i' => \$Git::SVN::Log::limit,
139 'revision|r=s' => \$_revision,
140 'verbose|v' => \$Git::SVN::Log::verbose,
141 'incremental' => \$Git::SVN::Log::incremental,
142 'oneline' => \$Git::SVN::Log::oneline,
143 'show-commit' => \$Git::SVN::Log::show_commit,
144 'non-recursive' => \$Git::SVN::Log::non_recursive,
145 'authors-file|A=s' => \$_authors,
146 'color' => \$Git::SVN::Log::color,
147 'pager=s' => \$Git::SVN::Log::pager,
148 } ],
149 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
150 { } ],
151 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
152 { 'merge|m|M' => \$_merge,
153 'verbose|v' => \$_verbose,
154 'strategy|s=s' => \$_strategy,
155 'local|l' => \$_local,
156 'fetch-all|all' => \$_fetch_all,
157 %fc_opts } ],
158 'commit-diff' => [ \&cmd_commit_diff,
159 'Commit a diff between two trees',
160 { 'message|m=s' => \$_message,
161 'file|F=s' => \$_file,
162 'revision|r=s' => \$_revision,
163 %cmt_opts } ],
166 my $cmd;
167 for (my $i = 0; $i < @ARGV; $i++) {
168 if (defined $cmd{$ARGV[$i]}) {
169 $cmd = $ARGV[$i];
170 splice @ARGV, $i, 1;
171 last;
175 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
177 read_repo_config(\%opts);
178 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
180 'minimize-connections' => \$Git::SVN::Migration::_minimize,
181 'id|i=s' => \$Git::SVN::default_ref_id,
182 'svn-remote|remote|R=s' => sub {
183 $Git::SVN::no_reuse_existing = 1;
184 $Git::SVN::default_repo_id = $_[1] });
185 exit 1 if (!$rv && $cmd && $cmd ne 'log');
187 usage(0) if $_help;
188 version() if $_version;
189 usage(1) unless defined $cmd;
190 load_authors() if $_authors;
192 # make sure we're always running
193 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
194 unless (-d $ENV{GIT_DIR}) {
195 if ($git_dir_user_set) {
196 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
197 "but it is not a directory\n";
199 my $git_dir = delete $ENV{GIT_DIR};
200 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
201 unless (length $cdup) {
202 die "Already at toplevel, but $git_dir ",
203 "not found '$cdup'\n";
205 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
206 unless (-d $git_dir) {
207 die "$git_dir still not found after going to ",
208 "'$cdup'\n";
210 $ENV{GIT_DIR} = $git_dir;
213 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
214 Git::SVN::Migration::migration_check();
216 Git::SVN::init_vars();
217 eval {
218 Git::SVN::verify_remotes_sanity();
219 $cmd{$cmd}->[0]->(@ARGV);
221 fatal $@ if $@;
222 post_fetch_checkout();
223 exit 0;
225 ####################### primary functions ######################
226 sub usage {
227 my $exit = shift || 0;
228 my $fd = $exit ? \*STDERR : \*STDOUT;
229 print $fd <<"";
230 git-svn - bidirectional operations between a single Subversion tree and git
231 Usage: $0 <command> [options] [arguments]\n
233 print $fd "Available commands:\n" unless $cmd;
235 foreach (sort keys %cmd) {
236 next if $cmd && $cmd ne $_;
237 next if /^multi-/; # don't show deprecated commands
238 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
239 foreach (keys %{$cmd{$_}->[2]}) {
240 # mixed-case options are for .git/config only
241 next if /[A-Z]/ && /^[a-z]+$/i;
242 # prints out arguments as they should be passed:
243 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
244 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
245 "--$_" : "-$_" }
246 split /\|/,$_)," $x\n";
249 print $fd <<"";
250 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
251 arbitrary identifier if you're tracking multiple SVN branches/repositories in
252 one git repository and want to keep them separate. See git-svn(1) for more
253 information.
255 exit $exit;
258 sub version {
259 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
260 exit 0;
263 sub do_git_init_db {
264 unless (-d $ENV{GIT_DIR}) {
265 my @init_db = ('init');
266 push @init_db, "--template=$_template" if defined $_template;
267 if (defined $_shared) {
268 if ($_shared =~ /[a-z]/) {
269 push @init_db, "--shared=$_shared";
270 } else {
271 push @init_db, "--shared";
274 command_noisy(@init_db);
276 my $set;
277 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
278 foreach my $i (keys %icv) {
279 die "'$set' and '$i' cannot both be set\n" if $set;
280 next unless defined $icv{$i};
281 command_noisy('config', "$pfx.$i", $icv{$i});
282 $set = $i;
286 sub init_subdir {
287 my $repo_path = shift or return;
288 mkpath([$repo_path]) unless -d $repo_path;
289 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
290 $ENV{GIT_DIR} = '.git';
293 sub cmd_clone {
294 my ($url, $path) = @_;
295 if (!defined $path &&
296 (defined $_trunk || defined $_branches || defined $_tags ||
297 defined $_stdlayout) &&
298 $url !~ m#^[a-z\+]+://#) {
299 $path = $url;
301 $path = basename($url) if !defined $path || !length $path;
302 cmd_init($url, $path);
303 Git::SVN::fetch_all($Git::SVN::default_repo_id);
306 sub cmd_init {
307 if (defined $_stdlayout) {
308 $_trunk = 'trunk' if (!defined $_trunk);
309 $_tags = 'tags' if (!defined $_tags);
310 $_branches = 'branches' if (!defined $_branches);
312 if (defined $_trunk || defined $_branches || defined $_tags) {
313 return cmd_multi_init(@_);
315 my $url = shift or die "SVN repository location required ",
316 "as a command-line argument\n";
317 init_subdir(@_);
318 do_git_init_db();
320 Git::SVN->init($url);
323 sub cmd_fetch {
324 if (grep /^\d+=./, @_) {
325 die "'<rev>=<commit>' fetch arguments are ",
326 "no longer supported.\n";
328 my ($remote) = @_;
329 if (@_ > 1) {
330 die "Usage: $0 fetch [--all] [svn-remote]\n";
332 $remote ||= $Git::SVN::default_repo_id;
333 if ($_fetch_all) {
334 cmd_multi_fetch();
335 } else {
336 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
340 sub cmd_set_tree {
341 my (@commits) = @_;
342 if ($_stdin || !@commits) {
343 print "Reading from stdin...\n";
344 @commits = ();
345 while (<STDIN>) {
346 if (/\b($sha1_short)\b/o) {
347 unshift @commits, $1;
351 my @revs;
352 foreach my $c (@commits) {
353 my @tmp = command('rev-parse',$c);
354 if (scalar @tmp == 1) {
355 push @revs, $tmp[0];
356 } elsif (scalar @tmp > 1) {
357 push @revs, reverse(command('rev-list',@tmp));
358 } else {
359 fatal "Failed to rev-parse $c\n";
362 my $gs = Git::SVN->new;
363 my ($r_last, $cmt_last) = $gs->last_rev_commit;
364 $gs->fetch;
365 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
366 fatal "There are new revisions that were fetched ",
367 "and need to be merged (or acknowledged) ",
368 "before committing.\nlast rev: $r_last\n",
369 " current: $gs->{last_rev}\n";
371 $gs->set_tree($_) foreach @revs;
372 print "Done committing ",scalar @revs," revisions to SVN\n";
375 sub cmd_dcommit {
376 my $head = shift;
377 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
378 'Cannot dcommit with a dirty index. Commit your changes first'
379 . "or stash them with `git stash'.\n";
380 $head ||= 'HEAD';
381 my @refs;
382 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
383 print "Committing to $url ...\n";
384 unless ($gs) {
385 die "Unable to determine upstream SVN information from ",
386 "$head history\n";
388 my $last_rev;
389 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
390 if ($_no_rebase && scalar(@$linear_refs) > 1) {
391 warn "Attempting to commit more than one change while ",
392 "--no-rebase is enabled.\n",
393 "If these changes depend on each other, re-running ",
394 "without --no-rebase will be required."
396 while (1) {
397 my $d = shift @$linear_refs or last;
398 unless (defined $last_rev) {
399 (undef, $last_rev, undef) = cmt_metadata("$d~1");
400 unless (defined $last_rev) {
401 fatal "Unable to extract revision information ",
402 "from commit $d~1\n";
405 if ($_dry_run) {
406 print "diff-tree $d~1 $d\n";
407 } else {
408 my $cmt_rev;
409 my %ed_opts = ( r => $last_rev,
410 log => get_commit_entry($d)->{log},
411 ra => Git::SVN::Ra->new($gs->full_url),
412 tree_a => "$d~1",
413 tree_b => $d,
414 editor_cb => sub {
415 print "Committed r$_[0]\n";
416 $cmt_rev = $_[0];
418 svn_path => '');
419 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
420 print "No changes\n$d~1 == $d\n";
421 } elsif ($parents->{$d} && @{$parents->{$d}}) {
422 $gs->{inject_parents_dcommit}->{$cmt_rev} =
423 $parents->{$d};
425 $_fetch_all ? $gs->fetch_all : $gs->fetch;
426 next if $_no_rebase;
428 # we always want to rebase against the current HEAD,
429 # not any head that was passed to us
430 my @diff = command('diff-tree', $d,
431 $gs->refname, '--');
432 my @finish;
433 if (@diff) {
434 @finish = rebase_cmd();
435 print STDERR "W: $d and ", $gs->refname,
436 " differ, using @finish:\n",
437 join("\n", @diff), "\n";
438 } else {
439 print "No changes between current HEAD and ",
440 $gs->refname,
441 "\nResetting to the latest ",
442 $gs->refname, "\n";
443 @finish = qw/reset --mixed/;
445 command_noisy(@finish, $gs->refname);
446 if (@diff) {
447 @refs = ();
448 my ($url_, $rev_, $uuid_, $gs_) =
449 working_head_info($head, \@refs);
450 my ($linear_refs_, $parents_) =
451 linearize_history($gs_, \@refs);
452 if (scalar(@$linear_refs) !=
453 scalar(@$linear_refs_)) {
454 fatal "# of revisions changed ",
455 "\nbefore:\n",
456 join("\n", @$linear_refs),
457 "\n\nafter:\n",
458 join("\n", @$linear_refs_), "\n",
459 'If you are attempting to commit ',
460 "merges, try running:\n\t",
461 'git rebase --interactive',
462 '--preserve-merges ',
463 $gs->refname,
464 "\nBefore dcommitting";
466 if ($url_ ne $url) {
467 fatal "URL mismatch after rebase: ",
468 "$url_ != $url";
470 if ($uuid_ ne $uuid) {
471 fatal "uuid mismatch after rebase: ",
472 "$uuid_ != $uuid";
474 # remap parents
475 my (%p, @l, $i);
476 for ($i = 0; $i < scalar @$linear_refs; $i++) {
477 my $new = $linear_refs_->[$i] or next;
478 $p{$new} =
479 $parents->{$linear_refs->[$i]};
480 push @l, $new;
482 $parents = \%p;
483 $linear_refs = \@l;
485 $last_rev = $cmt_rev;
490 sub cmd_find_rev {
491 my $revision_or_hash = shift;
492 my $result;
493 if ($revision_or_hash =~ /^r\d+$/) {
494 my $head = shift;
495 $head ||= 'HEAD';
496 my @refs;
497 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
498 unless ($gs) {
499 die "Unable to determine upstream SVN information from ",
500 "$head history\n";
502 my $desired_revision = substr($revision_or_hash, 1);
503 $result = $gs->rev_db_get($desired_revision);
504 } else {
505 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
506 $result = $rev;
508 print "$result\n" if $result;
511 sub cmd_rebase {
512 command_noisy(qw/update-index --refresh/);
513 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
514 unless ($gs) {
515 die "Unable to determine upstream SVN information from ",
516 "working tree history\n";
518 if (command(qw/diff-index HEAD --/)) {
519 print STDERR "Cannot rebase with uncommited changes:\n";
520 command_noisy('status');
521 exit 1;
523 unless ($_local) {
524 $_fetch_all ? $gs->fetch_all : $gs->fetch;
526 command_noisy(rebase_cmd(), $gs->refname);
529 sub cmd_show_ignore {
530 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
531 $gs ||= Git::SVN->new;
532 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
533 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
536 sub cmd_multi_init {
537 my $url = shift;
538 unless (defined $_trunk || defined $_branches || defined $_tags) {
539 usage(1);
542 # there are currently some bugs that prevent multi-init/multi-fetch
543 # setups from working well without this.
544 $Git::SVN::_minimize_url = 1;
546 $_prefix = '' unless defined $_prefix;
547 if (defined $url) {
548 $url =~ s#/+$##;
549 init_subdir(@_);
551 do_git_init_db();
552 if (defined $_trunk) {
553 my $trunk_ref = $_prefix . 'trunk';
554 # try both old-style and new-style lookups:
555 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
556 unless ($gs_trunk) {
557 my ($trunk_url, $trunk_path) =
558 complete_svn_url($url, $_trunk);
559 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
560 undef, $trunk_ref);
563 return unless defined $_branches || defined $_tags;
564 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
565 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
566 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
569 sub cmd_multi_fetch {
570 my $remotes = Git::SVN::read_all_remotes();
571 foreach my $repo_id (sort keys %$remotes) {
572 if ($remotes->{$repo_id}->{url}) {
573 Git::SVN::fetch_all($repo_id, $remotes);
578 # this command is special because it requires no metadata
579 sub cmd_commit_diff {
580 my ($ta, $tb, $url) = @_;
581 my $usage = "Usage: $0 commit-diff -r<revision> ".
582 "<tree-ish> <tree-ish> [<URL>]\n";
583 fatal($usage) if (!defined $ta || !defined $tb);
584 my $svn_path;
585 if (!defined $url) {
586 my $gs = eval { Git::SVN->new };
587 if (!$gs) {
588 fatal("Needed URL or usable git-svn --id in ",
589 "the command-line\n", $usage);
591 $url = $gs->{url};
592 $svn_path = $gs->{path};
594 unless (defined $_revision) {
595 fatal("-r|--revision is a required argument\n", $usage);
597 if (defined $_message && defined $_file) {
598 fatal("Both --message/-m and --file/-F specified ",
599 "for the commit message.\n",
600 "I have no idea what you mean\n");
602 if (defined $_file) {
603 $_message = file_to_s($_file);
604 } else {
605 $_message ||= get_commit_entry($tb)->{log};
607 my $ra ||= Git::SVN::Ra->new($url);
608 $svn_path ||= $ra->{svn_path};
609 my $r = $_revision;
610 if ($r eq 'HEAD') {
611 $r = $ra->get_latest_revnum;
612 } elsif ($r !~ /^\d+$/) {
613 die "revision argument: $r not understood by git-svn\n";
615 my %ed_opts = ( r => $r,
616 log => $_message,
617 ra => $ra,
618 tree_a => $ta,
619 tree_b => $tb,
620 editor_cb => sub { print "Committed r$_[0]\n" },
621 svn_path => $svn_path );
622 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
623 print "No changes\n$ta == $tb\n";
627 ########################### utility functions #########################
629 sub rebase_cmd {
630 my @cmd = qw/rebase/;
631 push @cmd, '-v' if $_verbose;
632 push @cmd, qw/--merge/ if $_merge;
633 push @cmd, "--strategy=$_strategy" if $_strategy;
634 @cmd;
637 sub post_fetch_checkout {
638 return if $_no_checkout;
639 my $gs = $Git::SVN::_head or return;
640 return if verify_ref('refs/heads/master^0');
642 my $valid_head = verify_ref('HEAD^0');
643 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
644 return if ($valid_head || !verify_ref('HEAD^0'));
646 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
647 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
648 return if -f $index;
650 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
651 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
652 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
653 print STDERR "Checked out HEAD:\n ",
654 $gs->full_url, " r", $gs->last_rev, "\n";
657 sub complete_svn_url {
658 my ($url, $path) = @_;
659 $path =~ s#/+$##;
660 if ($path !~ m#^[a-z\+]+://#) {
661 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
662 fatal("E: '$path' is not a complete URL ",
663 "and a separate URL is not specified\n");
665 return ($url, $path);
667 return ($path, '');
670 sub complete_url_ls_init {
671 my ($ra, $repo_path, $switch, $pfx) = @_;
672 unless ($repo_path) {
673 print STDERR "W: $switch not specified\n";
674 return;
676 $repo_path =~ s#/+$##;
677 if ($repo_path =~ m#^[a-z\+]+://#) {
678 $ra = Git::SVN::Ra->new($repo_path);
679 $repo_path = '';
680 } else {
681 $repo_path =~ s#^/+##;
682 unless ($ra) {
683 fatal("E: '$repo_path' is not a complete URL ",
684 "and a separate URL is not specified\n");
687 my $url = $ra->{url};
688 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
689 my $k = "svn-remote.$gs->{repo_id}.url";
690 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
691 if ($orig_url && ($orig_url ne $gs->{url})) {
692 die "$k already set: $orig_url\n",
693 "wanted to set to: $gs->{url}\n";
695 command_oneline('config', $k, $gs->{url}) unless $orig_url;
696 my $remote_path = "$ra->{svn_path}/$repo_path/*";
697 $remote_path =~ s#/+#/#g;
698 $remote_path =~ s#^/##g;
699 my ($n) = ($switch =~ /^--(\w+)/);
700 if (length $pfx && $pfx !~ m#/$#) {
701 die "--prefix='$pfx' must have a trailing slash '/'\n";
703 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
704 "$remote_path:refs/remotes/$pfx*");
707 sub verify_ref {
708 my ($ref) = @_;
709 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
710 { STDERR => 0 }); };
713 sub get_tree_from_treeish {
714 my ($treeish) = @_;
715 # $treeish can be a symbolic ref, too:
716 my $type = command_oneline(qw/cat-file -t/, $treeish);
717 my $expected;
718 while ($type eq 'tag') {
719 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
721 if ($type eq 'commit') {
722 $expected = (grep /^tree /, command(qw/cat-file commit/,
723 $treeish))[0];
724 ($expected) = ($expected =~ /^tree ($sha1)$/o);
725 die "Unable to get tree from $treeish\n" unless $expected;
726 } elsif ($type eq 'tree') {
727 $expected = $treeish;
728 } else {
729 die "$treeish is a $type, expected tree, tag or commit\n";
731 return $expected;
734 sub get_commit_entry {
735 my ($treeish) = shift;
736 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
737 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
738 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
739 open my $log_fh, '>', $commit_editmsg or croak $!;
741 my $type = command_oneline(qw/cat-file -t/, $treeish);
742 if ($type eq 'commit' || $type eq 'tag') {
743 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
744 $type, $treeish);
745 my $in_msg = 0;
746 while (<$msg_fh>) {
747 if (!$in_msg) {
748 $in_msg = 1 if (/^\s*$/);
749 } elsif (/^git-svn-id: /) {
750 # skip this for now, we regenerate the
751 # correct one on re-fetch anyways
752 # TODO: set *:merge properties or like...
753 } else {
754 print $log_fh $_ or croak $!;
757 command_close_pipe($msg_fh, $ctx);
759 close $log_fh or croak $!;
761 if ($_edit || ($type eq 'tree')) {
762 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
763 # TODO: strip out spaces, comments, like git-commit.sh
764 system($editor, $commit_editmsg);
766 rename $commit_editmsg, $commit_msg or croak $!;
767 open $log_fh, '<', $commit_msg or croak $!;
768 { local $/; chomp($log_entry{log} = <$log_fh>); }
769 close $log_fh or croak $!;
770 unlink $commit_msg;
771 \%log_entry;
774 sub s_to_file {
775 my ($str, $file, $mode) = @_;
776 open my $fd,'>',$file or croak $!;
777 print $fd $str,"\n" or croak $!;
778 close $fd or croak $!;
779 chmod ($mode &~ umask, $file) if (defined $mode);
782 sub file_to_s {
783 my $file = shift;
784 open my $fd,'<',$file or croak "$!: file: $file\n";
785 local $/;
786 my $ret = <$fd>;
787 close $fd or croak $!;
788 $ret =~ s/\s*$//s;
789 return $ret;
792 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
793 sub load_authors {
794 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
795 my $log = $cmd eq 'log';
796 while (<$authors>) {
797 chomp;
798 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
799 my ($user, $name, $email) = ($1, $2, $3);
800 if ($log) {
801 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
802 } else {
803 $users{$user} = [$name, $email];
806 close $authors or croak $!;
809 # convert GetOpt::Long specs for use by git-config
810 sub read_repo_config {
811 return unless -d $ENV{GIT_DIR};
812 my $opts = shift;
813 my @config_only;
814 foreach my $o (keys %$opts) {
815 # if we have mixedCase and a long option-only, then
816 # it's a config-only variable that we don't need for
817 # the command-line.
818 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
819 my $v = $opts->{$o};
820 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
821 $key =~ s/-//g;
822 my $arg = 'git-config';
823 $arg .= ' --int' if ($o =~ /[:=]i$/);
824 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
825 if (ref $v eq 'ARRAY') {
826 chomp(my @tmp = `$arg --get-all svn.$key`);
827 @$v = @tmp if @tmp;
828 } else {
829 chomp(my $tmp = `$arg --get svn.$key`);
830 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
831 $$v = $tmp;
835 delete @$opts{@config_only} if @config_only;
838 sub extract_metadata {
839 my $id = shift or return (undef, undef, undef);
840 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
841 \s([a-f\d\-]+)$/x);
842 if (!defined $rev || !$uuid || !$url) {
843 # some of the original repositories I made had
844 # identifiers like this:
845 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
847 return ($url, $rev, $uuid);
850 sub cmt_metadata {
851 return extract_metadata((grep(/^git-svn-id: /,
852 command(qw/cat-file commit/, shift)))[-1]);
855 sub working_head_info {
856 my ($head, $refs) = @_;
857 my ($fh, $ctx) = command_output_pipe('log', '--no-color', $head);
858 my $hash;
859 my %max;
860 while (<$fh>) {
861 if ( m{^commit ($::sha1)$} ) {
862 unshift @$refs, $hash if $hash and $refs;
863 $hash = $1;
864 next;
866 next unless s{^\s*(git-svn-id:)}{$1};
867 my ($url, $rev, $uuid) = extract_metadata($_);
868 if (defined $url && defined $rev) {
869 next if $max{$url} and $max{$url} < $rev;
870 if (my $gs = Git::SVN->find_by_url($url)) {
871 my $c = $gs->rev_db_get($rev);
872 if ($c && $c eq $hash) {
873 close $fh; # break the pipe
874 return ($url, $rev, $uuid, $gs);
875 } else {
876 $max{$url} ||= $gs->rev_db_max;
881 command_close_pipe($fh, $ctx);
882 (undef, undef, undef, undef);
885 sub read_commit_parents {
886 my ($parents, $c) = @_;
887 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
888 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
889 @{$parents->{$c}} = split(/ /, $p);
892 sub linearize_history {
893 my ($gs, $refs) = @_;
894 my %parents;
895 foreach my $c (@$refs) {
896 read_commit_parents(\%parents, $c);
899 my @linear_refs;
900 my %skip = ();
901 my $last_svn_commit = $gs->last_commit;
902 foreach my $c (reverse @$refs) {
903 next if $c eq $last_svn_commit;
904 last if $skip{$c};
906 unshift @linear_refs, $c;
907 $skip{$c} = 1;
909 # we only want the first parent to diff against for linear
910 # history, we save the rest to inject when we finalize the
911 # svn commit
912 my $fp_a = verify_ref("$c~1");
913 my $fp_b = shift @{$parents{$c}} if $parents{$c};
914 if (!$fp_a || !$fp_b) {
915 die "Commit $c\n",
916 "has no parent commit, and therefore ",
917 "nothing to diff against.\n",
918 "You should be working from a repository ",
919 "originally created by git-svn\n";
921 if ($fp_a ne $fp_b) {
922 die "$c~1 = $fp_a, however parsing commit $c ",
923 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
926 foreach my $p (@{$parents{$c}}) {
927 $skip{$p} = 1;
930 (\@linear_refs, \%parents);
933 package Git::SVN;
934 use strict;
935 use warnings;
936 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
937 $_repack $_repack_flags $_use_svm_props $_head
938 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
939 use Carp qw/croak/;
940 use File::Path qw/mkpath/;
941 use File::Copy qw/copy/;
942 use IPC::Open3;
944 my $_repack_nr;
945 # properties that we do not log:
946 my %SKIP_PROP;
947 BEGIN {
948 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
949 svn:special svn:executable
950 svn:entry:committed-rev
951 svn:entry:last-author
952 svn:entry:uuid
953 svn:entry:committed-date/;
955 # some options are read globally, but can be overridden locally
956 # per [svn-remote "..."] section. Command-line options will *NOT*
957 # override options set in an [svn-remote "..."] section
958 no strict 'refs';
959 for my $option (qw/follow_parent no_metadata use_svm_props
960 use_svnsync_props/) {
961 my $key = $option;
962 $key =~ tr/_//d;
963 my $prop = "-$option";
964 *$option = sub {
965 my ($self) = @_;
966 return $self->{$prop} if exists $self->{$prop};
967 my $k = "svn-remote.$self->{repo_id}.$key";
968 eval { command_oneline(qw/config --get/, $k) };
969 if ($@) {
970 $self->{$prop} = ${"Git::SVN::_$option"};
971 } else {
972 my $v = command_oneline(qw/config --bool/,$k);
973 $self->{$prop} = $v eq 'false' ? 0 : 1;
975 return $self->{$prop};
980 my %LOCKFILES;
981 END { unlink keys %LOCKFILES if %LOCKFILES }
983 sub resolve_local_globs {
984 my ($url, $fetch, $glob_spec) = @_;
985 return unless defined $glob_spec;
986 my $ref = $glob_spec->{ref};
987 my $path = $glob_spec->{path};
988 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
989 next unless m#^refs/remotes/$ref->{regex}$#;
990 my $p = $1;
991 my $pathname = desanitize_refname($path->full_path($p));
992 my $refname = desanitize_refname($ref->full_path($p));
993 if (my $existing = $fetch->{$pathname}) {
994 if ($existing ne $refname) {
995 die "Refspec conflict:\n",
996 "existing: refs/remotes/$existing\n",
997 " globbed: refs/remotes/$refname\n";
999 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1000 $u =~ s!^\Q$url\E(/|$)!! or die
1001 "refs/remotes/$refname: '$url' not found in '$u'\n";
1002 if ($pathname ne $u) {
1003 warn "W: Refspec glob conflict ",
1004 "(ref: refs/remotes/$refname):\n",
1005 "expected path: $pathname\n",
1006 " real path: $u\n",
1007 "Continuing ahead with $u\n";
1008 next;
1010 } else {
1011 $fetch->{$pathname} = $refname;
1016 sub parse_revision_argument {
1017 my ($base, $head) = @_;
1018 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1019 return ($base, $head);
1021 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1022 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1023 return ($head, $head) if ($::_revision eq 'HEAD');
1024 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1025 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1026 die "revision argument: $::_revision not understood by git-svn\n";
1029 sub fetch_all {
1030 my ($repo_id, $remotes) = @_;
1031 if (ref $repo_id) {
1032 my $gs = $repo_id;
1033 $repo_id = undef;
1034 $repo_id = $gs->{repo_id};
1036 $remotes ||= read_all_remotes();
1037 my $remote = $remotes->{$repo_id} or
1038 die "[svn-remote \"$repo_id\"] unknown\n";
1039 my $fetch = $remote->{fetch};
1040 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1041 my (@gs, @globs);
1042 my $ra = Git::SVN::Ra->new($url);
1043 my $uuid = $ra->get_uuid;
1044 my $head = $ra->get_latest_revnum;
1045 my $base = defined $fetch ? $head : 0;
1047 # read the max revs for wildcard expansion (branches/*, tags/*)
1048 foreach my $t (qw/branches tags/) {
1049 defined $remote->{$t} or next;
1050 push @globs, $remote->{$t};
1051 my $max_rev = eval { tmp_config(qw/--int --get/,
1052 "svn-remote.$repo_id.${t}-maxRev") };
1053 if (defined $max_rev && ($max_rev < $base)) {
1054 $base = $max_rev;
1055 } elsif (!defined $max_rev) {
1056 $base = 0;
1060 if ($fetch) {
1061 foreach my $p (sort keys %$fetch) {
1062 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1063 my $lr = $gs->rev_db_max;
1064 if (defined $lr) {
1065 $base = $lr if ($lr < $base);
1067 push @gs, $gs;
1071 ($base, $head) = parse_revision_argument($base, $head);
1072 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1075 sub read_all_remotes {
1076 my $r = {};
1077 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1078 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1079 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1080 $local_ref =~ s{^/}{};
1081 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1082 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1083 $r->{$1}->{url} = $2;
1084 } elsif (m!^(.+)\.(branches|tags)=
1085 (.*):refs/remotes/(.+)\s*$/!x) {
1086 my ($p, $g) = ($3, $4);
1087 my $rs = $r->{$1}->{$2} = {
1088 t => $2,
1089 remote => $1,
1090 path => Git::SVN::GlobSpec->new($p),
1091 ref => Git::SVN::GlobSpec->new($g) };
1092 if (length($rs->{ref}->{right}) != 0) {
1093 die "The '*' glob character must be the last ",
1094 "character of '$g'\n";
1101 sub init_vars {
1102 if (defined $_repack) {
1103 $_repack = 1000 if ($_repack <= 0);
1104 $_repack_nr = $_repack;
1105 $_repack_flags ||= '-d';
1109 sub verify_remotes_sanity {
1110 return unless -d $ENV{GIT_DIR};
1111 my %seen;
1112 foreach (command(qw/config -l/)) {
1113 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1114 if ($seen{$1}) {
1115 die "Remote ref refs/remote/$1 is tracked by",
1116 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1117 "Please resolve this ambiguity in ",
1118 "your git configuration file before ",
1119 "continuing\n";
1121 $seen{$1} = $_;
1126 # we allow more chars than remotes2config.sh...
1127 sub sanitize_remote_name {
1128 my ($name) = @_;
1129 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1130 $name;
1133 sub find_existing_remote {
1134 my ($url, $remotes) = @_;
1135 return undef if $no_reuse_existing;
1136 my $existing;
1137 foreach my $repo_id (keys %$remotes) {
1138 my $u = $remotes->{$repo_id}->{url} or next;
1139 next if $u ne $url;
1140 $existing = $repo_id;
1141 last;
1143 $existing;
1146 sub init_remote_config {
1147 my ($self, $url, $no_write) = @_;
1148 $url =~ s!/+$!!; # strip trailing slash
1149 my $r = read_all_remotes();
1150 my $existing = find_existing_remote($url, $r);
1151 if ($existing) {
1152 unless ($no_write) {
1153 print STDERR "Using existing ",
1154 "[svn-remote \"$existing\"]\n";
1156 $self->{repo_id} = $existing;
1157 } elsif ($_minimize_url) {
1158 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1159 $existing = find_existing_remote($min_url, $r);
1160 if ($existing) {
1161 unless ($no_write) {
1162 print STDERR "Using existing ",
1163 "[svn-remote \"$existing\"]\n";
1165 $self->{repo_id} = $existing;
1167 if ($min_url ne $url) {
1168 unless ($no_write) {
1169 print STDERR "Using higher level of URL: ",
1170 "$url => $min_url\n";
1172 my $old_path = $self->{path};
1173 $self->{path} = $url;
1174 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1175 if (length $old_path) {
1176 $self->{path} .= "/$old_path";
1178 $url = $min_url;
1181 my $orig_url;
1182 if (!$existing) {
1183 # verify that we aren't overwriting anything:
1184 $orig_url = eval {
1185 command_oneline('config', '--get',
1186 "svn-remote.$self->{repo_id}.url")
1188 if ($orig_url && ($orig_url ne $url)) {
1189 die "svn-remote.$self->{repo_id}.url already set: ",
1190 "$orig_url\nwanted to set to: $url\n";
1193 my ($xrepo_id, $xpath) = find_ref($self->refname);
1194 if (defined $xpath) {
1195 die "svn-remote.$xrepo_id.fetch already set to track ",
1196 "$xpath:refs/remotes/", $self->refname, "\n";
1198 unless ($no_write) {
1199 command_noisy('config',
1200 "svn-remote.$self->{repo_id}.url", $url);
1201 $self->{path} =~ s{^/}{};
1202 command_noisy('config', '--add',
1203 "svn-remote.$self->{repo_id}.fetch",
1204 "$self->{path}:".$self->refname);
1206 $self->{url} = $url;
1209 sub find_by_url { # repos_root and, path are optional
1210 my ($class, $full_url, $repos_root, $path) = @_;
1212 return undef unless defined $full_url;
1213 remove_username($full_url);
1214 remove_username($repos_root) if defined $repos_root;
1215 my $remotes = read_all_remotes();
1216 if (defined $full_url && defined $repos_root && !defined $path) {
1217 $path = $full_url;
1218 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1220 foreach my $repo_id (keys %$remotes) {
1221 my $u = $remotes->{$repo_id}->{url} or next;
1222 remove_username($u);
1223 next if defined $repos_root && $repos_root ne $u;
1225 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1226 foreach (qw/branches tags/) {
1227 resolve_local_globs($u, $fetch,
1228 $remotes->{$repo_id}->{$_});
1230 my $p = $path;
1231 unless (defined $p) {
1232 $p = $full_url;
1233 $p =~ s#^\Q$u\E(?:/|$)## or next;
1235 foreach my $f (keys %$fetch) {
1236 next if $f ne $p;
1237 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1240 undef;
1243 sub init {
1244 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1245 my $self = _new($class, $repo_id, $ref_id, $path);
1246 if (defined $url) {
1247 $self->init_remote_config($url, $no_write);
1249 $self;
1252 sub find_ref {
1253 my ($ref_id) = @_;
1254 foreach (command(qw/config -l/)) {
1255 next unless m!^svn-remote\.(.+)\.fetch=
1256 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1257 my ($repo_id, $path, $ref) = ($1, $2, $3);
1258 if ($ref eq $ref_id) {
1259 $path = '' if ($path =~ m#^\./?#);
1260 return ($repo_id, $path);
1263 (undef, undef, undef);
1266 sub new {
1267 my ($class, $ref_id, $repo_id, $path) = @_;
1268 if (defined $ref_id && !defined $repo_id && !defined $path) {
1269 ($repo_id, $path) = find_ref($ref_id);
1270 if (!defined $repo_id) {
1271 die "Could not find a \"svn-remote.*.fetch\" key ",
1272 "in the repository configuration matching: ",
1273 "refs/remotes/$ref_id\n";
1276 my $self = _new($class, $repo_id, $ref_id, $path);
1277 if (!defined $self->{path} || !length $self->{path}) {
1278 my $fetch = command_oneline('config', '--get',
1279 "svn-remote.$repo_id.fetch",
1280 ":refs/remotes/$ref_id\$") or
1281 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1282 "\":refs/remotes/$ref_id\$\" in config\n";
1283 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1285 $self->{url} = command_oneline('config', '--get',
1286 "svn-remote.$repo_id.url") or
1287 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1288 $self->rebuild;
1289 $self;
1292 sub refname {
1293 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1295 # It cannot end with a slash /, we'll throw up on this because
1296 # SVN can't have directories with a slash in their name, either:
1297 if ($refname =~ m{/$}) {
1298 die "ref: '$refname' ends with a trailing slash, this is ",
1299 "not permitted by git nor Subversion\n";
1302 # It cannot have ASCII control character space, tilde ~, caret ^,
1303 # colon :, question-mark ?, asterisk *, space, or open bracket [
1304 # anywhere.
1306 # Additionally, % must be escaped because it is used for escaping
1307 # and we want our escaped refname to be reversible
1308 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1310 # no slash-separated component can begin with a dot .
1311 # /.* becomes /%2E*
1312 $refname =~ s{/\.}{/%2E}g;
1314 # It cannot have two consecutive dots .. anywhere
1315 # .. becomes %2E%2E
1316 $refname =~ s{\.\.}{%2E%2E}g;
1318 return $refname;
1321 sub desanitize_refname {
1322 my ($refname) = @_;
1323 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1324 return $refname;
1327 sub svm_uuid {
1328 my ($self) = @_;
1329 return $self->{svm}->{uuid} if $self->svm;
1330 $self->ra;
1331 unless ($self->{svm}) {
1332 die "SVM UUID not cached, and reading remotely failed\n";
1334 $self->{svm}->{uuid};
1337 sub svm {
1338 my ($self) = @_;
1339 return $self->{svm} if $self->{svm};
1340 my $svm;
1341 # see if we have it in our config, first:
1342 eval {
1343 my $section = "svn-remote.$self->{repo_id}";
1344 $svm = {
1345 source => tmp_config('--get', "$section.svm-source"),
1346 uuid => tmp_config('--get', "$section.svm-uuid"),
1347 replace => tmp_config('--get', "$section.svm-replace"),
1350 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1351 $self->{svm} = $svm;
1353 $self->{svm};
1356 sub _set_svm_vars {
1357 my ($self, $ra) = @_;
1358 return $ra if $self->svm;
1360 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1361 "(svm:source, svm:uuid) ",
1362 "from the following URLs:\n" );
1363 sub read_svm_props {
1364 my ($self, $ra, $path, $r) = @_;
1365 my $props = ($ra->get_dir($path, $r))[2];
1366 my $src = $props->{'svm:source'};
1367 my $uuid = $props->{'svm:uuid'};
1368 return undef if (!$src || !$uuid);
1370 chomp($src, $uuid);
1372 $uuid =~ m{^[0-9a-f\-]{30,}$}
1373 or die "doesn't look right - svm:uuid is '$uuid'\n";
1375 # the '!' is used to mark the repos_root!/relative/path
1376 $src =~ s{/?!/?}{/};
1377 $src =~ s{/+$}{}; # no trailing slashes please
1378 # username is of no interest
1379 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1381 my $replace = $ra->{url};
1382 $replace .= "/$path" if length $path;
1384 my $section = "svn-remote.$self->{repo_id}";
1385 tmp_config("$section.svm-source", $src);
1386 tmp_config("$section.svm-replace", $replace);
1387 tmp_config("$section.svm-uuid", $uuid);
1388 $self->{svm} = {
1389 source => $src,
1390 uuid => $uuid,
1391 replace => $replace
1395 my $r = $ra->get_latest_revnum;
1396 my $path = $self->{path};
1397 my %tried;
1398 while (length $path) {
1399 unless ($tried{"$self->{url}/$path"}) {
1400 return $ra if $self->read_svm_props($ra, $path, $r);
1401 $tried{"$self->{url}/$path"} = 1;
1403 $path =~ s#/?[^/]+$##;
1405 die "Path: '$path' should be ''\n" if $path ne '';
1406 return $ra if $self->read_svm_props($ra, $path, $r);
1407 $tried{"$self->{url}/$path"} = 1;
1409 if ($ra->{repos_root} eq $self->{url}) {
1410 die @err, (map { " $_\n" } keys %tried), "\n";
1413 # nope, make sure we're connected to the repository root:
1414 my $ok;
1415 my @tried_b;
1416 $path = $ra->{svn_path};
1417 $ra = Git::SVN::Ra->new($ra->{repos_root});
1418 while (length $path) {
1419 unless ($tried{"$ra->{url}/$path"}) {
1420 $ok = $self->read_svm_props($ra, $path, $r);
1421 last if $ok;
1422 $tried{"$ra->{url}/$path"} = 1;
1424 $path =~ s#/?[^/]+$##;
1426 die "Path: '$path' should be ''\n" if $path ne '';
1427 $ok ||= $self->read_svm_props($ra, $path, $r);
1428 $tried{"$ra->{url}/$path"} = 1;
1429 if (!$ok) {
1430 die @err, (map { " $_\n" } keys %tried), "\n";
1432 Git::SVN::Ra->new($self->{url});
1435 sub svnsync {
1436 my ($self) = @_;
1437 return $self->{svnsync} if $self->{svnsync};
1439 if ($self->no_metadata) {
1440 die "Can't have both 'noMetadata' and ",
1441 "'useSvnsyncProps' options set!\n";
1443 if ($self->rewrite_root) {
1444 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1445 "options set!\n";
1448 my $svnsync;
1449 # see if we have it in our config, first:
1450 eval {
1451 my $section = "svn-remote.$self->{repo_id}";
1452 $svnsync = {
1453 url => tmp_config('--get', "$section.svnsync-url"),
1454 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1457 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1458 return $self->{svnsync} = $svnsync;
1461 my $err = "useSvnsyncProps set, but failed to read " .
1462 "svnsync property: svn:sync-from-";
1463 my $rp = $self->ra->rev_proplist(0);
1465 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1466 $url =~ m{^[a-z\+]+://} or
1467 die "doesn't look right - svn:sync-from-url is '$url'\n";
1469 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1470 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1471 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1473 my $section = "svn-remote.$self->{repo_id}";
1474 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1475 tmp_config('--add', "$section.svnsync-url", $url);
1476 return $self->{svnsync} = { url => $url, uuid => $uuid };
1479 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1480 # remote lookup (useful for 'git svn log').
1481 sub ra_uuid {
1482 my ($self) = @_;
1483 unless ($self->{ra_uuid}) {
1484 my $key = "svn-remote.$self->{repo_id}.uuid";
1485 my $uuid = eval { tmp_config('--get', $key) };
1486 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1487 $self->{ra_uuid} = $uuid;
1488 } else {
1489 die "ra_uuid called without URL\n" unless $self->{url};
1490 $self->{ra_uuid} = $self->ra->get_uuid;
1491 tmp_config('--add', $key, $self->{ra_uuid});
1494 $self->{ra_uuid};
1497 sub ra {
1498 my ($self) = shift;
1499 my $ra = Git::SVN::Ra->new($self->{url});
1500 if ($self->use_svm_props && !$self->{svm}) {
1501 if ($self->no_metadata) {
1502 die "Can't have both 'noMetadata' and ",
1503 "'useSvmProps' options set!\n";
1504 } elsif ($self->use_svnsync_props) {
1505 die "Can't have both 'useSvnsyncProps' and ",
1506 "'useSvmProps' options set!\n";
1508 $ra = $self->_set_svm_vars($ra);
1509 $self->{-want_revprops} = 1;
1511 $ra;
1514 sub rel_path {
1515 my ($self) = @_;
1516 my $repos_root = $self->ra->{repos_root};
1517 return $self->{path} if ($self->{url} eq $repos_root);
1518 my $url = $self->{url} .
1519 (length $self->{path} ? "/$self->{path}" : $self->{path});
1520 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1521 $url;
1524 sub traverse_ignore {
1525 my ($self, $fh, $path, $r) = @_;
1526 $path =~ s#^/+##g;
1527 my $ra = $self->ra;
1528 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1529 my $p = $path;
1530 $p =~ s#^\Q$self->{path}\E(/|$)##;
1531 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1532 if (my $s = $props->{'svn:ignore'}) {
1533 $s =~ s/[\r\n]+/\n/g;
1534 chomp $s;
1535 if (length $p == 0) {
1536 $s =~ s#\n#\n/$p#g;
1537 print $fh "/$s\n";
1538 } else {
1539 $s =~ s#\n#\n/$p/#g;
1540 print $fh "/$p/$s\n";
1543 foreach (sort keys %$dirent) {
1544 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1545 $self->traverse_ignore($fh, "$path/$_", $r);
1549 sub last_rev { ($_[0]->last_rev_commit)[0] }
1550 sub last_commit { ($_[0]->last_rev_commit)[1] }
1552 # returns the newest SVN revision number and newest commit SHA1
1553 sub last_rev_commit {
1554 my ($self) = @_;
1555 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1556 return ($self->{last_rev}, $self->{last_commit});
1558 my $c = ::verify_ref($self->refname.'^0');
1559 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1560 my $rev = (::cmt_metadata($c))[1];
1561 if (defined $rev) {
1562 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1563 return ($rev, $c);
1566 my $db_path = $self->db_path;
1567 unless (-e $db_path) {
1568 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1569 return (undef, undef);
1571 my $offset = -41; # from tail
1572 my $rl;
1573 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1574 sysseek($fh, $offset, 2); # don't care for errors
1575 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1576 chomp $rl;
1577 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1578 $offset -= 41;
1579 sysseek($fh, $offset, 2); # don't care for errors
1580 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1581 chomp $rl;
1583 if ($c && $c ne $rl) {
1584 die "$db_path and ", $self->refname,
1585 " inconsistent!:\n$c != $rl\n";
1587 my $rev = sysseek($fh, 0, 1) or croak $!;
1588 $rev = ($rev - 41) / 41;
1589 close $fh or croak $!;
1590 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1591 return ($rev, $c);
1594 sub get_fetch_range {
1595 my ($self, $min, $max) = @_;
1596 $max ||= $self->ra->get_latest_revnum;
1597 $min ||= $self->rev_db_max;
1598 (++$min, $max);
1601 sub tmp_config {
1602 my (@args) = @_;
1603 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1604 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1605 if (! -f $config && -f $old_def_config) {
1606 rename $old_def_config, $config or
1607 die "Failed rename $old_def_config => $config: $!\n";
1609 my $old_config = $ENV{GIT_CONFIG};
1610 $ENV{GIT_CONFIG} = $config;
1611 $@ = undef;
1612 my @ret = eval {
1613 unless (-f $config) {
1614 mkfile($config);
1615 open my $fh, '>', $config or
1616 die "Can't open $config: $!\n";
1617 print $fh "; This file is used internally by ",
1618 "git-svn\n" or die
1619 "Couldn't write to $config: $!\n";
1620 print $fh "; You should not have to edit it\n" or
1621 die "Couldn't write to $config: $!\n";
1622 close $fh or die "Couldn't close $config: $!\n";
1624 command('config', @args);
1626 my $err = $@;
1627 if (defined $old_config) {
1628 $ENV{GIT_CONFIG} = $old_config;
1629 } else {
1630 delete $ENV{GIT_CONFIG};
1632 die $err if $err;
1633 wantarray ? @ret : $ret[0];
1636 sub tmp_index_do {
1637 my ($self, $sub) = @_;
1638 my $old_index = $ENV{GIT_INDEX_FILE};
1639 $ENV{GIT_INDEX_FILE} = $self->{index};
1640 $@ = undef;
1641 my @ret = eval {
1642 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1643 mkpath([$dir]) unless -d $dir;
1644 &$sub;
1646 my $err = $@;
1647 if (defined $old_index) {
1648 $ENV{GIT_INDEX_FILE} = $old_index;
1649 } else {
1650 delete $ENV{GIT_INDEX_FILE};
1652 die $err if $err;
1653 wantarray ? @ret : $ret[0];
1656 sub assert_index_clean {
1657 my ($self, $treeish) = @_;
1659 $self->tmp_index_do(sub {
1660 command_noisy('read-tree', $treeish) unless -e $self->{index};
1661 my $x = command_oneline('write-tree');
1662 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1663 /^tree ($::sha1)/mo);
1664 return if $y eq $x;
1666 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1667 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1668 command_noisy('read-tree', $treeish);
1669 $x = command_oneline('write-tree');
1670 if ($y ne $x) {
1671 ::fatal "trees ($treeish) $y != $x\n",
1672 "Something is seriously wrong...\n";
1677 sub get_commit_parents {
1678 my ($self, $log_entry) = @_;
1679 my (%seen, @ret, @tmp);
1680 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1681 if (my $ip = $self->{inject_parents}) {
1682 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1683 push @tmp, $commit;
1686 if (my $cur = ::verify_ref($self->refname.'^0')) {
1687 push @tmp, $cur;
1689 if (my $ipd = $self->{inject_parents_dcommit}) {
1690 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1691 push @tmp, @$commit;
1694 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1695 while (my $p = shift @tmp) {
1696 next if $seen{$p};
1697 $seen{$p} = 1;
1698 push @ret, $p;
1699 # MAXPARENT is defined to 16 in commit-tree.c:
1700 last if @ret >= 16;
1702 if (@tmp) {
1703 die "r$log_entry->{revision}: No room for parents:\n\t",
1704 join("\n\t", @tmp), "\n";
1706 @ret;
1709 sub rewrite_root {
1710 my ($self) = @_;
1711 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1712 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1713 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1714 if ($rwr) {
1715 $rwr =~ s#/+$##;
1716 if ($rwr !~ m#^[a-z\+]+://#) {
1717 die "$rwr is not a valid URL (key: $k)\n";
1720 $self->{-rewrite_root} = $rwr;
1723 sub metadata_url {
1724 my ($self) = @_;
1725 ($self->rewrite_root || $self->{url}) .
1726 (length $self->{path} ? '/' . $self->{path} : '');
1729 sub full_url {
1730 my ($self) = @_;
1731 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1734 sub do_git_commit {
1735 my ($self, $log_entry) = @_;
1736 my $lr = $self->last_rev;
1737 if (defined $lr && $lr >= $log_entry->{revision}) {
1738 die "Last fetched revision of ", $self->refname,
1739 " was r$lr, but we are about to fetch: ",
1740 "r$log_entry->{revision}!\n";
1742 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1743 croak "$log_entry->{revision} = $c already exists! ",
1744 "Why are we refetching it?\n";
1746 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1747 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1748 $log_entry->{email};
1749 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1751 my $tree = $log_entry->{tree};
1752 if (!defined $tree) {
1753 $tree = $self->tmp_index_do(sub {
1754 command_oneline('write-tree') });
1756 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1758 my @exec = ('git-commit-tree', $tree);
1759 foreach ($self->get_commit_parents($log_entry)) {
1760 push @exec, '-p', $_;
1762 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1763 or croak $!;
1764 print $msg_fh $log_entry->{log} or croak $!;
1765 unless ($self->no_metadata) {
1766 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1767 or croak $!;
1769 $msg_fh->flush == 0 or croak $!;
1770 close $msg_fh or croak $!;
1771 chomp(my $commit = do { local $/; <$out_fh> });
1772 close $out_fh or croak $!;
1773 waitpid $pid, 0;
1774 croak $? if $?;
1775 if ($commit !~ /^$::sha1$/o) {
1776 die "Failed to commit, invalid sha1: $commit\n";
1779 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1781 $self->{last_rev} = $log_entry->{revision};
1782 $self->{last_commit} = $commit;
1783 print "r$log_entry->{revision}";
1784 if (defined $log_entry->{svm_revision}) {
1785 print " (\@$log_entry->{svm_revision})";
1786 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1787 0, $self->svm_uuid);
1789 print " = $commit ($self->{ref_id})\n";
1790 if (defined $_repack && (--$_repack_nr == 0)) {
1791 $_repack_nr = $_repack;
1792 # repack doesn't use any arguments with spaces in them, does it?
1793 print "Running git repack $_repack_flags ...\n";
1794 command_noisy('repack', split(/\s+/, $_repack_flags));
1795 print "Done repacking\n";
1797 return $commit;
1800 sub match_paths {
1801 my ($self, $paths, $r) = @_;
1802 return 1 if $self->{path} eq '';
1803 if (my $path = $paths->{"/$self->{path}"}) {
1804 return ($path->{action} eq 'D') ? 0 : 1;
1806 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1807 if (grep /$self->{path_regex}/, keys %$paths) {
1808 return 1;
1810 my $c = '';
1811 foreach (split m#/#, $self->{path}) {
1812 $c .= "/$_";
1813 next unless ($paths->{$c} &&
1814 ($paths->{$c}->{action} =~ /^[AR]$/));
1815 if ($self->ra->check_path($self->{path}, $r) ==
1816 $SVN::Node::dir) {
1817 return 1;
1820 return 0;
1823 sub find_parent_branch {
1824 my ($self, $paths, $rev) = @_;
1825 return undef unless $self->follow_parent;
1826 unless (defined $paths) {
1827 my $err_handler = $SVN::Error::handler;
1828 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1829 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1830 $paths =
1831 Git::SVN::Ra::dup_changed_paths($_[0]) });
1832 $SVN::Error::handler = $err_handler;
1834 return undef unless defined $paths;
1836 # look for a parent from another branch:
1837 my @b_path_components = split m#/#, $self->rel_path;
1838 my @a_path_components;
1839 my $i;
1840 while (@b_path_components) {
1841 $i = $paths->{'/'.join('/', @b_path_components)};
1842 last if $i && defined $i->{copyfrom_path};
1843 unshift(@a_path_components, pop(@b_path_components));
1845 return undef unless defined $i && defined $i->{copyfrom_path};
1846 my $branch_from = $i->{copyfrom_path};
1847 if (@a_path_components) {
1848 print STDERR "branch_from: $branch_from => ";
1849 $branch_from .= '/'.join('/', @a_path_components);
1850 print STDERR $branch_from, "\n";
1852 my $r = $i->{copyfrom_rev};
1853 my $repos_root = $self->ra->{repos_root};
1854 my $url = $self->ra->{url};
1855 my $new_url = $repos_root . $branch_from;
1856 print STDERR "Found possible branch point: ",
1857 "$new_url => ", $self->full_url, ", $r\n";
1858 $branch_from =~ s#^/##;
1859 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1860 unless ($gs) {
1861 my $ref_id = $self->{ref_id};
1862 $ref_id =~ s/\@\d+$//;
1863 $ref_id .= "\@$r";
1864 # just grow a tail if we're not unique enough :x
1865 $ref_id .= '-' while find_ref($ref_id);
1866 print STDERR "Initializing parent: $ref_id\n";
1867 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1869 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1870 if (!defined $r0 || !defined $parent) {
1871 my ($base, $head) = parse_revision_argument(0, $r);
1872 if ($base <= $r) {
1873 $gs->fetch($base, $r);
1875 ($r0, $parent) = $gs->last_rev_commit;
1877 if (defined $r0 && defined $parent) {
1878 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1879 my $ed;
1880 if ($self->ra->can_do_switch) {
1881 $self->assert_index_clean($parent);
1882 print STDERR "Following parent with do_switch\n";
1883 # do_switch works with svn/trunk >= r22312, but that
1884 # is not included with SVN 1.4.3 (the latest version
1885 # at the moment), so we can't rely on it
1886 $self->{last_commit} = $parent;
1887 $ed = SVN::Git::Fetcher->new($self);
1888 $gs->ra->gs_do_switch($r0, $rev, $gs,
1889 $self->full_url, $ed)
1890 or die "SVN connection failed somewhere...\n";
1891 } else {
1892 print STDERR "Following parent with do_update\n";
1893 $ed = SVN::Git::Fetcher->new($self);
1894 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1895 or die "SVN connection failed somewhere...\n";
1897 print STDERR "Successfully followed parent\n";
1898 return $self->make_log_entry($rev, [$parent], $ed);
1900 return undef;
1903 sub do_fetch {
1904 my ($self, $paths, $rev) = @_;
1905 my $ed;
1906 my ($last_rev, @parents);
1907 if (my $lc = $self->last_commit) {
1908 # we can have a branch that was deleted, then re-added
1909 # under the same name but copied from another path, in
1910 # which case we'll have multiple parents (we don't
1911 # want to break the original ref, nor lose copypath info):
1912 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1913 push @{$log_entry->{parents}}, $lc;
1914 return $log_entry;
1916 $ed = SVN::Git::Fetcher->new($self);
1917 $last_rev = $self->{last_rev};
1918 $ed->{c} = $lc;
1919 @parents = ($lc);
1920 } else {
1921 $last_rev = $rev;
1922 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1923 return $log_entry;
1925 $ed = SVN::Git::Fetcher->new($self);
1927 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1928 die "SVN connection failed somewhere...\n";
1930 $self->make_log_entry($rev, \@parents, $ed);
1933 sub get_untracked {
1934 my ($self, $ed) = @_;
1935 my @out;
1936 my $h = $ed->{empty};
1937 foreach (sort keys %$h) {
1938 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1939 push @out, " $act: " . uri_encode($_);
1940 warn "W: $act: $_\n";
1942 foreach my $t (qw/dir_prop file_prop/) {
1943 $h = $ed->{$t} or next;
1944 foreach my $path (sort keys %$h) {
1945 my $ppath = $path eq '' ? '.' : $path;
1946 foreach my $prop (sort keys %{$h->{$path}}) {
1947 next if $SKIP_PROP{$prop};
1948 my $v = $h->{$path}->{$prop};
1949 my $t_ppath_prop = "$t: " .
1950 uri_encode($ppath) . ' ' .
1951 uri_encode($prop);
1952 if (defined $v) {
1953 push @out, " +$t_ppath_prop " .
1954 uri_encode($v);
1955 } else {
1956 push @out, " -$t_ppath_prop";
1961 foreach my $t (qw/absent_file absent_directory/) {
1962 $h = $ed->{$t} or next;
1963 foreach my $parent (sort keys %$h) {
1964 foreach my $path (sort @{$h->{$parent}}) {
1965 push @out, " $t: " .
1966 uri_encode("$parent/$path");
1967 warn "W: $t: $parent/$path ",
1968 "Insufficient permissions?\n";
1972 \@out;
1975 sub parse_svn_date {
1976 my $date = shift || return '+0000 1970-01-01 00:00:00';
1977 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1978 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1979 croak "Unable to parse date: $date\n";
1980 "+0000 $Y-$m-$d $H:$M:$S";
1983 sub check_author {
1984 my ($author) = @_;
1985 if (!defined $author || length $author == 0) {
1986 $author = '(no author)';
1988 if (defined $::_authors && ! defined $::users{$author}) {
1989 die "Author: $author not defined in $::_authors file\n";
1991 $author;
1994 sub make_log_entry {
1995 my ($self, $rev, $parents, $ed) = @_;
1996 my $untracked = $self->get_untracked($ed);
1998 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1999 print $un "r$rev\n" or croak $!;
2000 print $un $_, "\n" foreach @$untracked;
2001 my %log_entry = ( parents => $parents || [], revision => $rev,
2002 log => '');
2004 my $headrev;
2005 my $logged = delete $self->{logged_rev_props};
2006 if (!$logged || $self->{-want_revprops}) {
2007 my $rp = $self->ra->rev_proplist($rev);
2008 foreach (sort keys %$rp) {
2009 my $v = $rp->{$_};
2010 if (/^svn:(author|date|log)$/) {
2011 $log_entry{$1} = $v;
2012 } elsif ($_ eq 'svm:headrev') {
2013 $headrev = $v;
2014 } else {
2015 print $un " rev_prop: ", uri_encode($_), ' ',
2016 uri_encode($v), "\n";
2019 } else {
2020 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2022 close $un or croak $!;
2024 $log_entry{date} = parse_svn_date($log_entry{date});
2025 $log_entry{log} .= "\n";
2026 my $author = $log_entry{author} = check_author($log_entry{author});
2027 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2028 : ($author, undef);
2029 if (defined $headrev && $self->use_svm_props) {
2030 if ($self->rewrite_root) {
2031 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2032 "options set!\n";
2034 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2035 # we don't want "SVM: initializing mirror for junk" ...
2036 return undef if $r == 0;
2037 my $svm = $self->svm;
2038 if ($uuid ne $svm->{uuid}) {
2039 die "UUID mismatch on SVM path:\n",
2040 "expected: $svm->{uuid}\n",
2041 " got: $uuid\n";
2043 my $full_url = $self->full_url;
2044 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2045 die "Failed to replace '$svm->{replace}' with ",
2046 "'$svm->{source}' in $full_url\n";
2047 # throw away username for storing in records
2048 remove_username($full_url);
2049 $log_entry{metadata} = "$full_url\@$r $uuid";
2050 $log_entry{svm_revision} = $r;
2051 $email ||= "$author\@$uuid"
2052 } elsif ($self->use_svnsync_props) {
2053 my $full_url = $self->svnsync->{url};
2054 $full_url .= "/$self->{path}" if length $self->{path};
2055 remove_username($full_url);
2056 my $uuid = $self->svnsync->{uuid};
2057 $log_entry{metadata} = "$full_url\@$rev $uuid";
2058 $email ||= "$author\@$uuid"
2059 } else {
2060 my $url = $self->metadata_url;
2061 remove_username($url);
2062 $log_entry{metadata} = "$url\@$rev " .
2063 $self->ra->get_uuid;
2064 $email ||= "$author\@" . $self->ra->get_uuid;
2066 $log_entry{name} = $name;
2067 $log_entry{email} = $email;
2068 \%log_entry;
2071 sub fetch {
2072 my ($self, $min_rev, $max_rev, @parents) = @_;
2073 my ($last_rev, $last_commit) = $self->last_rev_commit;
2074 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2075 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2078 sub set_tree_cb {
2079 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2080 $self->{inject_parents} = { $rev => $tree };
2081 $self->fetch(undef, undef);
2084 sub set_tree {
2085 my ($self, $tree) = (shift, shift);
2086 my $log_entry = ::get_commit_entry($tree);
2087 unless ($self->{last_rev}) {
2088 fatal("Must have an existing revision to commit\n");
2090 my %ed_opts = ( r => $self->{last_rev},
2091 log => $log_entry->{log},
2092 ra => $self->ra,
2093 tree_a => $self->{last_commit},
2094 tree_b => $tree,
2095 editor_cb => sub {
2096 $self->set_tree_cb($log_entry, $tree, @_) },
2097 svn_path => $self->{path} );
2098 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2099 print "No changes\nr$self->{last_rev} = $tree\n";
2103 sub rebuild {
2104 my ($self) = @_;
2105 my $db_path = $self->db_path;
2106 return if (-e $db_path && ! -z $db_path);
2107 return unless ::verify_ref($self->refname.'^0');
2108 if (-f $self->{db_root}) {
2109 rename $self->{db_root}, $db_path or die
2110 "rename $self->{db_root} => $db_path failed: $!\n";
2111 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2112 symlink $base, $self->{db_root} or die
2113 "symlink $base => $self->{db_root} failed: $!\n";
2114 return;
2116 print "Rebuilding $db_path ...\n";
2117 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2118 my $latest;
2119 my $full_url = $self->full_url;
2120 remove_username($full_url);
2121 my $svn_uuid;
2122 my $c;
2123 while (<$log>) {
2124 if ( m{^commit ($::sha1)$} ) {
2125 $c = $1;
2126 next;
2128 next unless s{^\s*(git-svn-id:)}{$1};
2129 my ($url, $rev, $uuid) = ::extract_metadata($_);
2130 remove_username($url);
2132 # ignore merges (from set-tree)
2133 next if (!defined $rev || !$uuid);
2135 # if we merged or otherwise started elsewhere, this is
2136 # how we break out of it
2137 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2138 ($full_url && $url && ($url ne $full_url))) {
2139 next;
2141 $latest ||= $rev;
2142 $svn_uuid ||= $uuid;
2144 $self->rev_db_set($rev, $c);
2145 print "r$rev = $c\n";
2147 command_close_pipe($log, $ctx);
2148 print "Done rebuilding $db_path\n";
2151 # rev_db:
2152 # Tie::File seems to be prone to offset errors if revisions get sparse,
2153 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2154 # one of my favorite modules is out :< Next up would be one of the DBM
2155 # modules, but I'm not sure which is most portable... So I'll just
2156 # go with something that's plain-text, but still capable of
2157 # being randomly accessed. So here's my ultra-simple fixed-width
2158 # database. All records are 40 characters + "\n", so it's easy to seek
2159 # to a revision: (41 * rev) is the byte offset.
2160 # A record of 40 0s denotes an empty revision.
2161 # And yes, it's still pretty fast (faster than Tie::File).
2162 # These files are disposable unless noMetadata or useSvmProps is set
2164 sub _rev_db_set {
2165 my ($fh, $rev, $commit) = @_;
2166 my $offset = $rev * 41;
2167 # assume that append is the common case:
2168 seek $fh, 0, 2 or croak $!;
2169 my $pos = tell $fh;
2170 if ($pos < $offset) {
2171 for (1 .. (($offset - $pos) / 41)) {
2172 print $fh (('0' x 40),"\n") or croak $!;
2175 seek $fh, $offset, 0 or croak $!;
2176 print $fh $commit,"\n" or croak $!;
2179 sub mkfile {
2180 my ($path) = @_;
2181 unless (-e $path) {
2182 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2183 mkpath([$dir]) unless -d $dir;
2184 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2185 close $fh or die "Couldn't close (create) $path: $!\n";
2189 sub rev_db_set {
2190 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2191 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2192 my $db = $self->db_path($uuid);
2193 my $db_lock = "$db.lock";
2194 my $sig;
2195 if ($update_ref) {
2196 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2197 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2199 mkfile($db);
2201 $LOCKFILES{$db_lock} = 1;
2202 my $sync;
2203 # both of these options make our .rev_db file very, very important
2204 # and we can't afford to lose it because rebuild() won't work
2205 if ($self->use_svm_props || $self->no_metadata) {
2206 $sync = 1;
2207 copy($db, $db_lock) or die "rev_db_set(@_): ",
2208 "Failed to copy: ",
2209 "$db => $db_lock ($!)\n";
2210 } else {
2211 rename $db, $db_lock or die "rev_db_set(@_): ",
2212 "Failed to rename: ",
2213 "$db => $db_lock ($!)\n";
2215 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2216 _rev_db_set($fh, $rev, $commit);
2217 if ($sync) {
2218 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2219 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2221 close $fh or croak $!;
2222 if ($update_ref) {
2223 $_head = $self;
2224 command_noisy('update-ref', '-m', "r$rev",
2225 $self->refname, $commit);
2227 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2228 "$db_lock => $db ($!)\n";
2229 delete $LOCKFILES{$db_lock};
2230 if ($update_ref) {
2231 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2232 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2233 kill $sig, $$ if defined $sig;
2237 sub rev_db_max {
2238 my ($self) = @_;
2239 $self->rebuild;
2240 my $db_path = $self->db_path;
2241 my @stat = stat $db_path or return 0;
2242 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2243 my $max = $stat[7] / 41;
2244 (($max > 0) ? $max - 1 : 0);
2247 sub rev_db_get {
2248 my ($self, $rev, $uuid) = @_;
2249 my $ret;
2250 my $offset = $rev * 41;
2251 my $db_path = $self->db_path($uuid);
2252 return undef unless -e $db_path;
2253 open my $fh, '<', $db_path or croak $!;
2254 if (sysseek($fh, $offset, 0) == $offset) {
2255 my $read = sysread($fh, $ret, 40);
2256 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2258 close $fh or croak $!;
2259 $ret;
2262 sub find_rev_before {
2263 my ($self, $rev, $eq_ok) = @_;
2264 --$rev unless $eq_ok;
2265 while ($rev > 0) {
2266 if (my $c = $self->rev_db_get($rev)) {
2267 return ($rev, $c);
2269 --$rev;
2271 return (undef, undef);
2274 sub _new {
2275 my ($class, $repo_id, $ref_id, $path) = @_;
2276 unless (defined $repo_id && length $repo_id) {
2277 $repo_id = $Git::SVN::default_repo_id;
2279 unless (defined $ref_id && length $ref_id) {
2280 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2282 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2283 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2284 $_[3] = $path = '' unless (defined $path);
2285 mkpath(["$ENV{GIT_DIR}/svn"]);
2286 bless {
2287 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2288 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2289 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2292 sub db_path {
2293 my ($self, $uuid) = @_;
2294 $uuid ||= $self->ra_uuid;
2295 "$self->{db_root}.$uuid";
2298 sub uri_encode {
2299 my ($f) = @_;
2300 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2304 sub remove_username {
2305 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2308 package Git::SVN::Prompt;
2309 use strict;
2310 use warnings;
2311 require SVN::Core;
2312 use vars qw/$_no_auth_cache $_username/;
2314 sub simple {
2315 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2316 $may_save = undef if $_no_auth_cache;
2317 $default_username = $_username if defined $_username;
2318 if (defined $default_username && length $default_username) {
2319 if (defined $realm && length $realm) {
2320 print STDERR "Authentication realm: $realm\n";
2321 STDERR->flush;
2323 $cred->username($default_username);
2324 } else {
2325 username($cred, $realm, $may_save, $pool);
2327 $cred->password(_read_password("Password for '" .
2328 $cred->username . "': ", $realm));
2329 $cred->may_save($may_save);
2330 $SVN::_Core::SVN_NO_ERROR;
2333 sub ssl_server_trust {
2334 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2335 $may_save = undef if $_no_auth_cache;
2336 print STDERR "Error validating server certificate for '$realm':\n";
2337 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2338 print STDERR " - The certificate is not issued by a trusted ",
2339 "authority. Use the\n",
2340 " fingerprint to validate the certificate manually!\n";
2342 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2343 print STDERR " - The certificate hostname does not match.\n";
2345 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2346 print STDERR " - The certificate is not yet valid.\n";
2348 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2349 print STDERR " - The certificate has expired.\n";
2351 if ($failures & $SVN::Auth::SSL::OTHER) {
2352 print STDERR " - The certificate has an unknown error.\n";
2354 printf STDERR
2355 "Certificate information:\n".
2356 " - Hostname: %s\n".
2357 " - Valid: from %s until %s\n".
2358 " - Issuer: %s\n".
2359 " - Fingerprint: %s\n",
2360 map $cert_info->$_, qw(hostname valid_from valid_until
2361 issuer_dname fingerprint);
2362 my $choice;
2363 prompt:
2364 print STDERR $may_save ?
2365 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2366 "(R)eject or accept (t)emporarily? ";
2367 STDERR->flush;
2368 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2369 if ($choice =~ /^t$/i) {
2370 $cred->may_save(undef);
2371 } elsif ($choice =~ /^r$/i) {
2372 return -1;
2373 } elsif ($may_save && $choice =~ /^p$/i) {
2374 $cred->may_save($may_save);
2375 } else {
2376 goto prompt;
2378 $cred->accepted_failures($failures);
2379 $SVN::_Core::SVN_NO_ERROR;
2382 sub ssl_client_cert {
2383 my ($cred, $realm, $may_save, $pool) = @_;
2384 $may_save = undef if $_no_auth_cache;
2385 print STDERR "Client certificate filename: ";
2386 STDERR->flush;
2387 chomp(my $filename = <STDIN>);
2388 $cred->cert_file($filename);
2389 $cred->may_save($may_save);
2390 $SVN::_Core::SVN_NO_ERROR;
2393 sub ssl_client_cert_pw {
2394 my ($cred, $realm, $may_save, $pool) = @_;
2395 $may_save = undef if $_no_auth_cache;
2396 $cred->password(_read_password("Password: ", $realm));
2397 $cred->may_save($may_save);
2398 $SVN::_Core::SVN_NO_ERROR;
2401 sub username {
2402 my ($cred, $realm, $may_save, $pool) = @_;
2403 $may_save = undef if $_no_auth_cache;
2404 if (defined $realm && length $realm) {
2405 print STDERR "Authentication realm: $realm\n";
2407 my $username;
2408 if (defined $_username) {
2409 $username = $_username;
2410 } else {
2411 print STDERR "Username: ";
2412 STDERR->flush;
2413 chomp($username = <STDIN>);
2415 $cred->username($username);
2416 $cred->may_save($may_save);
2417 $SVN::_Core::SVN_NO_ERROR;
2420 sub _read_password {
2421 my ($prompt, $realm) = @_;
2422 print STDERR $prompt;
2423 STDERR->flush;
2424 require Term::ReadKey;
2425 Term::ReadKey::ReadMode('noecho');
2426 my $password = '';
2427 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2428 last if $key =~ /[\012\015]/; # \n\r
2429 $password .= $key;
2431 Term::ReadKey::ReadMode('restore');
2432 print STDERR "\n";
2433 STDERR->flush;
2434 $password;
2437 package main;
2440 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2441 $SVN::Node::dir.$SVN::Node::unknown.
2442 $SVN::Node::none.$SVN::Node::file.
2443 $SVN::Node::dir.$SVN::Node::unknown.
2444 $SVN::Auth::SSL::CNMISMATCH.
2445 $SVN::Auth::SSL::NOTYETVALID.
2446 $SVN::Auth::SSL::EXPIRED.
2447 $SVN::Auth::SSL::UNKNOWNCA.
2448 $SVN::Auth::SSL::OTHER;
2451 package SVN::Git::Fetcher;
2452 use vars qw/@ISA/;
2453 use strict;
2454 use warnings;
2455 use Carp qw/croak/;
2456 use IO::File qw//;
2457 use Digest::MD5;
2459 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2460 sub new {
2461 my ($class, $git_svn) = @_;
2462 my $self = SVN::Delta::Editor->new;
2463 bless $self, $class;
2464 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2465 $self->{empty} = {};
2466 $self->{dir_prop} = {};
2467 $self->{file_prop} = {};
2468 $self->{absent_dir} = {};
2469 $self->{absent_file} = {};
2470 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2471 $self;
2474 sub set_path_strip {
2475 my ($self, $path) = @_;
2476 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2479 sub open_root {
2480 { path => '' };
2483 sub open_directory {
2484 my ($self, $path, $pb, $rev) = @_;
2485 { path => $path };
2488 sub git_path {
2489 my ($self, $path) = @_;
2490 if ($self->{path_strip}) {
2491 $path =~ s!$self->{path_strip}!! or
2492 die "Failed to strip path '$path' ($self->{path_strip})\n";
2494 $path;
2497 sub delete_entry {
2498 my ($self, $path, $rev, $pb) = @_;
2500 my $gpath = $self->git_path($path);
2501 return undef if ($gpath eq '');
2503 # remove entire directories.
2504 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2505 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2506 -r --name-only -z/,
2507 $self->{c}, '--', $gpath);
2508 local $/ = "\0";
2509 while (<$ls>) {
2510 chomp;
2511 $self->{gii}->remove($_);
2512 print "\tD\t$_\n" unless $::_q;
2514 print "\tD\t$gpath/\n" unless $::_q;
2515 command_close_pipe($ls, $ctx);
2516 $self->{empty}->{$path} = 0
2517 } else {
2518 $self->{gii}->remove($gpath);
2519 print "\tD\t$gpath\n" unless $::_q;
2521 undef;
2524 sub open_file {
2525 my ($self, $path, $pb, $rev) = @_;
2526 my $gpath = $self->git_path($path);
2527 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2528 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2529 unless (defined $mode && defined $blob) {
2530 die "$path was not found in commit $self->{c} (r$rev)\n";
2532 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2533 pool => SVN::Pool->new, action => 'M' };
2536 sub add_file {
2537 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2538 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2539 delete $self->{empty}->{$dir};
2540 { path => $path, mode_a => 100644, mode_b => 100644,
2541 pool => SVN::Pool->new, action => 'A' };
2544 sub add_directory {
2545 my ($self, $path, $cp_path, $cp_rev) = @_;
2546 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2547 delete $self->{empty}->{$dir};
2548 $self->{empty}->{$path} = 1;
2549 { path => $path };
2552 sub change_dir_prop {
2553 my ($self, $db, $prop, $value) = @_;
2554 $self->{dir_prop}->{$db->{path}} ||= {};
2555 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2556 undef;
2559 sub absent_directory {
2560 my ($self, $path, $pb) = @_;
2561 $self->{absent_dir}->{$pb->{path}} ||= [];
2562 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2563 undef;
2566 sub absent_file {
2567 my ($self, $path, $pb) = @_;
2568 $self->{absent_file}->{$pb->{path}} ||= [];
2569 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2570 undef;
2573 sub change_file_prop {
2574 my ($self, $fb, $prop, $value) = @_;
2575 if ($prop eq 'svn:executable') {
2576 if ($fb->{mode_b} != 120000) {
2577 $fb->{mode_b} = defined $value ? 100755 : 100644;
2579 } elsif ($prop eq 'svn:special') {
2580 $fb->{mode_b} = defined $value ? 120000 : 100644;
2581 } else {
2582 $self->{file_prop}->{$fb->{path}} ||= {};
2583 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2585 undef;
2588 sub apply_textdelta {
2589 my ($self, $fb, $exp) = @_;
2590 my $fh = IO::File->new_tmpfile;
2591 $fh->autoflush(1);
2592 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2593 # (but $base does not,) so dup() it for reading in close_file
2594 open my $dup, '<&', $fh or croak $!;
2595 my $base = IO::File->new_tmpfile;
2596 $base->autoflush(1);
2597 if ($fb->{blob}) {
2598 defined (my $pid = fork) or croak $!;
2599 if (!$pid) {
2600 open STDOUT, '>&', $base or croak $!;
2601 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2602 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2604 waitpid $pid, 0;
2605 croak $? if $?;
2607 if (defined $exp) {
2608 seek $base, 0, 0 or croak $!;
2609 my $md5 = Digest::MD5->new;
2610 $md5->addfile($base);
2611 my $got = $md5->hexdigest;
2612 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2613 "expected: $exp\n",
2614 " got: $got\n" if ($got ne $exp);
2617 seek $base, 0, 0 or croak $!;
2618 $fb->{fh} = $dup;
2619 $fb->{base} = $base;
2620 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2623 sub close_file {
2624 my ($self, $fb, $exp) = @_;
2625 my $hash;
2626 my $path = $self->git_path($fb->{path});
2627 if (my $fh = $fb->{fh}) {
2628 if (defined $exp) {
2629 seek($fh, 0, 0) or croak $!;
2630 my $md5 = Digest::MD5->new;
2631 $md5->addfile($fh);
2632 my $got = $md5->hexdigest;
2633 if ($got ne $exp) {
2634 die "Checksum mismatch: $path\n",
2635 "expected: $exp\n got: $got\n";
2638 sysseek($fh, 0, 0) or croak $!;
2639 if ($fb->{mode_b} == 120000) {
2640 sysread($fh, my $buf, 5) == 5 or croak $!;
2641 $buf eq 'link ' or die "$path has mode 120000",
2642 "but is not a link\n";
2644 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2645 if (!$pid) {
2646 open STDIN, '<&', $fh or croak $!;
2647 exec qw/git-hash-object -w --stdin/ or croak $!;
2649 chomp($hash = do { local $/; <$out> });
2650 close $out or croak $!;
2651 close $fh or croak $!;
2652 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2653 close $fb->{base} or croak $!;
2654 } else {
2655 $hash = $fb->{blob} or die "no blob information\n";
2657 $fb->{pool}->clear;
2658 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2659 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2660 undef;
2663 sub abort_edit {
2664 my $self = shift;
2665 $self->{nr} = $self->{gii}->{nr};
2666 delete $self->{gii};
2667 $self->SUPER::abort_edit(@_);
2670 sub close_edit {
2671 my $self = shift;
2672 $self->{git_commit_ok} = 1;
2673 $self->{nr} = $self->{gii}->{nr};
2674 delete $self->{gii};
2675 $self->SUPER::close_edit(@_);
2678 package SVN::Git::Editor;
2679 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2680 use strict;
2681 use warnings;
2682 use Carp qw/croak/;
2683 use IO::File;
2684 use Digest::MD5;
2686 sub new {
2687 my ($class, $opts) = @_;
2688 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2689 die "$_ required!\n" unless (defined $opts->{$_});
2692 my $pool = SVN::Pool->new;
2693 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2694 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2695 $opts->{r}, $mods);
2697 # $opts->{ra} functions should not be used after this:
2698 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2699 $opts->{editor_cb}, $pool);
2700 my $self = SVN::Delta::Editor->new(@ce, $pool);
2701 bless $self, $class;
2702 foreach (qw/svn_path r tree_a tree_b/) {
2703 $self->{$_} = $opts->{$_};
2705 $self->{url} = $opts->{ra}->{url};
2706 $self->{mods} = $mods;
2707 $self->{types} = $types;
2708 $self->{pool} = $pool;
2709 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2710 $self->{rm} = { };
2711 $self->{path_prefix} = length $self->{svn_path} ?
2712 "$self->{svn_path}/" : '';
2713 return $self;
2716 sub generate_diff {
2717 my ($tree_a, $tree_b) = @_;
2718 my @diff_tree = qw(diff-tree -z -r);
2719 if ($_cp_similarity) {
2720 push @diff_tree, "-C$_cp_similarity";
2721 } else {
2722 push @diff_tree, '-C';
2724 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2725 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2726 push @diff_tree, $tree_a, $tree_b;
2727 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2728 local $/ = "\0";
2729 my $state = 'meta';
2730 my @mods;
2731 while (<$diff_fh>) {
2732 chomp $_; # this gets rid of the trailing "\0"
2733 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2734 $::sha1\s($::sha1)\s
2735 ([MTCRAD])\d*$/xo) {
2736 push @mods, { mode_a => $1, mode_b => $2,
2737 sha1_b => $3, chg => $4 };
2738 if ($4 =~ /^(?:C|R)$/) {
2739 $state = 'file_a';
2740 } else {
2741 $state = 'file_b';
2743 } elsif ($state eq 'file_a') {
2744 my $x = $mods[$#mods] or croak "Empty array\n";
2745 if ($x->{chg} !~ /^(?:C|R)$/) {
2746 croak "Error parsing $_, $x->{chg}\n";
2748 $x->{file_a} = $_;
2749 $state = 'file_b';
2750 } elsif ($state eq 'file_b') {
2751 my $x = $mods[$#mods] or croak "Empty array\n";
2752 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2753 croak "Error parsing $_, $x->{chg}\n";
2755 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2756 croak "Error parsing $_, $x->{chg}\n";
2758 $x->{file_b} = $_;
2759 $state = 'meta';
2760 } else {
2761 croak "Error parsing $_\n";
2764 command_close_pipe($diff_fh, $ctx);
2765 \@mods;
2768 sub check_diff_paths {
2769 my ($ra, $pfx, $rev, $mods) = @_;
2770 my %types;
2771 $pfx .= '/' if length $pfx;
2773 sub type_diff_paths {
2774 my ($ra, $types, $path, $rev) = @_;
2775 my @p = split m#/+#, $path;
2776 my $c = shift @p;
2777 unless (defined $types->{$c}) {
2778 $types->{$c} = $ra->check_path($c, $rev);
2780 while (@p) {
2781 $c .= '/' . shift @p;
2782 next if defined $types->{$c};
2783 $types->{$c} = $ra->check_path($c, $rev);
2787 foreach my $m (@$mods) {
2788 foreach my $f (qw/file_a file_b/) {
2789 next unless defined $m->{$f};
2790 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2791 if (length $pfx.$dir && ! defined $types{$dir}) {
2792 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2796 \%types;
2799 sub split_path {
2800 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2803 sub repo_path {
2804 my ($self, $path) = @_;
2805 $self->{path_prefix}.(defined $path ? $path : '');
2808 sub url_path {
2809 my ($self, $path) = @_;
2810 if ($self->{url} =~ m#^https?://#) {
2811 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2813 $self->{url} . '/' . $self->repo_path($path);
2816 sub rmdirs {
2817 my ($self) = @_;
2818 my $rm = $self->{rm};
2819 delete $rm->{''}; # we never delete the url we're tracking
2820 return unless %$rm;
2822 foreach (keys %$rm) {
2823 my @d = split m#/#, $_;
2824 my $c = shift @d;
2825 $rm->{$c} = 1;
2826 while (@d) {
2827 $c .= '/' . shift @d;
2828 $rm->{$c} = 1;
2831 delete $rm->{$self->{svn_path}};
2832 delete $rm->{''}; # we never delete the url we're tracking
2833 return unless %$rm;
2835 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2836 $self->{tree_b});
2837 local $/ = "\0";
2838 while (<$fh>) {
2839 chomp;
2840 my @dn = split m#/#, $_;
2841 while (pop @dn) {
2842 delete $rm->{join '/', @dn};
2844 unless (%$rm) {
2845 close $fh;
2846 return;
2849 command_close_pipe($fh, $ctx);
2851 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2852 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2853 $self->close_directory($bat->{$d}, $p);
2854 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2855 print "\tD+\t$d/\n" unless $::_q;
2856 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2857 delete $bat->{$d};
2861 sub open_or_add_dir {
2862 my ($self, $full_path, $baton) = @_;
2863 my $t = $self->{types}->{$full_path};
2864 if (!defined $t) {
2865 die "$full_path not known in r$self->{r} or we have a bug!\n";
2867 if ($t == $SVN::Node::none) {
2868 return $self->add_directory($full_path, $baton,
2869 undef, -1, $self->{pool});
2870 } elsif ($t == $SVN::Node::dir) {
2871 return $self->open_directory($full_path, $baton,
2872 $self->{r}, $self->{pool});
2874 print STDERR "$full_path already exists in repository at ",
2875 "r$self->{r} and it is not a directory (",
2876 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2877 exit 1;
2880 sub ensure_path {
2881 my ($self, $path) = @_;
2882 my $bat = $self->{bat};
2883 my $repo_path = $self->repo_path($path);
2884 return $bat->{''} unless (length $repo_path);
2885 my @p = split m#/+#, $repo_path;
2886 my $c = shift @p;
2887 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2888 while (@p) {
2889 my $c0 = $c;
2890 $c .= '/' . shift @p;
2891 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2893 return $bat->{$c};
2896 sub A {
2897 my ($self, $m) = @_;
2898 my ($dir, $file) = split_path($m->{file_b});
2899 my $pbat = $self->ensure_path($dir);
2900 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2901 undef, -1);
2902 print "\tA\t$m->{file_b}\n" unless $::_q;
2903 $self->chg_file($fbat, $m);
2904 $self->close_file($fbat,undef,$self->{pool});
2907 sub C {
2908 my ($self, $m) = @_;
2909 my ($dir, $file) = split_path($m->{file_b});
2910 my $pbat = $self->ensure_path($dir);
2911 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2912 $self->url_path($m->{file_a}), $self->{r});
2913 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2914 $self->chg_file($fbat, $m);
2915 $self->close_file($fbat,undef,$self->{pool});
2918 sub delete_entry {
2919 my ($self, $path, $pbat) = @_;
2920 my $rpath = $self->repo_path($path);
2921 my ($dir, $file) = split_path($rpath);
2922 $self->{rm}->{$dir} = 1;
2923 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2926 sub R {
2927 my ($self, $m) = @_;
2928 my ($dir, $file) = split_path($m->{file_b});
2929 my $pbat = $self->ensure_path($dir);
2930 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2931 $self->url_path($m->{file_a}), $self->{r});
2932 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2933 $self->chg_file($fbat, $m);
2934 $self->close_file($fbat,undef,$self->{pool});
2936 ($dir, $file) = split_path($m->{file_a});
2937 $pbat = $self->ensure_path($dir);
2938 $self->delete_entry($m->{file_a}, $pbat);
2941 sub M {
2942 my ($self, $m) = @_;
2943 my ($dir, $file) = split_path($m->{file_b});
2944 my $pbat = $self->ensure_path($dir);
2945 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2946 $pbat,$self->{r},$self->{pool});
2947 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2948 $self->chg_file($fbat, $m);
2949 $self->close_file($fbat,undef,$self->{pool});
2952 sub T { shift->M(@_) }
2954 sub change_file_prop {
2955 my ($self, $fbat, $pname, $pval) = @_;
2956 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2959 sub chg_file {
2960 my ($self, $fbat, $m) = @_;
2961 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2962 $self->change_file_prop($fbat,'svn:executable','*');
2963 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2964 $self->change_file_prop($fbat,'svn:executable',undef);
2966 my $fh = IO::File->new_tmpfile or croak $!;
2967 if ($m->{mode_b} =~ /^120/) {
2968 print $fh 'link ' or croak $!;
2969 $self->change_file_prop($fbat,'svn:special','*');
2970 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2971 $self->change_file_prop($fbat,'svn:special',undef);
2973 defined(my $pid = fork) or croak $!;
2974 if (!$pid) {
2975 open STDOUT, '>&', $fh or croak $!;
2976 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2978 waitpid $pid, 0;
2979 croak $? if $?;
2980 $fh->flush == 0 or croak $!;
2981 seek $fh, 0, 0 or croak $!;
2983 my $md5 = Digest::MD5->new;
2984 $md5->addfile($fh) or croak $!;
2985 seek $fh, 0, 0 or croak $!;
2987 my $exp = $md5->hexdigest;
2988 my $pool = SVN::Pool->new;
2989 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2990 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2991 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2992 $pool->clear;
2994 close $fh or croak $!;
2997 sub D {
2998 my ($self, $m) = @_;
2999 my ($dir, $file) = split_path($m->{file_b});
3000 my $pbat = $self->ensure_path($dir);
3001 print "\tD\t$m->{file_b}\n" unless $::_q;
3002 $self->delete_entry($m->{file_b}, $pbat);
3005 sub close_edit {
3006 my ($self) = @_;
3007 my ($p,$bat) = ($self->{pool}, $self->{bat});
3008 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3009 next if $_ eq '';
3010 $self->close_directory($bat->{$_}, $p);
3012 $self->close_directory($bat->{''}, $p);
3013 $self->SUPER::close_edit($p);
3014 $p->clear;
3017 sub abort_edit {
3018 my ($self) = @_;
3019 $self->SUPER::abort_edit($self->{pool});
3022 sub DESTROY {
3023 my $self = shift;
3024 $self->SUPER::DESTROY(@_);
3025 $self->{pool}->clear;
3028 # this drives the editor
3029 sub apply_diff {
3030 my ($self) = @_;
3031 my $mods = $self->{mods};
3032 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3033 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3034 my $f = $m->{chg};
3035 if (defined $o{$f}) {
3036 $self->$f($m);
3037 } else {
3038 fatal("Invalid change type: $f\n");
3041 $self->rmdirs if $_rmdir;
3042 if (@$mods == 0) {
3043 $self->abort_edit;
3044 } else {
3045 $self->close_edit;
3047 return scalar @$mods;
3050 package Git::SVN::Ra;
3051 use vars qw/@ISA $config_dir $_log_window_size/;
3052 use strict;
3053 use warnings;
3054 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3056 BEGIN {
3057 # enforce temporary pool usage for some simple functions
3058 no strict 'refs';
3059 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3060 my $SUPER = "SUPER::$f";
3061 *$f = sub {
3062 my $self = shift;
3063 my $pool = SVN::Pool->new;
3064 my @ret = $self->$SUPER(@_,$pool);
3065 $pool->clear;
3066 wantarray ? @ret : $ret[0];
3071 sub escape_uri_only {
3072 my ($uri) = @_;
3073 my @tmp;
3074 foreach (split m{/}, $uri) {
3075 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3076 push @tmp, $_;
3078 join('/', @tmp);
3081 sub escape_url {
3082 my ($url) = @_;
3083 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3084 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3085 $url = "$scheme://$domain$uri";
3087 $url;
3090 sub new {
3091 my ($class, $url) = @_;
3092 $url =~ s!/+$!!;
3093 return $RA if ($RA && $RA->{url} eq $url);
3095 SVN::_Core::svn_config_ensure($config_dir, undef);
3096 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3097 SVN::Client::get_simple_provider(),
3098 SVN::Client::get_ssl_server_trust_file_provider(),
3099 SVN::Client::get_simple_prompt_provider(
3100 \&Git::SVN::Prompt::simple, 2),
3101 SVN::Client::get_ssl_client_cert_file_provider(),
3102 SVN::Client::get_ssl_client_cert_prompt_provider(
3103 \&Git::SVN::Prompt::ssl_client_cert, 2),
3104 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3105 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3106 SVN::Client::get_username_provider(),
3107 SVN::Client::get_ssl_server_trust_prompt_provider(
3108 \&Git::SVN::Prompt::ssl_server_trust),
3109 SVN::Client::get_username_prompt_provider(
3110 \&Git::SVN::Prompt::username, 2),
3112 my $config = SVN::Core::config_get_config($config_dir);
3113 $RA = undef;
3114 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3115 config => $config,
3116 pool => SVN::Pool->new,
3117 auth_provider_callbacks => $callbacks);
3118 $self->{url} = $url;
3119 $self->{svn_path} = $url;
3120 $self->{repos_root} = $self->get_repos_root;
3121 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3122 $self->{cache} = { check_path => { r => 0, data => {} },
3123 get_dir => { r => 0, data => {} } };
3124 $RA = bless $self, $class;
3127 sub check_path {
3128 my ($self, $path, $r) = @_;
3129 my $cache = $self->{cache}->{check_path};
3130 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3131 return $cache->{data}->{$path};
3133 my $pool = SVN::Pool->new;
3134 my $t = $self->SUPER::check_path($path, $r, $pool);
3135 $pool->clear;
3136 if ($r != $cache->{r}) {
3137 %{$cache->{data}} = ();
3138 $cache->{r} = $r;
3140 $cache->{data}->{$path} = $t;
3143 sub get_dir {
3144 my ($self, $dir, $r) = @_;
3145 my $cache = $self->{cache}->{get_dir};
3146 if ($r == $cache->{r}) {
3147 if (my $x = $cache->{data}->{$dir}) {
3148 return wantarray ? @$x : $x->[0];
3151 my $pool = SVN::Pool->new;
3152 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3153 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3154 $pool->clear;
3155 if ($r != $cache->{r}) {
3156 %{$cache->{data}} = ();
3157 $cache->{r} = $r;
3159 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3160 wantarray ? (\%dirents, $r, $props) : \%dirents;
3163 sub DESTROY {
3164 # do not call the real DESTROY since we store ourselves in $RA
3167 sub get_log {
3168 my ($self, @args) = @_;
3169 my $pool = SVN::Pool->new;
3170 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3171 my $ret = $self->SUPER::get_log(@args, $pool);
3172 $pool->clear;
3173 $ret;
3176 sub get_commit_editor {
3177 my ($self, $log, $cb, $pool) = @_;
3178 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3179 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3182 sub gs_do_update {
3183 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3184 my $new = ($rev_a == $rev_b);
3185 my $path = $gs->{path};
3187 if ($new && -e $gs->{index}) {
3188 unlink $gs->{index} or die
3189 "Couldn't unlink index: $gs->{index}: $!\n";
3191 my $pool = SVN::Pool->new;
3192 $editor->set_path_strip($path);
3193 my (@pc) = split m#/#, $path;
3194 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3195 1, $editor, $pool);
3196 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3198 # Since we can't rely on svn_ra_reparent being available, we'll
3199 # just have to do some magic with set_path to make it so
3200 # we only want a partial path.
3201 my $sp = '';
3202 my $final = join('/', @pc);
3203 while (@pc) {
3204 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3205 $sp .= '/' if length $sp;
3206 $sp .= shift @pc;
3208 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3210 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3212 $reporter->finish_report($pool);
3213 $pool->clear;
3214 $editor->{git_commit_ok};
3217 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3218 # svn_ra_reparent didn't work before 1.4)
3219 sub gs_do_switch {
3220 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3221 my $path = $gs->{path};
3222 my $pool = SVN::Pool->new;
3224 my $full_url = $self->{url};
3225 my $old_url = $full_url;
3226 $full_url .= '/' . escape_uri_only($path) if length $path;
3227 my ($ra, $reparented);
3228 if ($old_url ne $full_url) {
3229 if ($old_url !~ m#^svn(\+ssh)?://#) {
3230 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3231 $pool);
3232 $self->{url} = $full_url;
3233 $reparented = 1;
3234 } else {
3235 $_[0] = undef;
3236 $self = undef;
3237 $RA = undef;
3238 $ra = Git::SVN::Ra->new($full_url);
3239 $ra_invalid = 1;
3242 $ra ||= $self;
3243 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3244 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3245 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3246 $reporter->finish_report($pool);
3248 if ($reparented) {
3249 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3250 $self->{url} = $old_url;
3253 $pool->clear;
3254 $editor->{git_commit_ok};
3257 sub longest_common_path {
3258 my ($gsv, $globs) = @_;
3259 my %common;
3260 my $common_max = scalar @$gsv;
3262 foreach my $gs (@$gsv) {
3263 my @tmp = split m#/#, $gs->{path};
3264 my $p = '';
3265 foreach (@tmp) {
3266 $p .= length($p) ? "/$_" : $_;
3267 $common{$p} ||= 0;
3268 $common{$p}++;
3271 $globs ||= [];
3272 $common_max += scalar @$globs;
3273 foreach my $glob (@$globs) {
3274 my @tmp = split m#/#, $glob->{path}->{left};
3275 my $p = '';
3276 foreach (@tmp) {
3277 $p .= length($p) ? "/$_" : $_;
3278 $common{$p} ||= 0;
3279 $common{$p}++;
3283 my $longest_path = '';
3284 foreach (sort {length $b <=> length $a} keys %common) {
3285 if ($common{$_} == $common_max) {
3286 $longest_path = $_;
3287 last;
3290 $longest_path;
3293 sub gs_fetch_loop_common {
3294 my ($self, $base, $head, $gsv, $globs) = @_;
3295 return if ($base > $head);
3296 my $inc = $_log_window_size;
3297 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3298 my $longest_path = longest_common_path($gsv, $globs);
3299 my $ra_url = $self->{url};
3300 while (1) {
3301 my %revs;
3302 my $err;
3303 my $err_handler = $SVN::Error::handler;
3304 $SVN::Error::handler = sub {
3305 ($err) = @_;
3306 skip_unknown_revs($err);
3308 sub _cb {
3309 my ($paths, $r, $author, $date, $log) = @_;
3310 [ dup_changed_paths($paths),
3311 { author => $author, date => $date, log => $log } ];
3313 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3314 sub { $revs{$_[1]} = _cb(@_) });
3315 if ($err && $max >= $head) {
3316 print STDERR "Path '$longest_path' ",
3317 "was probably deleted:\n",
3318 $err->expanded_message,
3319 "\nWill attempt to follow ",
3320 "revisions r$min .. r$max ",
3321 "committed before the deletion\n";
3322 my $hi = $max;
3323 while (--$hi >= $min) {
3324 my $ok;
3325 $self->get_log([$longest_path], $min, $hi,
3326 0, 1, 1, sub {
3327 $ok ||= $_[1];
3328 $revs{$_[1]} = _cb(@_) });
3329 if ($ok) {
3330 print STDERR "r$min .. r$ok OK\n";
3331 last;
3335 $SVN::Error::handler = $err_handler;
3337 my %exists = map { $_->{path} => $_ } @$gsv;
3338 foreach my $r (sort {$a <=> $b} keys %revs) {
3339 my ($paths, $logged) = @{$revs{$r}};
3341 foreach my $gs ($self->match_globs(\%exists, $paths,
3342 $globs, $r)) {
3343 if ($gs->rev_db_max >= $r) {
3344 next;
3346 next unless $gs->match_paths($paths, $r);
3347 $gs->{logged_rev_props} = $logged;
3348 if (my $last_commit = $gs->last_commit) {
3349 $gs->assert_index_clean($last_commit);
3351 my $log_entry = $gs->do_fetch($paths, $r);
3352 if ($log_entry) {
3353 $gs->do_git_commit($log_entry);
3356 foreach my $g (@$globs) {
3357 my $k = "svn-remote.$g->{remote}." .
3358 "$g->{t}-maxRev";
3359 Git::SVN::tmp_config($k, $r);
3361 if ($ra_invalid) {
3362 $_[0] = undef;
3363 $self = undef;
3364 $RA = undef;
3365 $self = Git::SVN::Ra->new($ra_url);
3366 $ra_invalid = undef;
3369 # pre-fill the .rev_db since it'll eventually get filled in
3370 # with '0' x40 if something new gets committed
3371 foreach my $gs (@$gsv) {
3372 next if defined $gs->rev_db_get($max);
3373 $gs->rev_db_set($max, 0 x40);
3375 foreach my $g (@$globs) {
3376 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3377 Git::SVN::tmp_config($k, $max);
3379 last if $max >= $head;
3380 $min = $max + 1;
3381 $max += $inc;
3382 $max = $head if ($max > $head);
3386 sub match_globs {
3387 my ($self, $exists, $paths, $globs, $r) = @_;
3389 sub get_dir_check {
3390 my ($self, $exists, $g, $r) = @_;
3391 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3392 return unless scalar @x == 3;
3393 my $dirents = $x[0];
3394 foreach my $de (keys %$dirents) {
3395 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3396 my $p = $g->{path}->full_path($de);
3397 next if $exists->{$p};
3398 next if (length $g->{path}->{right} &&
3399 ($self->check_path($p, $r) !=
3400 $SVN::Node::dir));
3401 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3402 $g->{ref}->full_path($de), 1);
3405 foreach my $g (@$globs) {
3406 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3407 if ($path->{action} =~ /^[AR]$/) {
3408 get_dir_check($self, $exists, $g, $r);
3411 foreach (keys %$paths) {
3412 if (/$g->{path}->{left_regex}/ &&
3413 !/$g->{path}->{regex}/) {
3414 next if $paths->{$_}->{action} !~ /^[AR]$/;
3415 get_dir_check($self, $exists, $g, $r);
3417 next unless /$g->{path}->{regex}/;
3418 my $p = $1;
3419 my $pathname = $g->{path}->full_path($p);
3420 next if $exists->{$pathname};
3421 next if ($self->check_path($pathname, $r) !=
3422 $SVN::Node::dir);
3423 $exists->{$pathname} = Git::SVN->init(
3424 $self->{url}, $pathname, undef,
3425 $g->{ref}->full_path($p), 1);
3427 my $c = '';
3428 foreach (split m#/#, $g->{path}->{left}) {
3429 $c .= "/$_";
3430 next unless ($paths->{$c} &&
3431 ($paths->{$c}->{action} =~ /^[AR]$/));
3432 get_dir_check($self, $exists, $g, $r);
3435 values %$exists;
3438 sub minimize_url {
3439 my ($self) = @_;
3440 return $self->{url} if ($self->{url} eq $self->{repos_root});
3441 my $url = $self->{repos_root};
3442 my @components = split(m!/!, $self->{svn_path});
3443 my $c = '';
3444 do {
3445 $url .= "/$c" if length $c;
3446 eval { (ref $self)->new($url)->get_latest_revnum };
3447 } while ($@ && ($c = shift @components));
3448 $url;
3451 sub can_do_switch {
3452 my $self = shift;
3453 unless (defined $can_do_switch) {
3454 my $pool = SVN::Pool->new;
3455 my $rep = eval {
3456 $self->do_switch(1, '', 0, $self->{url},
3457 SVN::Delta::Editor->new, $pool);
3459 if ($@) {
3460 $can_do_switch = 0;
3461 } else {
3462 $rep->abort_report($pool);
3463 $can_do_switch = 1;
3465 $pool->clear;
3467 $can_do_switch;
3470 sub skip_unknown_revs {
3471 my ($err) = @_;
3472 my $errno = $err->apr_err();
3473 # Maybe the branch we're tracking didn't
3474 # exist when the repo started, so it's
3475 # not an error if it doesn't, just continue
3477 # Wonderfully consistent library, eh?
3478 # 160013 - svn:// and file://
3479 # 175002 - http(s)://
3480 # 175007 - http(s):// (this repo required authorization, too...)
3481 # More codes may be discovered later...
3482 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3483 my $err_key = $err->expanded_message;
3484 # revision numbers change every time, filter them out
3485 $err_key =~ s/\d+/\0/g;
3486 $err_key = "$errno\0$err_key";
3487 unless ($ignored_err{$err_key}) {
3488 warn "W: Ignoring error from SVN, path probably ",
3489 "does not exist: ($errno): ",
3490 $err->expanded_message,"\n";
3491 $ignored_err{$err_key} = 1;
3493 return;
3495 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3498 # svn_log_changed_path_t objects passed to get_log are likely to be
3499 # overwritten even if only the refs are copied to an external variable,
3500 # so we should dup the structures in their entirety. Using an externally
3501 # passed pool (instead of our temporary and quickly cleared pool in
3502 # Git::SVN::Ra) does not help matters at all...
3503 sub dup_changed_paths {
3504 my ($paths) = @_;
3505 return undef unless $paths;
3506 my %ret;
3507 foreach my $p (keys %$paths) {
3508 my $i = $paths->{$p};
3509 my %s = map { $_ => $i->$_ }
3510 qw/copyfrom_path copyfrom_rev action/;
3511 $ret{$p} = \%s;
3513 \%ret;
3516 package Git::SVN::Log;
3517 use strict;
3518 use warnings;
3519 use POSIX qw/strftime/;
3520 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3521 %rusers $show_commit $incremental/;
3522 my $l_fmt;
3524 sub cmt_showable {
3525 my ($c) = @_;
3526 return 1 if defined $c->{r};
3528 # big commit message got truncated by the 16k pretty buffer in rev-list
3529 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3530 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3531 @{$c->{l}} = ();
3532 my @log = command(qw/cat-file commit/, $c->{c});
3534 # shift off the headers
3535 shift @log while ($log[0] ne '');
3536 shift @log;
3538 # TODO: make $c->{l} not have a trailing newline in the future
3539 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3541 (undef, $c->{r}, undef) = ::extract_metadata(
3542 (grep(/^git-svn-id: /, @log))[-1]);
3544 return defined $c->{r};
3547 sub log_use_color {
3548 return 1 if $color;
3549 my ($dc, $dcvar);
3550 $dcvar = 'color.diff';
3551 $dc = `git-config --get $dcvar`;
3552 if ($dc eq '') {
3553 # nothing at all; fallback to "diff.color"
3554 $dcvar = 'diff.color';
3555 $dc = `git-config --get $dcvar`;
3557 chomp($dc);
3558 if ($dc eq 'auto') {
3559 my $pc;
3560 $pc = `git-config --get color.pager`;
3561 if ($pc eq '') {
3562 # does not have it -- fallback to pager.color
3563 $pc = `git-config --bool --get pager.color`;
3565 else {
3566 $pc = `git-config --bool --get color.pager`;
3567 if ($?) {
3568 $pc = 'false';
3571 chomp($pc);
3572 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3573 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3575 return 0;
3577 return 0 if $dc eq 'never';
3578 return 1 if $dc eq 'always';
3579 chomp($dc = `git-config --bool --get $dcvar`);
3580 return ($dc eq 'true');
3583 sub git_svn_log_cmd {
3584 my ($r_min, $r_max, @args) = @_;
3585 my $head = 'HEAD';
3586 my (@files, @log_opts);
3587 foreach my $x (@args) {
3588 if ($x eq '--' || @files) {
3589 push @files, $x;
3590 } else {
3591 if (::verify_ref("$x^0")) {
3592 $head = $x;
3593 } else {
3594 push @log_opts, $x;
3599 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3600 $gs ||= Git::SVN->_new;
3601 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3602 $gs->refname);
3603 push @cmd, '-r' unless $non_recursive;
3604 push @cmd, qw/--raw --name-status/ if $verbose;
3605 push @cmd, '--color' if log_use_color();
3606 push @cmd, @log_opts;
3607 if (defined $r_max && $r_max == $r_min) {
3608 push @cmd, '--max-count=1';
3609 if (my $c = $gs->rev_db_get($r_max)) {
3610 push @cmd, $c;
3612 } elsif (defined $r_max) {
3613 my ($c_min, $c_max);
3614 $c_max = $gs->rev_db_get($r_max);
3615 $c_min = $gs->rev_db_get($r_min);
3616 if (defined $c_min && defined $c_max) {
3617 if ($r_max > $r_max) {
3618 push @cmd, "$c_min..$c_max";
3619 } else {
3620 push @cmd, "$c_max..$c_min";
3622 } elsif ($r_max > $r_min) {
3623 push @cmd, $c_max;
3624 } else {
3625 push @cmd, $c_min;
3628 return (@cmd, @files);
3631 # adapted from pager.c
3632 sub config_pager {
3633 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3634 if (!defined $pager) {
3635 $pager = 'less';
3636 } elsif (length $pager == 0 || $pager eq 'cat') {
3637 $pager = undef;
3641 sub run_pager {
3642 return unless -t *STDOUT && defined $pager;
3643 pipe my $rfd, my $wfd or return;
3644 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3645 if (!$pid) {
3646 open STDOUT, '>&', $wfd or
3647 ::fatal "Can't redirect to stdout: $!\n";
3648 return;
3650 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3651 $ENV{LESS} ||= 'FRSX';
3652 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3655 sub tz_to_s_offset {
3656 my ($tz) = @_;
3657 $tz =~ s/(\d\d)$//;
3658 return ($1 * 60) + ($tz * 3600);
3661 sub get_author_info {
3662 my ($dest, $author, $t, $tz) = @_;
3663 $author =~ s/(?:^\s*|\s*$)//g;
3664 $dest->{a_raw} = $author;
3665 my $au;
3666 if ($::_authors) {
3667 $au = $rusers{$author} || undef;
3669 if (!$au) {
3670 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3672 $dest->{t} = $t;
3673 $dest->{tz} = $tz;
3674 $dest->{a} = $au;
3675 # Date::Parse isn't in the standard Perl distro :(
3676 if ($tz =~ s/^\+//) {
3677 $t += tz_to_s_offset($tz);
3678 } elsif ($tz =~ s/^\-//) {
3679 $t -= tz_to_s_offset($tz);
3681 $dest->{t_utc} = $t;
3684 sub process_commit {
3685 my ($c, $r_min, $r_max, $defer) = @_;
3686 if (defined $r_min && defined $r_max) {
3687 if ($r_min == $c->{r} && $r_min == $r_max) {
3688 show_commit($c);
3689 return 0;
3691 return 1 if $r_min == $r_max;
3692 if ($r_min < $r_max) {
3693 # we need to reverse the print order
3694 return 0 if (defined $limit && --$limit < 0);
3695 push @$defer, $c;
3696 return 1;
3698 if ($r_min != $r_max) {
3699 return 1 if ($r_min < $c->{r});
3700 return 1 if ($r_max > $c->{r});
3703 return 0 if (defined $limit && --$limit < 0);
3704 show_commit($c);
3705 return 1;
3708 sub show_commit {
3709 my $c = shift;
3710 if ($oneline) {
3711 my $x = "\n";
3712 if (my $l = $c->{l}) {
3713 while ($l->[0] =~ /^\s*$/) { shift @$l }
3714 $x = $l->[0];
3716 $l_fmt ||= 'A' . length($c->{r});
3717 print 'r',pack($l_fmt, $c->{r}),' | ';
3718 print "$c->{c} | " if $show_commit;
3719 print $x;
3720 } else {
3721 show_commit_normal($c);
3725 sub show_commit_changed_paths {
3726 my ($c) = @_;
3727 return unless $c->{changed};
3728 print "Changed paths:\n", @{$c->{changed}};
3731 sub show_commit_normal {
3732 my ($c) = @_;
3733 print '-' x72, "\nr$c->{r} | ";
3734 print "$c->{c} | " if $show_commit;
3735 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3736 localtime($c->{t_utc})), ' | ';
3737 my $nr_line = 0;
3739 if (my $l = $c->{l}) {
3740 while ($l->[$#$l] eq "\n" && $#$l > 0
3741 && $l->[($#$l - 1)] eq "\n") {
3742 pop @$l;
3744 $nr_line = scalar @$l;
3745 if (!$nr_line) {
3746 print "1 line\n\n\n";
3747 } else {
3748 if ($nr_line == 1) {
3749 $nr_line = '1 line';
3750 } else {
3751 $nr_line .= ' lines';
3753 print $nr_line, "\n";
3754 show_commit_changed_paths($c);
3755 print "\n";
3756 print $_ foreach @$l;
3758 } else {
3759 print "1 line\n";
3760 show_commit_changed_paths($c);
3761 print "\n";
3764 foreach my $x (qw/raw stat diff/) {
3765 if ($c->{$x}) {
3766 print "\n";
3767 print $_ foreach @{$c->{$x}}
3772 sub cmd_show_log {
3773 my (@args) = @_;
3774 my ($r_min, $r_max);
3775 my $r_last = -1; # prevent dupes
3776 if (defined $TZ) {
3777 $ENV{TZ} = $TZ;
3778 } else {
3779 delete $ENV{TZ};
3781 if (defined $::_revision) {
3782 if ($::_revision =~ /^(\d+):(\d+)$/) {
3783 ($r_min, $r_max) = ($1, $2);
3784 } elsif ($::_revision =~ /^\d+$/) {
3785 $r_min = $r_max = $::_revision;
3786 } else {
3787 ::fatal "-r$::_revision is not supported, use ",
3788 "standard \'git log\' arguments instead\n";
3792 config_pager();
3793 @args = git_svn_log_cmd($r_min, $r_max, @args);
3794 my $log = command_output_pipe(@args);
3795 run_pager();
3796 my (@k, $c, $d, $stat);
3797 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3798 while (<$log>) {
3799 if (/^${esc_color}commit ($::sha1_short)/o) {
3800 my $cmt = $1;
3801 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3802 $r_last = $c->{r};
3803 process_commit($c, $r_min, $r_max, \@k) or
3804 goto out;
3806 $d = undef;
3807 $c = { c => $cmt };
3808 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3809 get_author_info($c, $1, $2, $3);
3810 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3811 # ignore
3812 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3813 push @{$c->{raw}}, $_;
3814 } elsif (/^${esc_color}[ACRMDT]\t/) {
3815 # we could add $SVN->{svn_path} here, but that requires
3816 # remote access at the moment (repo_path_split)...
3817 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3818 push @{$c->{changed}}, $_;
3819 } elsif (/^${esc_color}diff /o) {
3820 $d = 1;
3821 push @{$c->{diff}}, $_;
3822 } elsif ($d) {
3823 push @{$c->{diff}}, $_;
3824 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3825 $esc_color*[\+\-]*$esc_color$/x) {
3826 $stat = 1;
3827 push @{$c->{stat}}, $_;
3828 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3829 push @{$c->{stat}}, $_;
3830 $stat = undef;
3831 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3832 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3833 } elsif (s/^${esc_color} //o) {
3834 push @{$c->{l}}, $_;
3837 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3838 $r_last = $c->{r};
3839 process_commit($c, $r_min, $r_max, \@k);
3841 if (@k) {
3842 my $swap = $r_max;
3843 $r_max = $r_min;
3844 $r_min = $swap;
3845 process_commit($_, $r_min, $r_max) foreach reverse @k;
3847 out:
3848 close $log;
3849 print '-' x72,"\n" unless $incremental || $oneline;
3852 package Git::SVN::Migration;
3853 # these version numbers do NOT correspond to actual version numbers
3854 # of git nor git-svn. They are just relative.
3856 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3858 # v1 layout: .git/$id/info/url, refs/remotes/$id
3860 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3862 # v3 layout: .git/svn/$id, refs/remotes/$id
3863 # - info/url may remain for backwards compatibility
3864 # - this is what we migrate up to this layout automatically,
3865 # - this will be used by git svn init on single branches
3866 # v3.1 layout (auto migrated):
3867 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3868 # for backwards compatibility
3870 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3871 # - this is only created for newly multi-init-ed
3872 # repositories. Similar in spirit to the
3873 # --use-separate-remotes option in git-clone (now default)
3874 # - we do not automatically migrate to this (following
3875 # the example set by core git)
3876 use strict;
3877 use warnings;
3878 use Carp qw/croak/;
3879 use File::Path qw/mkpath/;
3880 use File::Basename qw/dirname basename/;
3881 use vars qw/$_minimize/;
3883 sub migrate_from_v0 {
3884 my $git_dir = $ENV{GIT_DIR};
3885 return undef unless -d $git_dir;
3886 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3887 my $migrated = 0;
3888 while (<$fh>) {
3889 chomp;
3890 my ($id, $orig_ref) = ($_, $_);
3891 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3892 next unless -f "$git_dir/$id/info/url";
3893 my $new_ref = "refs/remotes/$id";
3894 if (::verify_ref("$new_ref^0")) {
3895 print STDERR "W: $orig_ref is probably an old ",
3896 "branch used by an ancient version of ",
3897 "git-svn.\n",
3898 "However, $new_ref also exists.\n",
3899 "We will not be able ",
3900 "to use this branch until this ",
3901 "ambiguity is resolved.\n";
3902 next;
3904 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3905 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3906 command_noisy('update-ref', $new_ref, $orig_ref);
3907 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3908 $migrated++;
3910 command_close_pipe($fh, $ctx);
3911 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3912 $migrated;
3915 sub migrate_from_v1 {
3916 my $git_dir = $ENV{GIT_DIR};
3917 my $migrated = 0;
3918 return $migrated unless -d $git_dir;
3919 my $svn_dir = "$git_dir/svn";
3921 # just in case somebody used 'svn' as their $id at some point...
3922 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3924 print STDERR "Migrating from a git-svn v1 layout...\n";
3925 mkpath([$svn_dir]);
3926 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3927 "$svn_dir\n\t(required for this version ",
3928 "($::VERSION) of git-svn) does not. exist\n";
3929 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3930 while (<$fh>) {
3931 my $x = $_;
3932 next unless $x =~ s#^refs/remotes/##;
3933 chomp $x;
3934 next unless -f "$git_dir/$x/info/url";
3935 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3936 next unless $u;
3937 my $dn = dirname("$git_dir/svn/$x");
3938 mkpath([$dn]) unless -d $dn;
3939 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3940 mkpath(["$git_dir/svn/svn"]);
3941 print STDERR " - $git_dir/$x/info => ",
3942 "$git_dir/svn/$x/info\n";
3943 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3944 croak "$!: $x";
3945 # don't worry too much about these, they probably
3946 # don't exist with repos this old (save for index,
3947 # and we can easily regenerate that)
3948 foreach my $f (qw/unhandled.log index .rev_db/) {
3949 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3951 } else {
3952 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3953 rename "$git_dir/$x", "$git_dir/svn/$x" or
3954 croak "$!: $x";
3956 $migrated++;
3958 command_close_pipe($fh, $ctx);
3959 print STDERR "Done migrating from a git-svn v1 layout\n";
3960 $migrated;
3963 sub read_old_urls {
3964 my ($l_map, $pfx, $path) = @_;
3965 my @dir;
3966 foreach (<$path/*>) {
3967 if (-r "$_/info/url") {
3968 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3969 my $ref_id = $pfx . basename $_;
3970 my $url = ::file_to_s("$_/info/url");
3971 $l_map->{$ref_id} = $url;
3972 } elsif (-d $_) {
3973 push @dir, $_;
3976 foreach (@dir) {
3977 my $x = $_;
3978 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3979 read_old_urls($l_map, $x, $_);
3983 sub migrate_from_v2 {
3984 my @cfg = command(qw/config -l/);
3985 return if grep /^svn-remote\..+\.url=/, @cfg;
3986 my %l_map;
3987 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3988 my $migrated = 0;
3990 foreach my $ref_id (sort keys %l_map) {
3991 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3992 if ($@) {
3993 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3995 $migrated++;
3997 $migrated;
4000 sub minimize_connections {
4001 my $r = Git::SVN::read_all_remotes();
4002 my $new_urls = {};
4003 my $root_repos = {};
4004 foreach my $repo_id (keys %$r) {
4005 my $url = $r->{$repo_id}->{url} or next;
4006 my $fetch = $r->{$repo_id}->{fetch} or next;
4007 my $ra = Git::SVN::Ra->new($url);
4009 # skip existing cases where we already connect to the root
4010 if (($ra->{url} eq $ra->{repos_root}) ||
4011 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4012 $repo_id)) {
4013 $root_repos->{$ra->{url}} = $repo_id;
4014 next;
4017 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4018 my $root_path = $ra->{url};
4019 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4020 foreach my $path (keys %$fetch) {
4021 my $ref_id = $fetch->{$path};
4022 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4024 # make sure we can read when connecting to
4025 # a higher level of a repository
4026 my ($last_rev, undef) = $gs->last_rev_commit;
4027 if (!defined $last_rev) {
4028 $last_rev = eval {
4029 $root_ra->get_latest_revnum;
4031 next if $@;
4033 my $new = $root_path;
4034 $new .= length $path ? "/$path" : '';
4035 eval {
4036 $root_ra->get_log([$new], $last_rev, $last_rev,
4037 0, 0, 1, sub { });
4039 next if $@;
4040 $new_urls->{$ra->{repos_root}}->{$new} =
4041 { ref_id => $ref_id,
4042 old_repo_id => $repo_id,
4043 old_path => $path };
4047 my @emptied;
4048 foreach my $url (keys %$new_urls) {
4049 # see if we can re-use an existing [svn-remote "repo_id"]
4050 # instead of creating a(n ugly) new section:
4051 my $repo_id = $root_repos->{$url} ||
4052 Git::SVN::sanitize_remote_name($url);
4054 my $fetch = $new_urls->{$url};
4055 foreach my $path (keys %$fetch) {
4056 my $x = $fetch->{$path};
4057 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4058 my $pfx = "svn-remote.$x->{old_repo_id}";
4060 my $old_fetch = quotemeta("$x->{old_path}:".
4061 "refs/remotes/$x->{ref_id}");
4062 command_noisy(qw/config --unset/,
4063 "$pfx.fetch", '^'. $old_fetch . '$');
4064 delete $r->{$x->{old_repo_id}}->
4065 {fetch}->{$x->{old_path}};
4066 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4067 command_noisy(qw/config --unset/,
4068 "$pfx.url");
4069 push @emptied, $x->{old_repo_id}
4073 if (@emptied) {
4074 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4075 "$ENV{GIT_DIR}/config";
4076 print STDERR <<EOF;
4077 The following [svn-remote] sections in your config file ($file) are empty
4078 and can be safely removed:
4080 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4084 sub migration_check {
4085 migrate_from_v0();
4086 migrate_from_v1();
4087 migrate_from_v2();
4088 minimize_connections() if $_minimize;
4091 package Git::IndexInfo;
4092 use strict;
4093 use warnings;
4094 use Git qw/command_input_pipe command_close_pipe/;
4096 sub new {
4097 my ($class) = @_;
4098 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4099 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4102 sub remove {
4103 my ($self, $path) = @_;
4104 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4105 return ++$self->{nr};
4107 undef;
4110 sub update {
4111 my ($self, $mode, $hash, $path) = @_;
4112 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4113 return ++$self->{nr};
4115 undef;
4118 sub DESTROY {
4119 my ($self) = @_;
4120 command_close_pipe($self->{gui}, $self->{ctx});
4123 package Git::SVN::GlobSpec;
4124 use strict;
4125 use warnings;
4127 sub new {
4128 my ($class, $glob) = @_;
4129 my $re = $glob;
4130 $re =~ s!/+$!!g; # no need for trailing slashes
4131 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4132 my ($left, $right) = ($1, $2);
4133 if ($nr > 1) {
4134 die "Only one '*' wildcard expansion ",
4135 "is supported (got $nr): '$glob'\n";
4136 } elsif ($nr == 0) {
4137 die "One '*' is needed for glob: '$glob'\n";
4139 $re = quotemeta($left) . $re . quotemeta($right);
4140 if (length $left && !($left =~ s!/+$!!g)) {
4141 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4143 if (length $right && !($right =~ s!^/+!!g)) {
4144 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4146 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4147 bless { left => $left, right => $right, left_regex => $left_re,
4148 regex => qr/$re/, glob => $glob }, $class;
4151 sub full_path {
4152 my ($self, $path) = @_;
4153 return (length $self->{left} ? "$self->{left}/" : '') .
4154 $path . (length $self->{right} ? "/$self->{right}" : '');
4157 __END__
4159 Data structures:
4162 $remotes = { # returned by read_all_remotes()
4163 'svn' => {
4164 # svn-remote.svn.url=https://svn.musicpd.org
4165 url => 'https://svn.musicpd.org',
4166 # svn-remote.svn.fetch=mpd/trunk:trunk
4167 fetch => {
4168 'mpd/trunk' => 'trunk',
4170 # svn-remote.svn.tags=mpd/tags/*:tags/*
4171 tags => {
4172 path => {
4173 left => 'mpd/tags',
4174 right => '',
4175 regex => qr!mpd/tags/([^/]+)$!,
4176 glob => 'tags/*',
4178 ref => {
4179 left => 'tags',
4180 right => '',
4181 regex => qr!tags/([^/]+)$!,
4182 glob => 'tags/*',
4188 $log_entry hashref as returned by libsvn_log_entry()
4190 log => 'whitespace-formatted log entry
4191 ', # trailing newline is preserved
4192 revision => '8', # integer
4193 date => '2004-02-24T17:01:44.108345Z', # commit date
4194 author => 'committer name'
4198 # this is generated by generate_diff();
4199 @mods = array of diff-index line hashes, each element represents one line
4200 of diff-index output
4202 diff-index line ($m hash)
4204 mode_a => first column of diff-index output, no leading ':',
4205 mode_b => second column of diff-index output,
4206 sha1_b => sha1sum of the final blob,
4207 chg => change type [MCRADT],
4208 file_a => original file name of a file (iff chg is 'C' or 'R')
4209 file_b => new/current file name of a file (any chg)
4213 # retval of read_url_paths{,_all}();
4214 $l_map = {
4215 # repository root url
4216 'https://svn.musicpd.org' => {
4217 # repository path # GIT_SVN_ID
4218 'mpd/trunk' => 'trunk',
4219 'mpd/tags/0.11.5' => 'tags/0.11.5',
4223 Notes:
4224 I don't trust the each() function on unless I created %hash myself
4225 because the internal iterator may not have started at base.