Add zlib
[git/pclouds.git] / git-svn.perl
blob299b40f93829eeef982b04f7f53dbb2d6baf9a6a
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);
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 'minimize-url|m' => \$Git::SVN::_minimize_url,
86 'no-metadata' => sub { $icv{noMetadata} = 1 },
87 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
88 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
89 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
90 %remote_opts );
91 my %cmt_opts = ( 'edit|e' => \$_edit,
92 'rmdir' => \$SVN::Git::Editor::_rmdir,
93 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
94 'l=i' => \$SVN::Git::Editor::_rename_limit,
95 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
98 my %cmd = (
99 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
100 { 'revision|r=s' => \$_revision,
101 'fetch-all|all' => \$_fetch_all,
102 %fc_opts } ],
103 clone => [ \&cmd_clone, "Initialize and fetch revisions",
104 { 'revision|r=s' => \$_revision,
105 %fc_opts, %init_opts } ],
106 init => [ \&cmd_init, "Initialize a repo for tracking" .
107 " (requires URL argument)",
108 \%init_opts ],
109 'multi-init' => [ \&cmd_multi_init,
110 "Deprecated alias for ".
111 "'$0 init -T<trunk> -b<branches> -t<tags>'",
112 \%init_opts ],
113 dcommit => [ \&cmd_dcommit,
114 'Commit several diffs to merge with upstream',
115 { 'merge|m|M' => \$_merge,
116 'strategy|s=s' => \$_strategy,
117 'verbose|v' => \$_verbose,
118 'dry-run|n' => \$_dry_run,
119 'fetch-all|all' => \$_fetch_all,
120 'no-rebase' => \$_no_rebase,
121 %cmt_opts, %fc_opts } ],
122 'set-tree' => [ \&cmd_set_tree,
123 "Set an SVN repository to a git tree-ish",
124 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
125 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
126 { 'revision|r=i' => \$_revision } ],
127 'multi-fetch' => [ \&cmd_multi_fetch,
128 "Deprecated alias for $0 fetch --all",
129 { 'revision|r=s' => \$_revision, %fc_opts } ],
130 'migrate' => [ sub { },
131 # no-op, we automatically run this anyways,
132 'Migrate configuration/metadata/layout from
133 previous versions of git-svn',
134 { 'minimize' => \$Git::SVN::Migration::_minimize,
135 %remote_opts } ],
136 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
137 { 'limit=i' => \$Git::SVN::Log::limit,
138 'revision|r=s' => \$_revision,
139 'verbose|v' => \$Git::SVN::Log::verbose,
140 'incremental' => \$Git::SVN::Log::incremental,
141 'oneline' => \$Git::SVN::Log::oneline,
142 'show-commit' => \$Git::SVN::Log::show_commit,
143 'non-recursive' => \$Git::SVN::Log::non_recursive,
144 'authors-file|A=s' => \$_authors,
145 'color' => \$Git::SVN::Log::color,
146 'pager=s' => \$Git::SVN::Log::pager,
147 } ],
148 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
149 { } ],
150 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
151 { 'merge|m|M' => \$_merge,
152 'verbose|v' => \$_verbose,
153 'strategy|s=s' => \$_strategy,
154 'local|l' => \$_local,
155 'fetch-all|all' => \$_fetch_all,
156 %fc_opts } ],
157 'commit-diff' => [ \&cmd_commit_diff,
158 'Commit a diff between two trees',
159 { 'message|m=s' => \$_message,
160 'file|F=s' => \$_file,
161 'revision|r=s' => \$_revision,
162 %cmt_opts } ],
165 my $cmd;
166 for (my $i = 0; $i < @ARGV; $i++) {
167 if (defined $cmd{$ARGV[$i]}) {
168 $cmd = $ARGV[$i];
169 splice @ARGV, $i, 1;
170 last;
174 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
176 read_repo_config(\%opts);
177 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
178 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
179 'minimize-connections' => \$Git::SVN::Migration::_minimize,
180 'id|i=s' => \$Git::SVN::default_ref_id,
181 'svn-remote|remote|R=s' => sub {
182 $Git::SVN::no_reuse_existing = 1;
183 $Git::SVN::default_repo_id = $_[1] });
184 exit 1 if (!$rv && $cmd && $cmd ne 'log');
186 usage(0) if $_help;
187 version() if $_version;
188 usage(1) unless defined $cmd;
189 load_authors() if $_authors;
191 # make sure we're always running
192 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
193 unless (-d $ENV{GIT_DIR}) {
194 if ($git_dir_user_set) {
195 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
196 "but it is not a directory\n";
198 my $git_dir = delete $ENV{GIT_DIR};
199 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
200 unless (length $cdup) {
201 die "Already at toplevel, but $git_dir ",
202 "not found '$cdup'\n";
204 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
205 unless (-d $git_dir) {
206 die "$git_dir still not found after going to ",
207 "'$cdup'\n";
209 $ENV{GIT_DIR} = $git_dir;
212 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
213 Git::SVN::Migration::migration_check();
215 Git::SVN::init_vars();
216 eval {
217 Git::SVN::verify_remotes_sanity();
218 $cmd{$cmd}->[0]->(@ARGV);
220 fatal $@ if $@;
221 post_fetch_checkout();
222 exit 0;
224 ####################### primary functions ######################
225 sub usage {
226 my $exit = shift || 0;
227 my $fd = $exit ? \*STDERR : \*STDOUT;
228 print $fd <<"";
229 git-svn - bidirectional operations between a single Subversion tree and git
230 Usage: $0 <command> [options] [arguments]\n
232 print $fd "Available commands:\n" unless $cmd;
234 foreach (sort keys %cmd) {
235 next if $cmd && $cmd ne $_;
236 next if /^multi-/; # don't show deprecated commands
237 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
238 foreach (keys %{$cmd{$_}->[2]}) {
239 # mixed-case options are for .git/config only
240 next if /[A-Z]/ && /^[a-z]+$/i;
241 # prints out arguments as they should be passed:
242 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
243 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
244 "--$_" : "-$_" }
245 split /\|/,$_)," $x\n";
248 print $fd <<"";
249 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
250 arbitrary identifier if you're tracking multiple SVN branches/repositories in
251 one git repository and want to keep them separate. See git-svn(1) for more
252 information.
254 exit $exit;
257 sub version {
258 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
259 exit 0;
262 sub do_git_init_db {
263 unless (-d $ENV{GIT_DIR}) {
264 my @init_db = ('init');
265 push @init_db, "--template=$_template" if defined $_template;
266 if (defined $_shared) {
267 if ($_shared =~ /[a-z]/) {
268 push @init_db, "--shared=$_shared";
269 } else {
270 push @init_db, "--shared";
273 command_noisy(@init_db);
275 my $set;
276 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
277 foreach my $i (keys %icv) {
278 die "'$set' and '$i' cannot both be set\n" if $set;
279 next unless defined $icv{$i};
280 command_noisy('config', "$pfx.$i", $icv{$i});
281 $set = $i;
285 sub init_subdir {
286 my $repo_path = shift or return;
287 mkpath([$repo_path]) unless -d $repo_path;
288 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
289 $ENV{GIT_DIR} = '.git';
292 sub cmd_clone {
293 my ($url, $path) = @_;
294 if (!defined $path &&
295 (defined $_trunk || defined $_branches || defined $_tags) &&
296 $url !~ m#^[a-z\+]+://#) {
297 $path = $url;
299 $path = basename($url) if !defined $path || !length $path;
300 cmd_init($url, $path);
301 Git::SVN::fetch_all($Git::SVN::default_repo_id);
304 sub cmd_init {
305 if (defined $_trunk || defined $_branches || defined $_tags) {
306 return cmd_multi_init(@_);
308 my $url = shift or die "SVN repository location required ",
309 "as a command-line argument\n";
310 init_subdir(@_);
311 do_git_init_db();
313 Git::SVN->init($url);
316 sub cmd_fetch {
317 if (grep /^\d+=./, @_) {
318 die "'<rev>=<commit>' fetch arguments are ",
319 "no longer supported.\n";
321 my ($remote) = @_;
322 if (@_ > 1) {
323 die "Usage: $0 fetch [--all] [svn-remote]\n";
325 $remote ||= $Git::SVN::default_repo_id;
326 if ($_fetch_all) {
327 cmd_multi_fetch();
328 } else {
329 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
333 sub cmd_set_tree {
334 my (@commits) = @_;
335 if ($_stdin || !@commits) {
336 print "Reading from stdin...\n";
337 @commits = ();
338 while (<STDIN>) {
339 if (/\b($sha1_short)\b/o) {
340 unshift @commits, $1;
344 my @revs;
345 foreach my $c (@commits) {
346 my @tmp = command('rev-parse',$c);
347 if (scalar @tmp == 1) {
348 push @revs, $tmp[0];
349 } elsif (scalar @tmp > 1) {
350 push @revs, reverse(command('rev-list',@tmp));
351 } else {
352 fatal "Failed to rev-parse $c\n";
355 my $gs = Git::SVN->new;
356 my ($r_last, $cmt_last) = $gs->last_rev_commit;
357 $gs->fetch;
358 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
359 fatal "There are new revisions that were fetched ",
360 "and need to be merged (or acknowledged) ",
361 "before committing.\nlast rev: $r_last\n",
362 " current: $gs->{last_rev}\n";
364 $gs->set_tree($_) foreach @revs;
365 print "Done committing ",scalar @revs," revisions to SVN\n";
368 sub cmd_dcommit {
369 my $head = shift;
370 $head ||= 'HEAD';
371 my @refs;
372 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
373 unless ($gs) {
374 die "Unable to determine upstream SVN information from ",
375 "$head history\n";
377 my $last_rev;
378 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
379 foreach my $d (@$linear_refs) {
380 unless (defined $last_rev) {
381 (undef, $last_rev, undef) = cmt_metadata("$d~1");
382 unless (defined $last_rev) {
383 fatal "Unable to extract revision information ",
384 "from commit $d~1\n";
387 if ($_dry_run) {
388 print "diff-tree $d~1 $d\n";
389 } else {
390 my %ed_opts = ( r => $last_rev,
391 log => get_commit_entry($d)->{log},
392 ra => Git::SVN::Ra->new($gs->full_url),
393 tree_a => "$d~1",
394 tree_b => $d,
395 editor_cb => sub {
396 print "Committed r$_[0]\n";
397 $last_rev = $_[0]; },
398 svn_path => '');
399 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
400 print "No changes\n$d~1 == $d\n";
401 } elsif ($parents->{$d} && @{$parents->{$d}}) {
402 $gs->{inject_parents_dcommit}->{$last_rev} =
403 $parents->{$d};
407 return if $_dry_run;
408 unless ($gs) {
409 warn "Could not determine fetch information for $url\n",
410 "Will not attempt to fetch and rebase commits.\n",
411 "This probably means you have useSvmProps and should\n",
412 "now resync your SVN::Mirror repository.\n";
413 return;
415 $_fetch_all ? $gs->fetch_all : $gs->fetch;
416 unless ($_no_rebase) {
417 # we always want to rebase against the current HEAD, not any
418 # head that was passed to us
419 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
420 my @finish;
421 if (@diff) {
422 @finish = rebase_cmd();
423 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
424 "using @finish:\n", "@diff";
425 } else {
426 print "No changes between current HEAD and ",
427 $gs->refname, "\nResetting to the latest ",
428 $gs->refname, "\n";
429 @finish = qw/reset --mixed/;
431 command_noisy(@finish, $gs->refname);
435 sub cmd_find_rev {
436 my $revision_or_hash = shift;
437 my $result;
438 if ($revision_or_hash =~ /^r\d+$/) {
439 my $head = shift;
440 $head ||= 'HEAD';
441 my @refs;
442 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
443 unless ($gs) {
444 die "Unable to determine upstream SVN information from ",
445 "$head history\n";
447 my $desired_revision = substr($revision_or_hash, 1);
448 $result = $gs->rev_db_get($desired_revision);
449 } else {
450 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
451 $result = $rev;
453 print "$result\n" if $result;
456 sub cmd_rebase {
457 command_noisy(qw/update-index --refresh/);
458 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
459 unless ($gs) {
460 die "Unable to determine upstream SVN information from ",
461 "working tree history\n";
463 if (command(qw/diff-index HEAD --/)) {
464 print STDERR "Cannot rebase with uncommited changes:\n";
465 command_noisy('status');
466 exit 1;
468 unless ($_local) {
469 $_fetch_all ? $gs->fetch_all : $gs->fetch;
471 command_noisy(rebase_cmd(), $gs->refname);
474 sub cmd_show_ignore {
475 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
476 $gs ||= Git::SVN->new;
477 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
478 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
481 sub cmd_multi_init {
482 my $url = shift;
483 unless (defined $_trunk || defined $_branches || defined $_tags) {
484 usage(1);
487 # there are currently some bugs that prevent multi-init/multi-fetch
488 # setups from working well without this.
489 $Git::SVN::_minimize_url = 1;
491 $_prefix = '' unless defined $_prefix;
492 if (defined $url) {
493 $url =~ s#/+$##;
494 init_subdir(@_);
496 do_git_init_db();
497 if (defined $_trunk) {
498 my $trunk_ref = $_prefix . 'trunk';
499 # try both old-style and new-style lookups:
500 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
501 unless ($gs_trunk) {
502 my ($trunk_url, $trunk_path) =
503 complete_svn_url($url, $_trunk);
504 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
505 undef, $trunk_ref);
508 return unless defined $_branches || defined $_tags;
509 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
510 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
511 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
514 sub cmd_multi_fetch {
515 my $remotes = Git::SVN::read_all_remotes();
516 foreach my $repo_id (sort keys %$remotes) {
517 if ($remotes->{$repo_id}->{url}) {
518 Git::SVN::fetch_all($repo_id, $remotes);
523 # this command is special because it requires no metadata
524 sub cmd_commit_diff {
525 my ($ta, $tb, $url) = @_;
526 my $usage = "Usage: $0 commit-diff -r<revision> ".
527 "<tree-ish> <tree-ish> [<URL>]\n";
528 fatal($usage) if (!defined $ta || !defined $tb);
529 my $svn_path;
530 if (!defined $url) {
531 my $gs = eval { Git::SVN->new };
532 if (!$gs) {
533 fatal("Needed URL or usable git-svn --id in ",
534 "the command-line\n", $usage);
536 $url = $gs->{url};
537 $svn_path = $gs->{path};
539 unless (defined $_revision) {
540 fatal("-r|--revision is a required argument\n", $usage);
542 if (defined $_message && defined $_file) {
543 fatal("Both --message/-m and --file/-F specified ",
544 "for the commit message.\n",
545 "I have no idea what you mean\n");
547 if (defined $_file) {
548 $_message = file_to_s($_file);
549 } else {
550 $_message ||= get_commit_entry($tb)->{log};
552 my $ra ||= Git::SVN::Ra->new($url);
553 $svn_path ||= $ra->{svn_path};
554 my $r = $_revision;
555 if ($r eq 'HEAD') {
556 $r = $ra->get_latest_revnum;
557 } elsif ($r !~ /^\d+$/) {
558 die "revision argument: $r not understood by git-svn\n";
560 my %ed_opts = ( r => $r,
561 log => $_message,
562 ra => $ra,
563 tree_a => $ta,
564 tree_b => $tb,
565 editor_cb => sub { print "Committed r$_[0]\n" },
566 svn_path => $svn_path );
567 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
568 print "No changes\n$ta == $tb\n";
572 ########################### utility functions #########################
574 sub rebase_cmd {
575 my @cmd = qw/rebase/;
576 push @cmd, '-v' if $_verbose;
577 push @cmd, qw/--merge/ if $_merge;
578 push @cmd, "--strategy=$_strategy" if $_strategy;
579 @cmd;
582 sub post_fetch_checkout {
583 return if $_no_checkout;
584 my $gs = $Git::SVN::_head or return;
585 return if verify_ref('refs/heads/master^0');
587 my $valid_head = verify_ref('HEAD^0');
588 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
589 return if ($valid_head || !verify_ref('HEAD^0'));
591 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
592 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
593 return if -f $index;
595 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
596 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
597 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
598 print STDERR "Checked out HEAD:\n ",
599 $gs->full_url, " r", $gs->last_rev, "\n";
602 sub complete_svn_url {
603 my ($url, $path) = @_;
604 $path =~ s#/+$##;
605 if ($path !~ m#^[a-z\+]+://#) {
606 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
607 fatal("E: '$path' is not a complete URL ",
608 "and a separate URL is not specified\n");
610 return ($url, $path);
612 return ($path, '');
615 sub complete_url_ls_init {
616 my ($ra, $repo_path, $switch, $pfx) = @_;
617 unless ($repo_path) {
618 print STDERR "W: $switch not specified\n";
619 return;
621 $repo_path =~ s#/+$##;
622 if ($repo_path =~ m#^[a-z\+]+://#) {
623 $ra = Git::SVN::Ra->new($repo_path);
624 $repo_path = '';
625 } else {
626 $repo_path =~ s#^/+##;
627 unless ($ra) {
628 fatal("E: '$repo_path' is not a complete URL ",
629 "and a separate URL is not specified\n");
632 my $url = $ra->{url};
633 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
634 my $k = "svn-remote.$gs->{repo_id}.url";
635 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
636 if ($orig_url && ($orig_url ne $gs->{url})) {
637 die "$k already set: $orig_url\n",
638 "wanted to set to: $gs->{url}\n";
640 command_oneline('config', $k, $gs->{url}) unless $orig_url;
641 my $remote_path = "$ra->{svn_path}/$repo_path/*";
642 $remote_path =~ s#/+#/#g;
643 $remote_path =~ s#^/##g;
644 my ($n) = ($switch =~ /^--(\w+)/);
645 if (length $pfx && $pfx !~ m#/$#) {
646 die "--prefix='$pfx' must have a trailing slash '/'\n";
648 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
649 "$remote_path:refs/remotes/$pfx*");
652 sub verify_ref {
653 my ($ref) = @_;
654 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
655 { STDERR => 0 }); };
658 sub get_tree_from_treeish {
659 my ($treeish) = @_;
660 # $treeish can be a symbolic ref, too:
661 my $type = command_oneline(qw/cat-file -t/, $treeish);
662 my $expected;
663 while ($type eq 'tag') {
664 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
666 if ($type eq 'commit') {
667 $expected = (grep /^tree /, command(qw/cat-file commit/,
668 $treeish))[0];
669 ($expected) = ($expected =~ /^tree ($sha1)$/o);
670 die "Unable to get tree from $treeish\n" unless $expected;
671 } elsif ($type eq 'tree') {
672 $expected = $treeish;
673 } else {
674 die "$treeish is a $type, expected tree, tag or commit\n";
676 return $expected;
679 sub get_commit_entry {
680 my ($treeish) = shift;
681 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
682 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
683 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
684 open my $log_fh, '>', $commit_editmsg or croak $!;
686 my $type = command_oneline(qw/cat-file -t/, $treeish);
687 if ($type eq 'commit' || $type eq 'tag') {
688 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
689 $type, $treeish);
690 my $in_msg = 0;
691 while (<$msg_fh>) {
692 if (!$in_msg) {
693 $in_msg = 1 if (/^\s*$/);
694 } elsif (/^git-svn-id: /) {
695 # skip this for now, we regenerate the
696 # correct one on re-fetch anyways
697 # TODO: set *:merge properties or like...
698 } else {
699 print $log_fh $_ or croak $!;
702 command_close_pipe($msg_fh, $ctx);
704 close $log_fh or croak $!;
706 if ($_edit || ($type eq 'tree')) {
707 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
708 # TODO: strip out spaces, comments, like git-commit.sh
709 system($editor, $commit_editmsg);
711 rename $commit_editmsg, $commit_msg or croak $!;
712 open $log_fh, '<', $commit_msg or croak $!;
713 { local $/; chomp($log_entry{log} = <$log_fh>); }
714 close $log_fh or croak $!;
715 unlink $commit_msg;
716 \%log_entry;
719 sub s_to_file {
720 my ($str, $file, $mode) = @_;
721 open my $fd,'>',$file or croak $!;
722 print $fd $str,"\n" or croak $!;
723 close $fd or croak $!;
724 chmod ($mode &~ umask, $file) if (defined $mode);
727 sub file_to_s {
728 my $file = shift;
729 open my $fd,'<',$file or croak "$!: file: $file\n";
730 local $/;
731 my $ret = <$fd>;
732 close $fd or croak $!;
733 $ret =~ s/\s*$//s;
734 return $ret;
737 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
738 sub load_authors {
739 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
740 my $log = $cmd eq 'log';
741 while (<$authors>) {
742 chomp;
743 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
744 my ($user, $name, $email) = ($1, $2, $3);
745 if ($log) {
746 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
747 } else {
748 $users{$user} = [$name, $email];
751 close $authors or croak $!;
754 # convert GetOpt::Long specs for use by git-config
755 sub read_repo_config {
756 return unless -d $ENV{GIT_DIR};
757 my $opts = shift;
758 my @config_only;
759 foreach my $o (keys %$opts) {
760 # if we have mixedCase and a long option-only, then
761 # it's a config-only variable that we don't need for
762 # the command-line.
763 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
764 my $v = $opts->{$o};
765 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
766 $key =~ s/-//g;
767 my $arg = 'git-config';
768 $arg .= ' --int' if ($o =~ /[:=]i$/);
769 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
770 if (ref $v eq 'ARRAY') {
771 chomp(my @tmp = `$arg --get-all svn.$key`);
772 @$v = @tmp if @tmp;
773 } else {
774 chomp(my $tmp = `$arg --get svn.$key`);
775 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
776 $$v = $tmp;
780 delete @$opts{@config_only} if @config_only;
783 sub extract_metadata {
784 my $id = shift or return (undef, undef, undef);
785 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
786 \s([a-f\d\-]+)$/x);
787 if (!defined $rev || !$uuid || !$url) {
788 # some of the original repositories I made had
789 # identifiers like this:
790 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
792 return ($url, $rev, $uuid);
795 sub cmt_metadata {
796 return extract_metadata((grep(/^git-svn-id: /,
797 command(qw/cat-file commit/, shift)))[-1]);
800 sub working_head_info {
801 my ($head, $refs) = @_;
802 my ($fh, $ctx) = command_output_pipe('log', $head);
803 my $hash;
804 my %max;
805 while (<$fh>) {
806 if ( m{^commit ($::sha1)$} ) {
807 unshift @$refs, $hash if $hash and $refs;
808 $hash = $1;
809 next;
811 next unless s{^\s*(git-svn-id:)}{$1};
812 my ($url, $rev, $uuid) = extract_metadata($_);
813 if (defined $url && defined $rev) {
814 next if $max{$url} and $max{$url} < $rev;
815 if (my $gs = Git::SVN->find_by_url($url)) {
816 my $c = $gs->rev_db_get($rev);
817 if ($c && $c eq $hash) {
818 close $fh; # break the pipe
819 return ($url, $rev, $uuid, $gs);
820 } else {
821 $max{$url} ||= $gs->rev_db_max;
826 command_close_pipe($fh, $ctx);
827 (undef, undef, undef, undef);
830 sub read_commit_parents {
831 my ($parents, $c) = @_;
832 my ($fh, $ctx) = command_output_pipe(qw/cat-file commit/, $c);
833 while (<$fh>) {
834 chomp;
835 last if '';
836 /^parent ($sha1)/ or next;
837 push @{$parents->{$c}}, $1;
839 close $fh; # break the pipe
842 sub linearize_history {
843 my ($gs, $refs) = @_;
844 my %parents;
845 foreach my $c (@$refs) {
846 read_commit_parents(\%parents, $c);
849 my @linear_refs;
850 my %skip = ();
851 my $last_svn_commit = $gs->last_commit;
852 foreach my $c (reverse @$refs) {
853 next if $c eq $last_svn_commit;
854 last if $skip{$c};
856 unshift @linear_refs, $c;
857 $skip{$c} = 1;
859 # we only want the first parent to diff against for linear
860 # history, we save the rest to inject when we finalize the
861 # svn commit
862 my $fp_a = verify_ref("$c~1");
863 my $fp_b = shift @{$parents{$c}} if $parents{$c};
864 if (!$fp_a || !$fp_b) {
865 die "Commit $c\n",
866 "has no parent commit, and therefore ",
867 "nothing to diff against.\n",
868 "You should be working from a repository ",
869 "originally created by git-svn\n";
871 if ($fp_a ne $fp_b) {
872 die "$c~1 = $fp_a, however parsing commit $c ",
873 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
876 foreach my $p (@{$parents{$c}}) {
877 $skip{$p} = 1;
880 (\@linear_refs, \%parents);
883 package Git::SVN;
884 use strict;
885 use warnings;
886 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
887 $_repack $_repack_flags $_use_svm_props $_head
888 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
889 use Carp qw/croak/;
890 use File::Path qw/mkpath/;
891 use File::Copy qw/copy/;
892 use IPC::Open3;
894 my $_repack_nr;
895 # properties that we do not log:
896 my %SKIP_PROP;
897 BEGIN {
898 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
899 svn:special svn:executable
900 svn:entry:committed-rev
901 svn:entry:last-author
902 svn:entry:uuid
903 svn:entry:committed-date/;
905 # some options are read globally, but can be overridden locally
906 # per [svn-remote "..."] section. Command-line options will *NOT*
907 # override options set in an [svn-remote "..."] section
908 no strict 'refs';
909 for my $option (qw/follow_parent no_metadata use_svm_props
910 use_svnsync_props/) {
911 my $key = $option;
912 $key =~ tr/_//d;
913 my $prop = "-$option";
914 *$option = sub {
915 my ($self) = @_;
916 return $self->{$prop} if exists $self->{$prop};
917 my $k = "svn-remote.$self->{repo_id}.$key";
918 eval { command_oneline(qw/config --get/, $k) };
919 if ($@) {
920 $self->{$prop} = ${"Git::SVN::_$option"};
921 } else {
922 my $v = command_oneline(qw/config --bool/,$k);
923 $self->{$prop} = $v eq 'false' ? 0 : 1;
925 return $self->{$prop};
930 my %LOCKFILES;
931 END { unlink keys %LOCKFILES if %LOCKFILES }
933 sub resolve_local_globs {
934 my ($url, $fetch, $glob_spec) = @_;
935 return unless defined $glob_spec;
936 my $ref = $glob_spec->{ref};
937 my $path = $glob_spec->{path};
938 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
939 next unless m#^refs/remotes/$ref->{regex}$#;
940 my $p = $1;
941 my $pathname = $path->full_path($p);
942 my $refname = $ref->full_path($p);
943 if (my $existing = $fetch->{$pathname}) {
944 if ($existing ne $refname) {
945 die "Refspec conflict:\n",
946 "existing: refs/remotes/$existing\n",
947 " globbed: refs/remotes/$refname\n";
949 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
950 $u =~ s!^\Q$url\E(/|$)!! or die
951 "refs/remotes/$refname: '$url' not found in '$u'\n";
952 if ($pathname ne $u) {
953 warn "W: Refspec glob conflict ",
954 "(ref: refs/remotes/$refname):\n",
955 "expected path: $pathname\n",
956 " real path: $u\n",
957 "Continuing ahead with $u\n";
958 next;
960 } else {
961 $fetch->{$pathname} = $refname;
966 sub parse_revision_argument {
967 my ($base, $head) = @_;
968 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
969 return ($base, $head);
971 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
972 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
973 return ($head, $head) if ($::_revision eq 'HEAD');
974 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
975 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
976 die "revision argument: $::_revision not understood by git-svn\n";
979 sub fetch_all {
980 my ($repo_id, $remotes) = @_;
981 if (ref $repo_id) {
982 my $gs = $repo_id;
983 $repo_id = undef;
984 $repo_id = $gs->{repo_id};
986 $remotes ||= read_all_remotes();
987 my $remote = $remotes->{$repo_id} or
988 die "[svn-remote \"$repo_id\"] unknown\n";
989 my $fetch = $remote->{fetch};
990 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
991 my (@gs, @globs);
992 my $ra = Git::SVN::Ra->new($url);
993 my $uuid = $ra->get_uuid;
994 my $head = $ra->get_latest_revnum;
995 my $base = defined $fetch ? $head : 0;
997 # read the max revs for wildcard expansion (branches/*, tags/*)
998 foreach my $t (qw/branches tags/) {
999 defined $remote->{$t} or next;
1000 push @globs, $remote->{$t};
1001 my $max_rev = eval { tmp_config(qw/--int --get/,
1002 "svn-remote.$repo_id.${t}-maxRev") };
1003 if (defined $max_rev && ($max_rev < $base)) {
1004 $base = $max_rev;
1005 } elsif (!defined $max_rev) {
1006 $base = 0;
1010 if ($fetch) {
1011 foreach my $p (sort keys %$fetch) {
1012 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1013 my $lr = $gs->rev_db_max;
1014 if (defined $lr) {
1015 $base = $lr if ($lr < $base);
1017 push @gs, $gs;
1021 ($base, $head) = parse_revision_argument($base, $head);
1022 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1025 sub read_all_remotes {
1026 my $r = {};
1027 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1028 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1029 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1030 $local_ref =~ s{^/}{};
1031 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1032 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1033 $r->{$1}->{url} = $2;
1034 } elsif (m!^(.+)\.(branches|tags)=
1035 (.*):refs/remotes/(.+)\s*$/!x) {
1036 my ($p, $g) = ($3, $4);
1037 my $rs = $r->{$1}->{$2} = {
1038 t => $2,
1039 remote => $1,
1040 path => Git::SVN::GlobSpec->new($p),
1041 ref => Git::SVN::GlobSpec->new($g) };
1042 if (length($rs->{ref}->{right}) != 0) {
1043 die "The '*' glob character must be the last ",
1044 "character of '$g'\n";
1051 sub init_vars {
1052 if (defined $_repack) {
1053 $_repack = 1000 if ($_repack <= 0);
1054 $_repack_nr = $_repack;
1055 $_repack_flags ||= '-d';
1059 sub verify_remotes_sanity {
1060 return unless -d $ENV{GIT_DIR};
1061 my %seen;
1062 foreach (command(qw/config -l/)) {
1063 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1064 if ($seen{$1}) {
1065 die "Remote ref refs/remote/$1 is tracked by",
1066 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1067 "Please resolve this ambiguity in ",
1068 "your git configuration file before ",
1069 "continuing\n";
1071 $seen{$1} = $_;
1076 # we allow more chars than remotes2config.sh...
1077 sub sanitize_remote_name {
1078 my ($name) = @_;
1079 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1080 $name;
1083 sub find_existing_remote {
1084 my ($url, $remotes) = @_;
1085 return undef if $no_reuse_existing;
1086 my $existing;
1087 foreach my $repo_id (keys %$remotes) {
1088 my $u = $remotes->{$repo_id}->{url} or next;
1089 next if $u ne $url;
1090 $existing = $repo_id;
1091 last;
1093 $existing;
1096 sub init_remote_config {
1097 my ($self, $url, $no_write) = @_;
1098 $url =~ s!/+$!!; # strip trailing slash
1099 my $r = read_all_remotes();
1100 my $existing = find_existing_remote($url, $r);
1101 if ($existing) {
1102 unless ($no_write) {
1103 print STDERR "Using existing ",
1104 "[svn-remote \"$existing\"]\n";
1106 $self->{repo_id} = $existing;
1107 } elsif ($_minimize_url) {
1108 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1109 $existing = find_existing_remote($min_url, $r);
1110 if ($existing) {
1111 unless ($no_write) {
1112 print STDERR "Using existing ",
1113 "[svn-remote \"$existing\"]\n";
1115 $self->{repo_id} = $existing;
1117 if ($min_url ne $url) {
1118 unless ($no_write) {
1119 print STDERR "Using higher level of URL: ",
1120 "$url => $min_url\n";
1122 my $old_path = $self->{path};
1123 $self->{path} = $url;
1124 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1125 if (length $old_path) {
1126 $self->{path} .= "/$old_path";
1128 $url = $min_url;
1131 my $orig_url;
1132 if (!$existing) {
1133 # verify that we aren't overwriting anything:
1134 $orig_url = eval {
1135 command_oneline('config', '--get',
1136 "svn-remote.$self->{repo_id}.url")
1138 if ($orig_url && ($orig_url ne $url)) {
1139 die "svn-remote.$self->{repo_id}.url already set: ",
1140 "$orig_url\nwanted to set to: $url\n";
1143 my ($xrepo_id, $xpath) = find_ref($self->refname);
1144 if (defined $xpath) {
1145 die "svn-remote.$xrepo_id.fetch already set to track ",
1146 "$xpath:refs/remotes/", $self->refname, "\n";
1148 unless ($no_write) {
1149 command_noisy('config',
1150 "svn-remote.$self->{repo_id}.url", $url);
1151 $self->{path} =~ s{^/}{};
1152 command_noisy('config', '--add',
1153 "svn-remote.$self->{repo_id}.fetch",
1154 "$self->{path}:".$self->refname);
1156 $self->{url} = $url;
1159 sub find_by_url { # repos_root and, path are optional
1160 my ($class, $full_url, $repos_root, $path) = @_;
1162 return undef unless defined $full_url;
1163 remove_username($full_url);
1164 remove_username($repos_root) if defined $repos_root;
1165 my $remotes = read_all_remotes();
1166 if (defined $full_url && defined $repos_root && !defined $path) {
1167 $path = $full_url;
1168 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1170 foreach my $repo_id (keys %$remotes) {
1171 my $u = $remotes->{$repo_id}->{url} or next;
1172 remove_username($u);
1173 next if defined $repos_root && $repos_root ne $u;
1175 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1176 foreach (qw/branches tags/) {
1177 resolve_local_globs($u, $fetch,
1178 $remotes->{$repo_id}->{$_});
1180 my $p = $path;
1181 unless (defined $p) {
1182 $p = $full_url;
1183 $p =~ s#^\Q$u\E(?:/|$)## or next;
1185 foreach my $f (keys %$fetch) {
1186 next if $f ne $p;
1187 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1190 undef;
1193 sub init {
1194 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1195 my $self = _new($class, $repo_id, $ref_id, $path);
1196 if (defined $url) {
1197 $self->init_remote_config($url, $no_write);
1199 $self;
1202 sub find_ref {
1203 my ($ref_id) = @_;
1204 foreach (command(qw/config -l/)) {
1205 next unless m!^svn-remote\.(.+)\.fetch=
1206 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1207 my ($repo_id, $path, $ref) = ($1, $2, $3);
1208 if ($ref eq $ref_id) {
1209 $path = '' if ($path =~ m#^\./?#);
1210 return ($repo_id, $path);
1213 (undef, undef, undef);
1216 sub new {
1217 my ($class, $ref_id, $repo_id, $path) = @_;
1218 if (defined $ref_id && !defined $repo_id && !defined $path) {
1219 ($repo_id, $path) = find_ref($ref_id);
1220 if (!defined $repo_id) {
1221 die "Could not find a \"svn-remote.*.fetch\" key ",
1222 "in the repository configuration matching: ",
1223 "refs/remotes/$ref_id\n";
1226 my $self = _new($class, $repo_id, $ref_id, $path);
1227 if (!defined $self->{path} || !length $self->{path}) {
1228 my $fetch = command_oneline('config', '--get',
1229 "svn-remote.$repo_id.fetch",
1230 ":refs/remotes/$ref_id\$") or
1231 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1232 "\":refs/remotes/$ref_id\$\" in config\n";
1233 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1235 $self->{url} = command_oneline('config', '--get',
1236 "svn-remote.$repo_id.url") or
1237 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1238 $self->rebuild;
1239 $self;
1242 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1244 sub svm_uuid {
1245 my ($self) = @_;
1246 return $self->{svm}->{uuid} if $self->svm;
1247 $self->ra;
1248 unless ($self->{svm}) {
1249 die "SVM UUID not cached, and reading remotely failed\n";
1251 $self->{svm}->{uuid};
1254 sub svm {
1255 my ($self) = @_;
1256 return $self->{svm} if $self->{svm};
1257 my $svm;
1258 # see if we have it in our config, first:
1259 eval {
1260 my $section = "svn-remote.$self->{repo_id}";
1261 $svm = {
1262 source => tmp_config('--get', "$section.svm-source"),
1263 uuid => tmp_config('--get', "$section.svm-uuid"),
1264 replace => tmp_config('--get', "$section.svm-replace"),
1267 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1268 $self->{svm} = $svm;
1270 $self->{svm};
1273 sub _set_svm_vars {
1274 my ($self, $ra) = @_;
1275 return $ra if $self->svm;
1277 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1278 "(svm:source, svm:uuid) ",
1279 "from the following URLs:\n" );
1280 sub read_svm_props {
1281 my ($self, $ra, $path, $r) = @_;
1282 my $props = ($ra->get_dir($path, $r))[2];
1283 my $src = $props->{'svm:source'};
1284 my $uuid = $props->{'svm:uuid'};
1285 return undef if (!$src || !$uuid);
1287 chomp($src, $uuid);
1289 $uuid =~ m{^[0-9a-f\-]{30,}$}
1290 or die "doesn't look right - svm:uuid is '$uuid'\n";
1292 # the '!' is used to mark the repos_root!/relative/path
1293 $src =~ s{/?!/?}{/};
1294 $src =~ s{/+$}{}; # no trailing slashes please
1295 # username is of no interest
1296 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1298 my $replace = $ra->{url};
1299 $replace .= "/$path" if length $path;
1301 my $section = "svn-remote.$self->{repo_id}";
1302 tmp_config("$section.svm-source", $src);
1303 tmp_config("$section.svm-replace", $replace);
1304 tmp_config("$section.svm-uuid", $uuid);
1305 $self->{svm} = {
1306 source => $src,
1307 uuid => $uuid,
1308 replace => $replace
1312 my $r = $ra->get_latest_revnum;
1313 my $path = $self->{path};
1314 my %tried;
1315 while (length $path) {
1316 unless ($tried{"$self->{url}/$path"}) {
1317 return $ra if $self->read_svm_props($ra, $path, $r);
1318 $tried{"$self->{url}/$path"} = 1;
1320 $path =~ s#/?[^/]+$##;
1322 die "Path: '$path' should be ''\n" if $path ne '';
1323 return $ra if $self->read_svm_props($ra, $path, $r);
1324 $tried{"$self->{url}/$path"} = 1;
1326 if ($ra->{repos_root} eq $self->{url}) {
1327 die @err, (map { " $_\n" } keys %tried), "\n";
1330 # nope, make sure we're connected to the repository root:
1331 my $ok;
1332 my @tried_b;
1333 $path = $ra->{svn_path};
1334 $ra = Git::SVN::Ra->new($ra->{repos_root});
1335 while (length $path) {
1336 unless ($tried{"$ra->{url}/$path"}) {
1337 $ok = $self->read_svm_props($ra, $path, $r);
1338 last if $ok;
1339 $tried{"$ra->{url}/$path"} = 1;
1341 $path =~ s#/?[^/]+$##;
1343 die "Path: '$path' should be ''\n" if $path ne '';
1344 $ok ||= $self->read_svm_props($ra, $path, $r);
1345 $tried{"$ra->{url}/$path"} = 1;
1346 if (!$ok) {
1347 die @err, (map { " $_\n" } keys %tried), "\n";
1349 Git::SVN::Ra->new($self->{url});
1352 sub svnsync {
1353 my ($self) = @_;
1354 return $self->{svnsync} if $self->{svnsync};
1356 if ($self->no_metadata) {
1357 die "Can't have both 'noMetadata' and ",
1358 "'useSvnsyncProps' options set!\n";
1360 if ($self->rewrite_root) {
1361 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1362 "options set!\n";
1365 my $svnsync;
1366 # see if we have it in our config, first:
1367 eval {
1368 my $section = "svn-remote.$self->{repo_id}";
1369 $svnsync = {
1370 url => tmp_config('--get', "$section.svnsync-url"),
1371 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1374 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1375 return $self->{svnsync} = $svnsync;
1378 my $err = "useSvnsyncProps set, but failed to read " .
1379 "svnsync property: svn:sync-from-";
1380 my $rp = $self->ra->rev_proplist(0);
1382 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1383 $url =~ m{^[a-z\+]+://} or
1384 die "doesn't look right - svn:sync-from-url is '$url'\n";
1386 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1387 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1388 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1390 my $section = "svn-remote.$self->{repo_id}";
1391 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1392 tmp_config('--add', "$section.svnsync-url", $url);
1393 return $self->{svnsync} = { url => $url, uuid => $uuid };
1396 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1397 # remote lookup (useful for 'git svn log').
1398 sub ra_uuid {
1399 my ($self) = @_;
1400 unless ($self->{ra_uuid}) {
1401 my $key = "svn-remote.$self->{repo_id}.uuid";
1402 my $uuid = eval { tmp_config('--get', $key) };
1403 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1404 $self->{ra_uuid} = $uuid;
1405 } else {
1406 die "ra_uuid called without URL\n" unless $self->{url};
1407 $self->{ra_uuid} = $self->ra->get_uuid;
1408 tmp_config('--add', $key, $self->{ra_uuid});
1411 $self->{ra_uuid};
1414 sub ra {
1415 my ($self) = shift;
1416 my $ra = Git::SVN::Ra->new($self->{url});
1417 if ($self->use_svm_props && !$self->{svm}) {
1418 if ($self->no_metadata) {
1419 die "Can't have both 'noMetadata' and ",
1420 "'useSvmProps' options set!\n";
1421 } elsif ($self->use_svnsync_props) {
1422 die "Can't have both 'useSvnsyncProps' and ",
1423 "'useSvmProps' options set!\n";
1425 $ra = $self->_set_svm_vars($ra);
1426 $self->{-want_revprops} = 1;
1428 $ra;
1431 sub rel_path {
1432 my ($self) = @_;
1433 my $repos_root = $self->ra->{repos_root};
1434 return $self->{path} if ($self->{url} eq $repos_root);
1435 my $url = $self->{url} .
1436 (length $self->{path} ? "/$self->{path}" : $self->{path});
1437 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1438 $url;
1441 sub traverse_ignore {
1442 my ($self, $fh, $path, $r) = @_;
1443 $path =~ s#^/+##g;
1444 my $ra = $self->ra;
1445 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1446 my $p = $path;
1447 $p =~ s#^\Q$self->{path}\E(/|$)##;
1448 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1449 if (my $s = $props->{'svn:ignore'}) {
1450 $s =~ s/[\r\n]+/\n/g;
1451 chomp $s;
1452 if (length $p == 0) {
1453 $s =~ s#\n#\n/$p#g;
1454 print $fh "/$s\n";
1455 } else {
1456 $s =~ s#\n#\n/$p/#g;
1457 print $fh "/$p/$s\n";
1460 foreach (sort keys %$dirent) {
1461 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1462 $self->traverse_ignore($fh, "$path/$_", $r);
1466 sub last_rev { ($_[0]->last_rev_commit)[0] }
1467 sub last_commit { ($_[0]->last_rev_commit)[1] }
1469 # returns the newest SVN revision number and newest commit SHA1
1470 sub last_rev_commit {
1471 my ($self) = @_;
1472 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1473 return ($self->{last_rev}, $self->{last_commit});
1475 my $c = ::verify_ref($self->refname.'^0');
1476 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1477 my $rev = (::cmt_metadata($c))[1];
1478 if (defined $rev) {
1479 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1480 return ($rev, $c);
1483 my $db_path = $self->db_path;
1484 unless (-e $db_path) {
1485 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1486 return (undef, undef);
1488 my $offset = -41; # from tail
1489 my $rl;
1490 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1491 sysseek($fh, $offset, 2); # don't care for errors
1492 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1493 chomp $rl;
1494 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1495 $offset -= 41;
1496 sysseek($fh, $offset, 2); # don't care for errors
1497 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1498 chomp $rl;
1500 if ($c && $c ne $rl) {
1501 die "$db_path and ", $self->refname,
1502 " inconsistent!:\n$c != $rl\n";
1504 my $rev = sysseek($fh, 0, 1) or croak $!;
1505 $rev = ($rev - 41) / 41;
1506 close $fh or croak $!;
1507 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1508 return ($rev, $c);
1511 sub get_fetch_range {
1512 my ($self, $min, $max) = @_;
1513 $max ||= $self->ra->get_latest_revnum;
1514 $min ||= $self->rev_db_max;
1515 (++$min, $max);
1518 sub tmp_config {
1519 my (@args) = @_;
1520 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1521 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1522 if (! -f $config && -f $old_def_config) {
1523 rename $old_def_config, $config or
1524 die "Failed rename $old_def_config => $config: $!\n";
1526 my $old_config = $ENV{GIT_CONFIG};
1527 $ENV{GIT_CONFIG} = $config;
1528 $@ = undef;
1529 my @ret = eval {
1530 unless (-f $config) {
1531 mkfile($config);
1532 open my $fh, '>', $config or
1533 die "Can't open $config: $!\n";
1534 print $fh "; This file is used internally by ",
1535 "git-svn\n" or die
1536 "Couldn't write to $config: $!\n";
1537 print $fh "; You should not have to edit it\n" or
1538 die "Couldn't write to $config: $!\n";
1539 close $fh or die "Couldn't close $config: $!\n";
1541 command('config', @args);
1543 my $err = $@;
1544 if (defined $old_config) {
1545 $ENV{GIT_CONFIG} = $old_config;
1546 } else {
1547 delete $ENV{GIT_CONFIG};
1549 die $err if $err;
1550 wantarray ? @ret : $ret[0];
1553 sub tmp_index_do {
1554 my ($self, $sub) = @_;
1555 my $old_index = $ENV{GIT_INDEX_FILE};
1556 $ENV{GIT_INDEX_FILE} = $self->{index};
1557 $@ = undef;
1558 my @ret = eval {
1559 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1560 mkpath([$dir]) unless -d $dir;
1561 &$sub;
1563 my $err = $@;
1564 if (defined $old_index) {
1565 $ENV{GIT_INDEX_FILE} = $old_index;
1566 } else {
1567 delete $ENV{GIT_INDEX_FILE};
1569 die $err if $err;
1570 wantarray ? @ret : $ret[0];
1573 sub assert_index_clean {
1574 my ($self, $treeish) = @_;
1576 $self->tmp_index_do(sub {
1577 command_noisy('read-tree', $treeish) unless -e $self->{index};
1578 my $x = command_oneline('write-tree');
1579 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1580 /^tree ($::sha1)/mo);
1581 return if $y eq $x;
1583 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1584 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1585 command_noisy('read-tree', $treeish);
1586 $x = command_oneline('write-tree');
1587 if ($y ne $x) {
1588 ::fatal "trees ($treeish) $y != $x\n",
1589 "Something is seriously wrong...\n";
1594 sub get_commit_parents {
1595 my ($self, $log_entry) = @_;
1596 my (%seen, @ret, @tmp);
1597 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1598 if (my $ip = $self->{inject_parents}) {
1599 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1600 push @tmp, $commit;
1603 if (my $cur = ::verify_ref($self->refname.'^0')) {
1604 push @tmp, $cur;
1606 if (my $ipd = $self->{inject_parents_dcommit}) {
1607 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1608 push @tmp, @$commit;
1611 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1612 while (my $p = shift @tmp) {
1613 next if $seen{$p};
1614 $seen{$p} = 1;
1615 push @ret, $p;
1616 # MAXPARENT is defined to 16 in commit-tree.c:
1617 last if @ret >= 16;
1619 if (@tmp) {
1620 die "r$log_entry->{revision}: No room for parents:\n\t",
1621 join("\n\t", @tmp), "\n";
1623 @ret;
1626 sub rewrite_root {
1627 my ($self) = @_;
1628 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1629 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1630 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1631 if ($rwr) {
1632 $rwr =~ s#/+$##;
1633 if ($rwr !~ m#^[a-z\+]+://#) {
1634 die "$rwr is not a valid URL (key: $k)\n";
1637 $self->{-rewrite_root} = $rwr;
1640 sub metadata_url {
1641 my ($self) = @_;
1642 ($self->rewrite_root || $self->{url}) .
1643 (length $self->{path} ? '/' . $self->{path} : '');
1646 sub full_url {
1647 my ($self) = @_;
1648 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1651 sub do_git_commit {
1652 my ($self, $log_entry) = @_;
1653 my $lr = $self->last_rev;
1654 if (defined $lr && $lr >= $log_entry->{revision}) {
1655 die "Last fetched revision of ", $self->refname,
1656 " was r$lr, but we are about to fetch: ",
1657 "r$log_entry->{revision}!\n";
1659 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1660 croak "$log_entry->{revision} = $c already exists! ",
1661 "Why are we refetching it?\n";
1663 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1664 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1665 $log_entry->{email};
1666 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1668 my $tree = $log_entry->{tree};
1669 if (!defined $tree) {
1670 $tree = $self->tmp_index_do(sub {
1671 command_oneline('write-tree') });
1673 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1675 my @exec = ('git-commit-tree', $tree);
1676 foreach ($self->get_commit_parents($log_entry)) {
1677 push @exec, '-p', $_;
1679 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1680 or croak $!;
1681 print $msg_fh $log_entry->{log} or croak $!;
1682 unless ($self->no_metadata) {
1683 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1684 or croak $!;
1686 $msg_fh->flush == 0 or croak $!;
1687 close $msg_fh or croak $!;
1688 chomp(my $commit = do { local $/; <$out_fh> });
1689 close $out_fh or croak $!;
1690 waitpid $pid, 0;
1691 croak $? if $?;
1692 if ($commit !~ /^$::sha1$/o) {
1693 die "Failed to commit, invalid sha1: $commit\n";
1696 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1698 $self->{last_rev} = $log_entry->{revision};
1699 $self->{last_commit} = $commit;
1700 print "r$log_entry->{revision}";
1701 if (defined $log_entry->{svm_revision}) {
1702 print " (\@$log_entry->{svm_revision})";
1703 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1704 0, $self->svm_uuid);
1706 print " = $commit ($self->{ref_id})\n";
1707 if (defined $_repack && (--$_repack_nr == 0)) {
1708 $_repack_nr = $_repack;
1709 # repack doesn't use any arguments with spaces in them, does it?
1710 print "Running git repack $_repack_flags ...\n";
1711 command_noisy('repack', split(/\s+/, $_repack_flags));
1712 print "Done repacking\n";
1714 return $commit;
1717 sub match_paths {
1718 my ($self, $paths, $r) = @_;
1719 return 1 if $self->{path} eq '';
1720 if (my $path = $paths->{"/$self->{path}"}) {
1721 return ($path->{action} eq 'D') ? 0 : 1;
1723 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1724 if (grep /$self->{path_regex}/, keys %$paths) {
1725 return 1;
1727 my $c = '';
1728 foreach (split m#/#, $self->{path}) {
1729 $c .= "/$_";
1730 next unless ($paths->{$c} &&
1731 ($paths->{$c}->{action} =~ /^[AR]$/));
1732 if ($self->ra->check_path($self->{path}, $r) ==
1733 $SVN::Node::dir) {
1734 return 1;
1737 return 0;
1740 sub find_parent_branch {
1741 my ($self, $paths, $rev) = @_;
1742 return undef unless $self->follow_parent;
1743 unless (defined $paths) {
1744 my $err_handler = $SVN::Error::handler;
1745 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1746 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1747 $paths =
1748 Git::SVN::Ra::dup_changed_paths($_[0]) });
1749 $SVN::Error::handler = $err_handler;
1751 return undef unless defined $paths;
1753 # look for a parent from another branch:
1754 my @b_path_components = split m#/#, $self->rel_path;
1755 my @a_path_components;
1756 my $i;
1757 while (@b_path_components) {
1758 $i = $paths->{'/'.join('/', @b_path_components)};
1759 last if $i && defined $i->{copyfrom_path};
1760 unshift(@a_path_components, pop(@b_path_components));
1762 return undef unless defined $i && defined $i->{copyfrom_path};
1763 my $branch_from = $i->{copyfrom_path};
1764 if (@a_path_components) {
1765 print STDERR "branch_from: $branch_from => ";
1766 $branch_from .= '/'.join('/', @a_path_components);
1767 print STDERR $branch_from, "\n";
1769 my $r = $i->{copyfrom_rev};
1770 my $repos_root = $self->ra->{repos_root};
1771 my $url = $self->ra->{url};
1772 my $new_url = $repos_root . $branch_from;
1773 print STDERR "Found possible branch point: ",
1774 "$new_url => ", $self->full_url, ", $r\n";
1775 $branch_from =~ s#^/##;
1776 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1777 unless ($gs) {
1778 my $ref_id = $self->{ref_id};
1779 $ref_id =~ s/\@\d+$//;
1780 $ref_id .= "\@$r";
1781 # just grow a tail if we're not unique enough :x
1782 $ref_id .= '-' while find_ref($ref_id);
1783 print STDERR "Initializing parent: $ref_id\n";
1784 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1786 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1787 if (!defined $r0 || !defined $parent) {
1788 my ($base, $head) = parse_revision_argument(0, $r);
1789 if ($base <= $r) {
1790 $gs->fetch($base, $r);
1792 ($r0, $parent) = $gs->last_rev_commit;
1794 if (defined $r0 && defined $parent) {
1795 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1796 my $ed;
1797 if ($self->ra->can_do_switch) {
1798 $self->assert_index_clean($parent);
1799 print STDERR "Following parent with do_switch\n";
1800 # do_switch works with svn/trunk >= r22312, but that
1801 # is not included with SVN 1.4.3 (the latest version
1802 # at the moment), so we can't rely on it
1803 $self->{last_commit} = $parent;
1804 $ed = SVN::Git::Fetcher->new($self);
1805 $gs->ra->gs_do_switch($r0, $rev, $gs,
1806 $self->full_url, $ed)
1807 or die "SVN connection failed somewhere...\n";
1808 } else {
1809 print STDERR "Following parent with do_update\n";
1810 $ed = SVN::Git::Fetcher->new($self);
1811 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1812 or die "SVN connection failed somewhere...\n";
1814 print STDERR "Successfully followed parent\n";
1815 return $self->make_log_entry($rev, [$parent], $ed);
1817 return undef;
1820 sub do_fetch {
1821 my ($self, $paths, $rev) = @_;
1822 my $ed;
1823 my ($last_rev, @parents);
1824 if (my $lc = $self->last_commit) {
1825 # we can have a branch that was deleted, then re-added
1826 # under the same name but copied from another path, in
1827 # which case we'll have multiple parents (we don't
1828 # want to break the original ref, nor lose copypath info):
1829 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1830 push @{$log_entry->{parents}}, $lc;
1831 return $log_entry;
1833 $ed = SVN::Git::Fetcher->new($self);
1834 $last_rev = $self->{last_rev};
1835 $ed->{c} = $lc;
1836 @parents = ($lc);
1837 } else {
1838 $last_rev = $rev;
1839 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1840 return $log_entry;
1842 $ed = SVN::Git::Fetcher->new($self);
1844 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1845 die "SVN connection failed somewhere...\n";
1847 $self->make_log_entry($rev, \@parents, $ed);
1850 sub get_untracked {
1851 my ($self, $ed) = @_;
1852 my @out;
1853 my $h = $ed->{empty};
1854 foreach (sort keys %$h) {
1855 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1856 push @out, " $act: " . uri_encode($_);
1857 warn "W: $act: $_\n";
1859 foreach my $t (qw/dir_prop file_prop/) {
1860 $h = $ed->{$t} or next;
1861 foreach my $path (sort keys %$h) {
1862 my $ppath = $path eq '' ? '.' : $path;
1863 foreach my $prop (sort keys %{$h->{$path}}) {
1864 next if $SKIP_PROP{$prop};
1865 my $v = $h->{$path}->{$prop};
1866 my $t_ppath_prop = "$t: " .
1867 uri_encode($ppath) . ' ' .
1868 uri_encode($prop);
1869 if (defined $v) {
1870 push @out, " +$t_ppath_prop " .
1871 uri_encode($v);
1872 } else {
1873 push @out, " -$t_ppath_prop";
1878 foreach my $t (qw/absent_file absent_directory/) {
1879 $h = $ed->{$t} or next;
1880 foreach my $parent (sort keys %$h) {
1881 foreach my $path (sort @{$h->{$parent}}) {
1882 push @out, " $t: " .
1883 uri_encode("$parent/$path");
1884 warn "W: $t: $parent/$path ",
1885 "Insufficient permissions?\n";
1889 \@out;
1892 sub parse_svn_date {
1893 my $date = shift || return '+0000 1970-01-01 00:00:00';
1894 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1895 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1896 croak "Unable to parse date: $date\n";
1897 "+0000 $Y-$m-$d $H:$M:$S";
1900 sub check_author {
1901 my ($author) = @_;
1902 if (!defined $author || length $author == 0) {
1903 $author = '(no author)';
1905 if (defined $::_authors && ! defined $::users{$author}) {
1906 die "Author: $author not defined in $::_authors file\n";
1908 $author;
1911 sub make_log_entry {
1912 my ($self, $rev, $parents, $ed) = @_;
1913 my $untracked = $self->get_untracked($ed);
1915 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1916 print $un "r$rev\n" or croak $!;
1917 print $un $_, "\n" foreach @$untracked;
1918 my %log_entry = ( parents => $parents || [], revision => $rev,
1919 log => '');
1921 my $headrev;
1922 my $logged = delete $self->{logged_rev_props};
1923 if (!$logged || $self->{-want_revprops}) {
1924 my $rp = $self->ra->rev_proplist($rev);
1925 foreach (sort keys %$rp) {
1926 my $v = $rp->{$_};
1927 if (/^svn:(author|date|log)$/) {
1928 $log_entry{$1} = $v;
1929 } elsif ($_ eq 'svm:headrev') {
1930 $headrev = $v;
1931 } else {
1932 print $un " rev_prop: ", uri_encode($_), ' ',
1933 uri_encode($v), "\n";
1936 } else {
1937 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1939 close $un or croak $!;
1941 $log_entry{date} = parse_svn_date($log_entry{date});
1942 $log_entry{log} .= "\n";
1943 my $author = $log_entry{author} = check_author($log_entry{author});
1944 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1945 : ($author, undef);
1946 if (defined $headrev && $self->use_svm_props) {
1947 if ($self->rewrite_root) {
1948 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1949 "options set!\n";
1951 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1952 # we don't want "SVM: initializing mirror for junk" ...
1953 return undef if $r == 0;
1954 my $svm = $self->svm;
1955 if ($uuid ne $svm->{uuid}) {
1956 die "UUID mismatch on SVM path:\n",
1957 "expected: $svm->{uuid}\n",
1958 " got: $uuid\n";
1960 my $full_url = $self->full_url;
1961 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1962 die "Failed to replace '$svm->{replace}' with ",
1963 "'$svm->{source}' in $full_url\n";
1964 # throw away username for storing in records
1965 remove_username($full_url);
1966 $log_entry{metadata} = "$full_url\@$r $uuid";
1967 $log_entry{svm_revision} = $r;
1968 $email ||= "$author\@$uuid"
1969 } elsif ($self->use_svnsync_props) {
1970 my $full_url = $self->svnsync->{url};
1971 $full_url .= "/$self->{path}" if length $self->{path};
1972 remove_username($full_url);
1973 my $uuid = $self->svnsync->{uuid};
1974 $log_entry{metadata} = "$full_url\@$rev $uuid";
1975 $email ||= "$author\@$uuid"
1976 } else {
1977 my $url = $self->metadata_url;
1978 remove_username($url);
1979 $log_entry{metadata} = "$url\@$rev " .
1980 $self->ra->get_uuid;
1981 $email ||= "$author\@" . $self->ra->get_uuid;
1983 $log_entry{name} = $name;
1984 $log_entry{email} = $email;
1985 \%log_entry;
1988 sub fetch {
1989 my ($self, $min_rev, $max_rev, @parents) = @_;
1990 my ($last_rev, $last_commit) = $self->last_rev_commit;
1991 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1992 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1995 sub set_tree_cb {
1996 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1997 $self->{inject_parents} = { $rev => $tree };
1998 $self->fetch(undef, undef);
2001 sub set_tree {
2002 my ($self, $tree) = (shift, shift);
2003 my $log_entry = ::get_commit_entry($tree);
2004 unless ($self->{last_rev}) {
2005 fatal("Must have an existing revision to commit\n");
2007 my %ed_opts = ( r => $self->{last_rev},
2008 log => $log_entry->{log},
2009 ra => $self->ra,
2010 tree_a => $self->{last_commit},
2011 tree_b => $tree,
2012 editor_cb => sub {
2013 $self->set_tree_cb($log_entry, $tree, @_) },
2014 svn_path => $self->{path} );
2015 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2016 print "No changes\nr$self->{last_rev} = $tree\n";
2020 sub rebuild {
2021 my ($self) = @_;
2022 my $db_path = $self->db_path;
2023 return if (-e $db_path && ! -z $db_path);
2024 return unless ::verify_ref($self->refname.'^0');
2025 if (-f $self->{db_root}) {
2026 rename $self->{db_root}, $db_path or die
2027 "rename $self->{db_root} => $db_path failed: $!\n";
2028 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2029 symlink $base, $self->{db_root} or die
2030 "symlink $base => $self->{db_root} failed: $!\n";
2031 return;
2033 print "Rebuilding $db_path ...\n";
2034 my ($log, $ctx) = command_output_pipe("log", $self->refname);
2035 my $latest;
2036 my $full_url = $self->full_url;
2037 remove_username($full_url);
2038 my $svn_uuid;
2039 my $c;
2040 while (<$log>) {
2041 if ( m{^commit ($::sha1)$} ) {
2042 $c = $1;
2043 next;
2045 next unless s{^\s*(git-svn-id:)}{$1};
2046 my ($url, $rev, $uuid) = ::extract_metadata($_);
2047 remove_username($url);
2049 # ignore merges (from set-tree)
2050 next if (!defined $rev || !$uuid);
2052 # if we merged or otherwise started elsewhere, this is
2053 # how we break out of it
2054 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2055 ($full_url && $url && ($url ne $full_url))) {
2056 next;
2058 $latest ||= $rev;
2059 $svn_uuid ||= $uuid;
2061 $self->rev_db_set($rev, $c);
2062 print "r$rev = $c\n";
2064 command_close_pipe($log, $ctx);
2065 print "Done rebuilding $db_path\n";
2068 # rev_db:
2069 # Tie::File seems to be prone to offset errors if revisions get sparse,
2070 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2071 # one of my favorite modules is out :< Next up would be one of the DBM
2072 # modules, but I'm not sure which is most portable... So I'll just
2073 # go with something that's plain-text, but still capable of
2074 # being randomly accessed. So here's my ultra-simple fixed-width
2075 # database. All records are 40 characters + "\n", so it's easy to seek
2076 # to a revision: (41 * rev) is the byte offset.
2077 # A record of 40 0s denotes an empty revision.
2078 # And yes, it's still pretty fast (faster than Tie::File).
2079 # These files are disposable unless noMetadata or useSvmProps is set
2081 sub _rev_db_set {
2082 my ($fh, $rev, $commit) = @_;
2083 my $offset = $rev * 41;
2084 # assume that append is the common case:
2085 seek $fh, 0, 2 or croak $!;
2086 my $pos = tell $fh;
2087 if ($pos < $offset) {
2088 for (1 .. (($offset - $pos) / 41)) {
2089 print $fh (('0' x 40),"\n") or croak $!;
2092 seek $fh, $offset, 0 or croak $!;
2093 print $fh $commit,"\n" or croak $!;
2096 sub mkfile {
2097 my ($path) = @_;
2098 unless (-e $path) {
2099 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2100 mkpath([$dir]) unless -d $dir;
2101 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2102 close $fh or die "Couldn't close (create) $path: $!\n";
2106 sub rev_db_set {
2107 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2108 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2109 my $db = $self->db_path($uuid);
2110 my $db_lock = "$db.lock";
2111 my $sig;
2112 if ($update_ref) {
2113 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2114 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2116 mkfile($db);
2118 $LOCKFILES{$db_lock} = 1;
2119 my $sync;
2120 # both of these options make our .rev_db file very, very important
2121 # and we can't afford to lose it because rebuild() won't work
2122 if ($self->use_svm_props || $self->no_metadata) {
2123 $sync = 1;
2124 copy($db, $db_lock) or die "rev_db_set(@_): ",
2125 "Failed to copy: ",
2126 "$db => $db_lock ($!)\n";
2127 } else {
2128 rename $db, $db_lock or die "rev_db_set(@_): ",
2129 "Failed to rename: ",
2130 "$db => $db_lock ($!)\n";
2132 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2133 _rev_db_set($fh, $rev, $commit);
2134 if ($sync) {
2135 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2136 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2138 close $fh or croak $!;
2139 if ($update_ref) {
2140 $_head = $self;
2141 command_noisy('update-ref', '-m', "r$rev",
2142 $self->refname, $commit);
2144 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2145 "$db_lock => $db ($!)\n";
2146 delete $LOCKFILES{$db_lock};
2147 if ($update_ref) {
2148 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2149 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2150 kill $sig, $$ if defined $sig;
2154 sub rev_db_max {
2155 my ($self) = @_;
2156 $self->rebuild;
2157 my $db_path = $self->db_path;
2158 my @stat = stat $db_path or return 0;
2159 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2160 my $max = $stat[7] / 41;
2161 (($max > 0) ? $max - 1 : 0);
2164 sub rev_db_get {
2165 my ($self, $rev, $uuid) = @_;
2166 my $ret;
2167 my $offset = $rev * 41;
2168 my $db_path = $self->db_path($uuid);
2169 return undef unless -e $db_path;
2170 open my $fh, '<', $db_path or croak $!;
2171 if (sysseek($fh, $offset, 0) == $offset) {
2172 my $read = sysread($fh, $ret, 40);
2173 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2175 close $fh or croak $!;
2176 $ret;
2179 sub find_rev_before {
2180 my ($self, $rev, $eq_ok) = @_;
2181 --$rev unless $eq_ok;
2182 while ($rev > 0) {
2183 if (my $c = $self->rev_db_get($rev)) {
2184 return ($rev, $c);
2186 --$rev;
2188 return (undef, undef);
2191 sub _new {
2192 my ($class, $repo_id, $ref_id, $path) = @_;
2193 unless (defined $repo_id && length $repo_id) {
2194 $repo_id = $Git::SVN::default_repo_id;
2196 unless (defined $ref_id && length $ref_id) {
2197 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2199 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2200 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2201 $_[3] = $path = '' unless (defined $path);
2202 mkpath(["$ENV{GIT_DIR}/svn"]);
2203 bless {
2204 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2205 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2206 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2209 sub db_path {
2210 my ($self, $uuid) = @_;
2211 $uuid ||= $self->ra_uuid;
2212 "$self->{db_root}.$uuid";
2215 sub uri_encode {
2216 my ($f) = @_;
2217 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2221 sub remove_username {
2222 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2225 package Git::SVN::Prompt;
2226 use strict;
2227 use warnings;
2228 require SVN::Core;
2229 use vars qw/$_no_auth_cache $_username/;
2231 sub simple {
2232 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2233 $may_save = undef if $_no_auth_cache;
2234 $default_username = $_username if defined $_username;
2235 if (defined $default_username && length $default_username) {
2236 if (defined $realm && length $realm) {
2237 print STDERR "Authentication realm: $realm\n";
2238 STDERR->flush;
2240 $cred->username($default_username);
2241 } else {
2242 username($cred, $realm, $may_save, $pool);
2244 $cred->password(_read_password("Password for '" .
2245 $cred->username . "': ", $realm));
2246 $cred->may_save($may_save);
2247 $SVN::_Core::SVN_NO_ERROR;
2250 sub ssl_server_trust {
2251 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2252 $may_save = undef if $_no_auth_cache;
2253 print STDERR "Error validating server certificate for '$realm':\n";
2254 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2255 print STDERR " - The certificate is not issued by a trusted ",
2256 "authority. Use the\n",
2257 " fingerprint to validate the certificate manually!\n";
2259 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2260 print STDERR " - The certificate hostname does not match.\n";
2262 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2263 print STDERR " - The certificate is not yet valid.\n";
2265 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2266 print STDERR " - The certificate has expired.\n";
2268 if ($failures & $SVN::Auth::SSL::OTHER) {
2269 print STDERR " - The certificate has an unknown error.\n";
2271 printf STDERR
2272 "Certificate information:\n".
2273 " - Hostname: %s\n".
2274 " - Valid: from %s until %s\n".
2275 " - Issuer: %s\n".
2276 " - Fingerprint: %s\n",
2277 map $cert_info->$_, qw(hostname valid_from valid_until
2278 issuer_dname fingerprint);
2279 my $choice;
2280 prompt:
2281 print STDERR $may_save ?
2282 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2283 "(R)eject or accept (t)emporarily? ";
2284 STDERR->flush;
2285 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2286 if ($choice =~ /^t$/i) {
2287 $cred->may_save(undef);
2288 } elsif ($choice =~ /^r$/i) {
2289 return -1;
2290 } elsif ($may_save && $choice =~ /^p$/i) {
2291 $cred->may_save($may_save);
2292 } else {
2293 goto prompt;
2295 $cred->accepted_failures($failures);
2296 $SVN::_Core::SVN_NO_ERROR;
2299 sub ssl_client_cert {
2300 my ($cred, $realm, $may_save, $pool) = @_;
2301 $may_save = undef if $_no_auth_cache;
2302 print STDERR "Client certificate filename: ";
2303 STDERR->flush;
2304 chomp(my $filename = <STDIN>);
2305 $cred->cert_file($filename);
2306 $cred->may_save($may_save);
2307 $SVN::_Core::SVN_NO_ERROR;
2310 sub ssl_client_cert_pw {
2311 my ($cred, $realm, $may_save, $pool) = @_;
2312 $may_save = undef if $_no_auth_cache;
2313 $cred->password(_read_password("Password: ", $realm));
2314 $cred->may_save($may_save);
2315 $SVN::_Core::SVN_NO_ERROR;
2318 sub username {
2319 my ($cred, $realm, $may_save, $pool) = @_;
2320 $may_save = undef if $_no_auth_cache;
2321 if (defined $realm && length $realm) {
2322 print STDERR "Authentication realm: $realm\n";
2324 my $username;
2325 if (defined $_username) {
2326 $username = $_username;
2327 } else {
2328 print STDERR "Username: ";
2329 STDERR->flush;
2330 chomp($username = <STDIN>);
2332 $cred->username($username);
2333 $cred->may_save($may_save);
2334 $SVN::_Core::SVN_NO_ERROR;
2337 sub _read_password {
2338 my ($prompt, $realm) = @_;
2339 print STDERR $prompt;
2340 STDERR->flush;
2341 require Term::ReadKey;
2342 Term::ReadKey::ReadMode('noecho');
2343 my $password = '';
2344 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2345 last if $key =~ /[\012\015]/; # \n\r
2346 $password .= $key;
2348 Term::ReadKey::ReadMode('restore');
2349 print STDERR "\n";
2350 STDERR->flush;
2351 $password;
2354 package main;
2357 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2358 $SVN::Node::dir.$SVN::Node::unknown.
2359 $SVN::Node::none.$SVN::Node::file.
2360 $SVN::Node::dir.$SVN::Node::unknown.
2361 $SVN::Auth::SSL::CNMISMATCH.
2362 $SVN::Auth::SSL::NOTYETVALID.
2363 $SVN::Auth::SSL::EXPIRED.
2364 $SVN::Auth::SSL::UNKNOWNCA.
2365 $SVN::Auth::SSL::OTHER;
2368 package SVN::Git::Fetcher;
2369 use vars qw/@ISA/;
2370 use strict;
2371 use warnings;
2372 use Carp qw/croak/;
2373 use IO::File qw//;
2374 use Digest::MD5;
2376 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2377 sub new {
2378 my ($class, $git_svn) = @_;
2379 my $self = SVN::Delta::Editor->new;
2380 bless $self, $class;
2381 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2382 $self->{empty} = {};
2383 $self->{dir_prop} = {};
2384 $self->{file_prop} = {};
2385 $self->{absent_dir} = {};
2386 $self->{absent_file} = {};
2387 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2388 $self;
2391 sub set_path_strip {
2392 my ($self, $path) = @_;
2393 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2396 sub open_root {
2397 { path => '' };
2400 sub open_directory {
2401 my ($self, $path, $pb, $rev) = @_;
2402 { path => $path };
2405 sub git_path {
2406 my ($self, $path) = @_;
2407 if ($self->{path_strip}) {
2408 $path =~ s!$self->{path_strip}!! or
2409 die "Failed to strip path '$path' ($self->{path_strip})\n";
2411 $path;
2414 sub delete_entry {
2415 my ($self, $path, $rev, $pb) = @_;
2417 my $gpath = $self->git_path($path);
2418 return undef if ($gpath eq '');
2420 # remove entire directories.
2421 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2422 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2423 -r --name-only -z/,
2424 $self->{c}, '--', $gpath);
2425 local $/ = "\0";
2426 while (<$ls>) {
2427 chomp;
2428 $self->{gii}->remove($_);
2429 print "\tD\t$_\n" unless $::_q;
2431 print "\tD\t$gpath/\n" unless $::_q;
2432 command_close_pipe($ls, $ctx);
2433 $self->{empty}->{$path} = 0
2434 } else {
2435 $self->{gii}->remove($gpath);
2436 print "\tD\t$gpath\n" unless $::_q;
2438 undef;
2441 sub open_file {
2442 my ($self, $path, $pb, $rev) = @_;
2443 my $gpath = $self->git_path($path);
2444 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2445 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2446 unless (defined $mode && defined $blob) {
2447 die "$path was not found in commit $self->{c} (r$rev)\n";
2449 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2450 pool => SVN::Pool->new, action => 'M' };
2453 sub add_file {
2454 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2455 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2456 delete $self->{empty}->{$dir};
2457 { path => $path, mode_a => 100644, mode_b => 100644,
2458 pool => SVN::Pool->new, action => 'A' };
2461 sub add_directory {
2462 my ($self, $path, $cp_path, $cp_rev) = @_;
2463 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2464 delete $self->{empty}->{$dir};
2465 $self->{empty}->{$path} = 1;
2466 { path => $path };
2469 sub change_dir_prop {
2470 my ($self, $db, $prop, $value) = @_;
2471 $self->{dir_prop}->{$db->{path}} ||= {};
2472 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2473 undef;
2476 sub absent_directory {
2477 my ($self, $path, $pb) = @_;
2478 $self->{absent_dir}->{$pb->{path}} ||= [];
2479 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2480 undef;
2483 sub absent_file {
2484 my ($self, $path, $pb) = @_;
2485 $self->{absent_file}->{$pb->{path}} ||= [];
2486 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2487 undef;
2490 sub change_file_prop {
2491 my ($self, $fb, $prop, $value) = @_;
2492 if ($prop eq 'svn:executable') {
2493 if ($fb->{mode_b} != 120000) {
2494 $fb->{mode_b} = defined $value ? 100755 : 100644;
2496 } elsif ($prop eq 'svn:special') {
2497 $fb->{mode_b} = defined $value ? 120000 : 100644;
2498 } else {
2499 $self->{file_prop}->{$fb->{path}} ||= {};
2500 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2502 undef;
2505 sub apply_textdelta {
2506 my ($self, $fb, $exp) = @_;
2507 my $fh = IO::File->new_tmpfile;
2508 $fh->autoflush(1);
2509 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2510 # (but $base does not,) so dup() it for reading in close_file
2511 open my $dup, '<&', $fh or croak $!;
2512 my $base = IO::File->new_tmpfile;
2513 $base->autoflush(1);
2514 if ($fb->{blob}) {
2515 defined (my $pid = fork) or croak $!;
2516 if (!$pid) {
2517 open STDOUT, '>&', $base or croak $!;
2518 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2519 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2521 waitpid $pid, 0;
2522 croak $? if $?;
2524 if (defined $exp) {
2525 seek $base, 0, 0 or croak $!;
2526 my $md5 = Digest::MD5->new;
2527 $md5->addfile($base);
2528 my $got = $md5->hexdigest;
2529 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2530 "expected: $exp\n",
2531 " got: $got\n" if ($got ne $exp);
2534 seek $base, 0, 0 or croak $!;
2535 $fb->{fh} = $dup;
2536 $fb->{base} = $base;
2537 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2540 sub close_file {
2541 my ($self, $fb, $exp) = @_;
2542 my $hash;
2543 my $path = $self->git_path($fb->{path});
2544 if (my $fh = $fb->{fh}) {
2545 if (defined $exp) {
2546 seek($fh, 0, 0) or croak $!;
2547 my $md5 = Digest::MD5->new;
2548 $md5->addfile($fh);
2549 my $got = $md5->hexdigest;
2550 if ($got ne $exp) {
2551 die "Checksum mismatch: $path\n",
2552 "expected: $exp\n got: $got\n";
2555 sysseek($fh, 0, 0) or croak $!;
2556 if ($fb->{mode_b} == 120000) {
2557 sysread($fh, my $buf, 5) == 5 or croak $!;
2558 $buf eq 'link ' or die "$path has mode 120000",
2559 "but is not a link\n";
2561 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2562 if (!$pid) {
2563 open STDIN, '<&', $fh or croak $!;
2564 exec qw/git-hash-object -w --stdin/ or croak $!;
2566 chomp($hash = do { local $/; <$out> });
2567 close $out or croak $!;
2568 close $fh or croak $!;
2569 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2570 close $fb->{base} or croak $!;
2571 } else {
2572 $hash = $fb->{blob} or die "no blob information\n";
2574 $fb->{pool}->clear;
2575 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2576 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2577 undef;
2580 sub abort_edit {
2581 my $self = shift;
2582 $self->{nr} = $self->{gii}->{nr};
2583 delete $self->{gii};
2584 $self->SUPER::abort_edit(@_);
2587 sub close_edit {
2588 my $self = shift;
2589 $self->{git_commit_ok} = 1;
2590 $self->{nr} = $self->{gii}->{nr};
2591 delete $self->{gii};
2592 $self->SUPER::close_edit(@_);
2595 package SVN::Git::Editor;
2596 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2597 use strict;
2598 use warnings;
2599 use Carp qw/croak/;
2600 use IO::File;
2601 use Digest::MD5;
2603 sub new {
2604 my ($class, $opts) = @_;
2605 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2606 die "$_ required!\n" unless (defined $opts->{$_});
2609 my $pool = SVN::Pool->new;
2610 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2611 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2612 $opts->{r}, $mods);
2614 # $opts->{ra} functions should not be used after this:
2615 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2616 $opts->{editor_cb}, $pool);
2617 my $self = SVN::Delta::Editor->new(@ce, $pool);
2618 bless $self, $class;
2619 foreach (qw/svn_path r tree_a tree_b/) {
2620 $self->{$_} = $opts->{$_};
2622 $self->{url} = $opts->{ra}->{url};
2623 $self->{mods} = $mods;
2624 $self->{types} = $types;
2625 $self->{pool} = $pool;
2626 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2627 $self->{rm} = { };
2628 $self->{path_prefix} = length $self->{svn_path} ?
2629 "$self->{svn_path}/" : '';
2630 return $self;
2633 sub generate_diff {
2634 my ($tree_a, $tree_b) = @_;
2635 my @diff_tree = qw(diff-tree -z -r);
2636 if ($_cp_similarity) {
2637 push @diff_tree, "-C$_cp_similarity";
2638 } else {
2639 push @diff_tree, '-C';
2641 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2642 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2643 push @diff_tree, $tree_a, $tree_b;
2644 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2645 local $/ = "\0";
2646 my $state = 'meta';
2647 my @mods;
2648 while (<$diff_fh>) {
2649 chomp $_; # this gets rid of the trailing "\0"
2650 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2651 $::sha1\s($::sha1)\s
2652 ([MTCRAD])\d*$/xo) {
2653 push @mods, { mode_a => $1, mode_b => $2,
2654 sha1_b => $3, chg => $4 };
2655 if ($4 =~ /^(?:C|R)$/) {
2656 $state = 'file_a';
2657 } else {
2658 $state = 'file_b';
2660 } elsif ($state eq 'file_a') {
2661 my $x = $mods[$#mods] or croak "Empty array\n";
2662 if ($x->{chg} !~ /^(?:C|R)$/) {
2663 croak "Error parsing $_, $x->{chg}\n";
2665 $x->{file_a} = $_;
2666 $state = 'file_b';
2667 } elsif ($state eq 'file_b') {
2668 my $x = $mods[$#mods] or croak "Empty array\n";
2669 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2670 croak "Error parsing $_, $x->{chg}\n";
2672 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2673 croak "Error parsing $_, $x->{chg}\n";
2675 $x->{file_b} = $_;
2676 $state = 'meta';
2677 } else {
2678 croak "Error parsing $_\n";
2681 command_close_pipe($diff_fh, $ctx);
2682 \@mods;
2685 sub check_diff_paths {
2686 my ($ra, $pfx, $rev, $mods) = @_;
2687 my %types;
2688 $pfx .= '/' if length $pfx;
2690 sub type_diff_paths {
2691 my ($ra, $types, $path, $rev) = @_;
2692 my @p = split m#/+#, $path;
2693 my $c = shift @p;
2694 unless (defined $types->{$c}) {
2695 $types->{$c} = $ra->check_path($c, $rev);
2697 while (@p) {
2698 $c .= '/' . shift @p;
2699 next if defined $types->{$c};
2700 $types->{$c} = $ra->check_path($c, $rev);
2704 foreach my $m (@$mods) {
2705 foreach my $f (qw/file_a file_b/) {
2706 next unless defined $m->{$f};
2707 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2708 if (length $pfx.$dir && ! defined $types{$dir}) {
2709 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2713 \%types;
2716 sub split_path {
2717 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2720 sub repo_path {
2721 my ($self, $path) = @_;
2722 $self->{path_prefix}.(defined $path ? $path : '');
2725 sub url_path {
2726 my ($self, $path) = @_;
2727 $self->{url} . '/' . $self->repo_path($path);
2730 sub rmdirs {
2731 my ($self) = @_;
2732 my $rm = $self->{rm};
2733 delete $rm->{''}; # we never delete the url we're tracking
2734 return unless %$rm;
2736 foreach (keys %$rm) {
2737 my @d = split m#/#, $_;
2738 my $c = shift @d;
2739 $rm->{$c} = 1;
2740 while (@d) {
2741 $c .= '/' . shift @d;
2742 $rm->{$c} = 1;
2745 delete $rm->{$self->{svn_path}};
2746 delete $rm->{''}; # we never delete the url we're tracking
2747 return unless %$rm;
2749 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2750 $self->{tree_b});
2751 local $/ = "\0";
2752 while (<$fh>) {
2753 chomp;
2754 my @dn = split m#/#, $_;
2755 while (pop @dn) {
2756 delete $rm->{join '/', @dn};
2758 unless (%$rm) {
2759 close $fh;
2760 return;
2763 command_close_pipe($fh, $ctx);
2765 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2766 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2767 $self->close_directory($bat->{$d}, $p);
2768 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2769 print "\tD+\t$d/\n" unless $::_q;
2770 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2771 delete $bat->{$d};
2775 sub open_or_add_dir {
2776 my ($self, $full_path, $baton) = @_;
2777 my $t = $self->{types}->{$full_path};
2778 if (!defined $t) {
2779 die "$full_path not known in r$self->{r} or we have a bug!\n";
2781 if ($t == $SVN::Node::none) {
2782 return $self->add_directory($full_path, $baton,
2783 undef, -1, $self->{pool});
2784 } elsif ($t == $SVN::Node::dir) {
2785 return $self->open_directory($full_path, $baton,
2786 $self->{r}, $self->{pool});
2788 print STDERR "$full_path already exists in repository at ",
2789 "r$self->{r} and it is not a directory (",
2790 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2791 exit 1;
2794 sub ensure_path {
2795 my ($self, $path) = @_;
2796 my $bat = $self->{bat};
2797 my $repo_path = $self->repo_path($path);
2798 return $bat->{''} unless (length $repo_path);
2799 my @p = split m#/+#, $repo_path;
2800 my $c = shift @p;
2801 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2802 while (@p) {
2803 my $c0 = $c;
2804 $c .= '/' . shift @p;
2805 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2807 return $bat->{$c};
2810 sub A {
2811 my ($self, $m) = @_;
2812 my ($dir, $file) = split_path($m->{file_b});
2813 my $pbat = $self->ensure_path($dir);
2814 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2815 undef, -1);
2816 print "\tA\t$m->{file_b}\n" unless $::_q;
2817 $self->chg_file($fbat, $m);
2818 $self->close_file($fbat,undef,$self->{pool});
2821 sub C {
2822 my ($self, $m) = @_;
2823 my ($dir, $file) = split_path($m->{file_b});
2824 my $pbat = $self->ensure_path($dir);
2825 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2826 $self->url_path($m->{file_a}), $self->{r});
2827 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2828 $self->chg_file($fbat, $m);
2829 $self->close_file($fbat,undef,$self->{pool});
2832 sub delete_entry {
2833 my ($self, $path, $pbat) = @_;
2834 my $rpath = $self->repo_path($path);
2835 my ($dir, $file) = split_path($rpath);
2836 $self->{rm}->{$dir} = 1;
2837 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2840 sub R {
2841 my ($self, $m) = @_;
2842 my ($dir, $file) = split_path($m->{file_b});
2843 my $pbat = $self->ensure_path($dir);
2844 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2845 $self->url_path($m->{file_a}), $self->{r});
2846 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2847 $self->chg_file($fbat, $m);
2848 $self->close_file($fbat,undef,$self->{pool});
2850 ($dir, $file) = split_path($m->{file_a});
2851 $pbat = $self->ensure_path($dir);
2852 $self->delete_entry($m->{file_a}, $pbat);
2855 sub M {
2856 my ($self, $m) = @_;
2857 my ($dir, $file) = split_path($m->{file_b});
2858 my $pbat = $self->ensure_path($dir);
2859 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2860 $pbat,$self->{r},$self->{pool});
2861 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2862 $self->chg_file($fbat, $m);
2863 $self->close_file($fbat,undef,$self->{pool});
2866 sub T { shift->M(@_) }
2868 sub change_file_prop {
2869 my ($self, $fbat, $pname, $pval) = @_;
2870 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2873 sub chg_file {
2874 my ($self, $fbat, $m) = @_;
2875 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2876 $self->change_file_prop($fbat,'svn:executable','*');
2877 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2878 $self->change_file_prop($fbat,'svn:executable',undef);
2880 my $fh = IO::File->new_tmpfile or croak $!;
2881 if ($m->{mode_b} =~ /^120/) {
2882 print $fh 'link ' or croak $!;
2883 $self->change_file_prop($fbat,'svn:special','*');
2884 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2885 $self->change_file_prop($fbat,'svn:special',undef);
2887 defined(my $pid = fork) or croak $!;
2888 if (!$pid) {
2889 open STDOUT, '>&', $fh or croak $!;
2890 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2892 waitpid $pid, 0;
2893 croak $? if $?;
2894 $fh->flush == 0 or croak $!;
2895 seek $fh, 0, 0 or croak $!;
2897 my $md5 = Digest::MD5->new;
2898 $md5->addfile($fh) or croak $!;
2899 seek $fh, 0, 0 or croak $!;
2901 my $exp = $md5->hexdigest;
2902 my $pool = SVN::Pool->new;
2903 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2904 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2905 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2906 $pool->clear;
2908 close $fh or croak $!;
2911 sub D {
2912 my ($self, $m) = @_;
2913 my ($dir, $file) = split_path($m->{file_b});
2914 my $pbat = $self->ensure_path($dir);
2915 print "\tD\t$m->{file_b}\n" unless $::_q;
2916 $self->delete_entry($m->{file_b}, $pbat);
2919 sub close_edit {
2920 my ($self) = @_;
2921 my ($p,$bat) = ($self->{pool}, $self->{bat});
2922 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2923 next if $_ eq '';
2924 $self->close_directory($bat->{$_}, $p);
2926 $self->close_directory($bat->{''}, $p);
2927 $self->SUPER::close_edit($p);
2928 $p->clear;
2931 sub abort_edit {
2932 my ($self) = @_;
2933 $self->SUPER::abort_edit($self->{pool});
2936 sub DESTROY {
2937 my $self = shift;
2938 $self->SUPER::DESTROY(@_);
2939 $self->{pool}->clear;
2942 # this drives the editor
2943 sub apply_diff {
2944 my ($self) = @_;
2945 my $mods = $self->{mods};
2946 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2947 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2948 my $f = $m->{chg};
2949 if (defined $o{$f}) {
2950 $self->$f($m);
2951 } else {
2952 fatal("Invalid change type: $f\n");
2955 $self->rmdirs if $_rmdir;
2956 if (@$mods == 0) {
2957 $self->abort_edit;
2958 } else {
2959 $self->close_edit;
2961 return scalar @$mods;
2964 package Git::SVN::Ra;
2965 use vars qw/@ISA $config_dir $_log_window_size/;
2966 use strict;
2967 use warnings;
2968 my ($can_do_switch, %ignored_err, $RA);
2970 BEGIN {
2971 # enforce temporary pool usage for some simple functions
2972 no strict 'refs';
2973 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
2974 my $SUPER = "SUPER::$f";
2975 *$f = sub {
2976 my $self = shift;
2977 my $pool = SVN::Pool->new;
2978 my @ret = $self->$SUPER(@_,$pool);
2979 $pool->clear;
2980 wantarray ? @ret : $ret[0];
2985 sub new {
2986 my ($class, $url) = @_;
2987 $url =~ s!/+$!!;
2988 return $RA if ($RA && $RA->{url} eq $url);
2990 SVN::_Core::svn_config_ensure($config_dir, undef);
2991 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2992 SVN::Client::get_simple_provider(),
2993 SVN::Client::get_ssl_server_trust_file_provider(),
2994 SVN::Client::get_simple_prompt_provider(
2995 \&Git::SVN::Prompt::simple, 2),
2996 SVN::Client::get_ssl_client_cert_file_provider(),
2997 SVN::Client::get_ssl_client_cert_prompt_provider(
2998 \&Git::SVN::Prompt::ssl_client_cert, 2),
2999 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3000 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3001 SVN::Client::get_username_provider(),
3002 SVN::Client::get_ssl_server_trust_prompt_provider(
3003 \&Git::SVN::Prompt::ssl_server_trust),
3004 SVN::Client::get_username_prompt_provider(
3005 \&Git::SVN::Prompt::username, 2),
3007 my $config = SVN::Core::config_get_config($config_dir);
3008 $RA = undef;
3009 my $self = SVN::Ra->new(url => $url, auth => $baton,
3010 config => $config,
3011 pool => SVN::Pool->new,
3012 auth_provider_callbacks => $callbacks);
3013 $self->{svn_path} = $url;
3014 $self->{repos_root} = $self->get_repos_root;
3015 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3016 $self->{cache} = { check_path => { r => 0, data => {} },
3017 get_dir => { r => 0, data => {} } };
3018 $RA = bless $self, $class;
3021 sub check_path {
3022 my ($self, $path, $r) = @_;
3023 my $cache = $self->{cache}->{check_path};
3024 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3025 return $cache->{data}->{$path};
3027 my $pool = SVN::Pool->new;
3028 my $t = $self->SUPER::check_path($path, $r, $pool);
3029 $pool->clear;
3030 if ($r != $cache->{r}) {
3031 %{$cache->{data}} = ();
3032 $cache->{r} = $r;
3034 $cache->{data}->{$path} = $t;
3037 sub get_dir {
3038 my ($self, $dir, $r) = @_;
3039 my $cache = $self->{cache}->{get_dir};
3040 if ($r == $cache->{r}) {
3041 if (my $x = $cache->{data}->{$dir}) {
3042 return wantarray ? @$x : $x->[0];
3045 my $pool = SVN::Pool->new;
3046 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3047 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3048 $pool->clear;
3049 if ($r != $cache->{r}) {
3050 %{$cache->{data}} = ();
3051 $cache->{r} = $r;
3053 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3054 wantarray ? (\%dirents, $r, $props) : \%dirents;
3057 sub DESTROY {
3058 # do not call the real DESTROY since we store ourselves in $RA
3061 sub get_log {
3062 my ($self, @args) = @_;
3063 my $pool = SVN::Pool->new;
3064 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3065 my $ret = $self->SUPER::get_log(@args, $pool);
3066 $pool->clear;
3067 $ret;
3070 sub get_commit_editor {
3071 my ($self, $log, $cb, $pool) = @_;
3072 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3073 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3076 sub gs_do_update {
3077 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3078 my $new = ($rev_a == $rev_b);
3079 my $path = $gs->{path};
3081 if ($new && -e $gs->{index}) {
3082 unlink $gs->{index} or die
3083 "Couldn't unlink index: $gs->{index}: $!\n";
3085 my $pool = SVN::Pool->new;
3086 $editor->set_path_strip($path);
3087 my (@pc) = split m#/#, $path;
3088 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3089 1, $editor, $pool);
3090 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3092 # Since we can't rely on svn_ra_reparent being available, we'll
3093 # just have to do some magic with set_path to make it so
3094 # we only want a partial path.
3095 my $sp = '';
3096 my $final = join('/', @pc);
3097 while (@pc) {
3098 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3099 $sp .= '/' if length $sp;
3100 $sp .= shift @pc;
3102 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3104 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3106 $reporter->finish_report($pool);
3107 $pool->clear;
3108 $editor->{git_commit_ok};
3111 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3112 # svn_ra_reparent didn't work before 1.4)
3113 sub gs_do_switch {
3114 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3115 my $path = $gs->{path};
3116 my $pool = SVN::Pool->new;
3118 my $full_url = $self->{url};
3119 my $old_url = $full_url;
3120 $full_url .= "/$path" if length $path;
3121 my ($ra, $reparented);
3122 if ($old_url ne $full_url) {
3123 if ($old_url !~ m#^svn(\+ssh)?://#) {
3124 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3125 $pool);
3126 $self->{url} = $full_url;
3127 $reparented = 1;
3128 } else {
3129 $ra = Git::SVN::Ra->new($full_url);
3132 $ra ||= $self;
3133 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3134 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3135 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3136 $reporter->finish_report($pool);
3138 if ($reparented) {
3139 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3140 $self->{url} = $old_url;
3143 $pool->clear;
3144 $editor->{git_commit_ok};
3147 sub longest_common_path {
3148 my ($gsv, $globs) = @_;
3149 my %common;
3150 my $common_max = scalar @$gsv;
3152 foreach my $gs (@$gsv) {
3153 my @tmp = split m#/#, $gs->{path};
3154 my $p = '';
3155 foreach (@tmp) {
3156 $p .= length($p) ? "/$_" : $_;
3157 $common{$p} ||= 0;
3158 $common{$p}++;
3161 $globs ||= [];
3162 $common_max += scalar @$globs;
3163 foreach my $glob (@$globs) {
3164 my @tmp = split m#/#, $glob->{path}->{left};
3165 my $p = '';
3166 foreach (@tmp) {
3167 $p .= length($p) ? "/$_" : $_;
3168 $common{$p} ||= 0;
3169 $common{$p}++;
3173 my $longest_path = '';
3174 foreach (sort {length $b <=> length $a} keys %common) {
3175 if ($common{$_} == $common_max) {
3176 $longest_path = $_;
3177 last;
3180 $longest_path;
3183 sub gs_fetch_loop_common {
3184 my ($self, $base, $head, $gsv, $globs) = @_;
3185 return if ($base > $head);
3186 my $inc = $_log_window_size;
3187 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3188 my $longest_path = longest_common_path($gsv, $globs);
3189 while (1) {
3190 my %revs;
3191 my $err;
3192 my $err_handler = $SVN::Error::handler;
3193 $SVN::Error::handler = sub {
3194 ($err) = @_;
3195 skip_unknown_revs($err);
3197 sub _cb {
3198 my ($paths, $r, $author, $date, $log) = @_;
3199 [ dup_changed_paths($paths),
3200 { author => $author, date => $date, log => $log } ];
3202 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3203 sub { $revs{$_[1]} = _cb(@_) });
3204 if ($err && $max >= $head) {
3205 print STDERR "Path '$longest_path' ",
3206 "was probably deleted:\n",
3207 $err->expanded_message,
3208 "\nWill attempt to follow ",
3209 "revisions r$min .. r$max ",
3210 "committed before the deletion\n";
3211 my $hi = $max;
3212 while (--$hi >= $min) {
3213 my $ok;
3214 $self->get_log([$longest_path], $min, $hi,
3215 0, 1, 1, sub {
3216 $ok ||= $_[1];
3217 $revs{$_[1]} = _cb(@_) });
3218 if ($ok) {
3219 print STDERR "r$min .. r$ok OK\n";
3220 last;
3224 $SVN::Error::handler = $err_handler;
3226 my %exists = map { $_->{path} => $_ } @$gsv;
3227 foreach my $r (sort {$a <=> $b} keys %revs) {
3228 my ($paths, $logged) = @{$revs{$r}};
3230 foreach my $gs ($self->match_globs(\%exists, $paths,
3231 $globs, $r)) {
3232 if ($gs->rev_db_max >= $r) {
3233 next;
3235 next unless $gs->match_paths($paths, $r);
3236 $gs->{logged_rev_props} = $logged;
3237 if (my $last_commit = $gs->last_commit) {
3238 $gs->assert_index_clean($last_commit);
3240 my $log_entry = $gs->do_fetch($paths, $r);
3241 if ($log_entry) {
3242 $gs->do_git_commit($log_entry);
3245 foreach my $g (@$globs) {
3246 my $k = "svn-remote.$g->{remote}." .
3247 "$g->{t}-maxRev";
3248 Git::SVN::tmp_config($k, $r);
3251 # pre-fill the .rev_db since it'll eventually get filled in
3252 # with '0' x40 if something new gets committed
3253 foreach my $gs (@$gsv) {
3254 next if defined $gs->rev_db_get($max);
3255 $gs->rev_db_set($max, 0 x40);
3257 foreach my $g (@$globs) {
3258 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3259 Git::SVN::tmp_config($k, $max);
3261 last if $max >= $head;
3262 $min = $max + 1;
3263 $max += $inc;
3264 $max = $head if ($max > $head);
3268 sub match_globs {
3269 my ($self, $exists, $paths, $globs, $r) = @_;
3271 sub get_dir_check {
3272 my ($self, $exists, $g, $r) = @_;
3273 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3274 return unless scalar @x == 3;
3275 my $dirents = $x[0];
3276 foreach my $de (keys %$dirents) {
3277 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3278 my $p = $g->{path}->full_path($de);
3279 next if $exists->{$p};
3280 next if (length $g->{path}->{right} &&
3281 ($self->check_path($p, $r) !=
3282 $SVN::Node::dir));
3283 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3284 $g->{ref}->full_path($de), 1);
3287 foreach my $g (@$globs) {
3288 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3289 if ($path->{action} =~ /^[AR]$/) {
3290 get_dir_check($self, $exists, $g, $r);
3293 foreach (keys %$paths) {
3294 if (/$g->{path}->{left_regex}/ &&
3295 !/$g->{path}->{regex}/) {
3296 next if $paths->{$_}->{action} !~ /^[AR]$/;
3297 get_dir_check($self, $exists, $g, $r);
3299 next unless /$g->{path}->{regex}/;
3300 my $p = $1;
3301 my $pathname = $g->{path}->full_path($p);
3302 next if $exists->{$pathname};
3303 next if ($self->check_path($pathname, $r) !=
3304 $SVN::Node::dir);
3305 $exists->{$pathname} = Git::SVN->init(
3306 $self->{url}, $pathname, undef,
3307 $g->{ref}->full_path($p), 1);
3309 my $c = '';
3310 foreach (split m#/#, $g->{path}->{left}) {
3311 $c .= "/$_";
3312 next unless ($paths->{$c} &&
3313 ($paths->{$c}->{action} =~ /^[AR]$/));
3314 get_dir_check($self, $exists, $g, $r);
3317 values %$exists;
3320 sub minimize_url {
3321 my ($self) = @_;
3322 return $self->{url} if ($self->{url} eq $self->{repos_root});
3323 my $url = $self->{repos_root};
3324 my @components = split(m!/!, $self->{svn_path});
3325 my $c = '';
3326 do {
3327 $url .= "/$c" if length $c;
3328 eval { (ref $self)->new($url)->get_latest_revnum };
3329 } while ($@ && ($c = shift @components));
3330 $url;
3333 sub can_do_switch {
3334 my $self = shift;
3335 unless (defined $can_do_switch) {
3336 my $pool = SVN::Pool->new;
3337 my $rep = eval {
3338 $self->do_switch(1, '', 0, $self->{url},
3339 SVN::Delta::Editor->new, $pool);
3341 if ($@) {
3342 $can_do_switch = 0;
3343 } else {
3344 $rep->abort_report($pool);
3345 $can_do_switch = 1;
3347 $pool->clear;
3349 $can_do_switch;
3352 sub skip_unknown_revs {
3353 my ($err) = @_;
3354 my $errno = $err->apr_err();
3355 # Maybe the branch we're tracking didn't
3356 # exist when the repo started, so it's
3357 # not an error if it doesn't, just continue
3359 # Wonderfully consistent library, eh?
3360 # 160013 - svn:// and file://
3361 # 175002 - http(s)://
3362 # 175007 - http(s):// (this repo required authorization, too...)
3363 # More codes may be discovered later...
3364 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3365 my $err_key = $err->expanded_message;
3366 # revision numbers change every time, filter them out
3367 $err_key =~ s/\d+/\0/g;
3368 $err_key = "$errno\0$err_key";
3369 unless ($ignored_err{$err_key}) {
3370 warn "W: Ignoring error from SVN, path probably ",
3371 "does not exist: ($errno): ",
3372 $err->expanded_message,"\n";
3373 $ignored_err{$err_key} = 1;
3375 return;
3377 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3380 # svn_log_changed_path_t objects passed to get_log are likely to be
3381 # overwritten even if only the refs are copied to an external variable,
3382 # so we should dup the structures in their entirety. Using an externally
3383 # passed pool (instead of our temporary and quickly cleared pool in
3384 # Git::SVN::Ra) does not help matters at all...
3385 sub dup_changed_paths {
3386 my ($paths) = @_;
3387 return undef unless $paths;
3388 my %ret;
3389 foreach my $p (keys %$paths) {
3390 my $i = $paths->{$p};
3391 my %s = map { $_ => $i->$_ }
3392 qw/copyfrom_path copyfrom_rev action/;
3393 $ret{$p} = \%s;
3395 \%ret;
3398 package Git::SVN::Log;
3399 use strict;
3400 use warnings;
3401 use POSIX qw/strftime/;
3402 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3403 %rusers $show_commit $incremental/;
3404 my $l_fmt;
3406 sub cmt_showable {
3407 my ($c) = @_;
3408 return 1 if defined $c->{r};
3410 # big commit message got truncated by the 16k pretty buffer in rev-list
3411 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3412 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3413 @{$c->{l}} = ();
3414 my @log = command(qw/cat-file commit/, $c->{c});
3416 # shift off the headers
3417 shift @log while ($log[0] ne '');
3418 shift @log;
3420 # TODO: make $c->{l} not have a trailing newline in the future
3421 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3423 (undef, $c->{r}, undef) = ::extract_metadata(
3424 (grep(/^git-svn-id: /, @log))[-1]);
3426 return defined $c->{r};
3429 sub log_use_color {
3430 return 1 if $color;
3431 my ($dc, $dcvar);
3432 $dcvar = 'color.diff';
3433 $dc = `git-config --get $dcvar`;
3434 if ($dc eq '') {
3435 # nothing at all; fallback to "diff.color"
3436 $dcvar = 'diff.color';
3437 $dc = `git-config --get $dcvar`;
3439 chomp($dc);
3440 if ($dc eq 'auto') {
3441 my $pc;
3442 $pc = `git-config --get color.pager`;
3443 if ($pc eq '') {
3444 # does not have it -- fallback to pager.color
3445 $pc = `git-config --bool --get pager.color`;
3447 else {
3448 $pc = `git-config --bool --get color.pager`;
3449 if ($?) {
3450 $pc = 'false';
3453 chomp($pc);
3454 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3455 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3457 return 0;
3459 return 0 if $dc eq 'never';
3460 return 1 if $dc eq 'always';
3461 chomp($dc = `git-config --bool --get $dcvar`);
3462 return ($dc eq 'true');
3465 sub git_svn_log_cmd {
3466 my ($r_min, $r_max, @args) = @_;
3467 my $head = 'HEAD';
3468 foreach my $x (@args) {
3469 last if $x eq '--';
3470 next unless ::verify_ref("$x^0");
3471 $head = $x;
3472 last;
3475 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3476 $gs ||= Git::SVN->_new;
3477 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3478 $gs->refname);
3479 push @cmd, '-r' unless $non_recursive;
3480 push @cmd, qw/--raw --name-status/ if $verbose;
3481 push @cmd, '--color' if log_use_color();
3482 return @cmd unless defined $r_max;
3483 if ($r_max == $r_min) {
3484 push @cmd, '--max-count=1';
3485 if (my $c = $gs->rev_db_get($r_max)) {
3486 push @cmd, $c;
3488 } else {
3489 my ($c_min, $c_max);
3490 $c_max = $gs->rev_db_get($r_max);
3491 $c_min = $gs->rev_db_get($r_min);
3492 if (defined $c_min && defined $c_max) {
3493 if ($r_max > $r_max) {
3494 push @cmd, "$c_min..$c_max";
3495 } else {
3496 push @cmd, "$c_max..$c_min";
3498 } elsif ($r_max > $r_min) {
3499 push @cmd, $c_max;
3500 } else {
3501 push @cmd, $c_min;
3504 return @cmd;
3507 # adapted from pager.c
3508 sub config_pager {
3509 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3510 if (!defined $pager) {
3511 $pager = 'less';
3512 } elsif (length $pager == 0 || $pager eq 'cat') {
3513 $pager = undef;
3517 sub run_pager {
3518 return unless -t *STDOUT;
3519 pipe my $rfd, my $wfd or return;
3520 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3521 if (!$pid) {
3522 open STDOUT, '>&', $wfd or
3523 ::fatal "Can't redirect to stdout: $!\n";
3524 return;
3526 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3527 $ENV{LESS} ||= 'FRSX';
3528 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3531 sub tz_to_s_offset {
3532 my ($tz) = @_;
3533 $tz =~ s/(\d\d)$//;
3534 return ($1 * 60) + ($tz * 3600);
3537 sub get_author_info {
3538 my ($dest, $author, $t, $tz) = @_;
3539 $author =~ s/(?:^\s*|\s*$)//g;
3540 $dest->{a_raw} = $author;
3541 my $au;
3542 if ($::_authors) {
3543 $au = $rusers{$author} || undef;
3545 if (!$au) {
3546 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3548 $dest->{t} = $t;
3549 $dest->{tz} = $tz;
3550 $dest->{a} = $au;
3551 # Date::Parse isn't in the standard Perl distro :(
3552 if ($tz =~ s/^\+//) {
3553 $t += tz_to_s_offset($tz);
3554 } elsif ($tz =~ s/^\-//) {
3555 $t -= tz_to_s_offset($tz);
3557 $dest->{t_utc} = $t;
3560 sub process_commit {
3561 my ($c, $r_min, $r_max, $defer) = @_;
3562 if (defined $r_min && defined $r_max) {
3563 if ($r_min == $c->{r} && $r_min == $r_max) {
3564 show_commit($c);
3565 return 0;
3567 return 1 if $r_min == $r_max;
3568 if ($r_min < $r_max) {
3569 # we need to reverse the print order
3570 return 0 if (defined $limit && --$limit < 0);
3571 push @$defer, $c;
3572 return 1;
3574 if ($r_min != $r_max) {
3575 return 1 if ($r_min < $c->{r});
3576 return 1 if ($r_max > $c->{r});
3579 return 0 if (defined $limit && --$limit < 0);
3580 show_commit($c);
3581 return 1;
3584 sub show_commit {
3585 my $c = shift;
3586 if ($oneline) {
3587 my $x = "\n";
3588 if (my $l = $c->{l}) {
3589 while ($l->[0] =~ /^\s*$/) { shift @$l }
3590 $x = $l->[0];
3592 $l_fmt ||= 'A' . length($c->{r});
3593 print 'r',pack($l_fmt, $c->{r}),' | ';
3594 print "$c->{c} | " if $show_commit;
3595 print $x;
3596 } else {
3597 show_commit_normal($c);
3601 sub show_commit_changed_paths {
3602 my ($c) = @_;
3603 return unless $c->{changed};
3604 print "Changed paths:\n", @{$c->{changed}};
3607 sub show_commit_normal {
3608 my ($c) = @_;
3609 print '-' x72, "\nr$c->{r} | ";
3610 print "$c->{c} | " if $show_commit;
3611 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3612 localtime($c->{t_utc})), ' | ';
3613 my $nr_line = 0;
3615 if (my $l = $c->{l}) {
3616 while ($l->[$#$l] eq "\n" && $#$l > 0
3617 && $l->[($#$l - 1)] eq "\n") {
3618 pop @$l;
3620 $nr_line = scalar @$l;
3621 if (!$nr_line) {
3622 print "1 line\n\n\n";
3623 } else {
3624 if ($nr_line == 1) {
3625 $nr_line = '1 line';
3626 } else {
3627 $nr_line .= ' lines';
3629 print $nr_line, "\n";
3630 show_commit_changed_paths($c);
3631 print "\n";
3632 print $_ foreach @$l;
3634 } else {
3635 print "1 line\n";
3636 show_commit_changed_paths($c);
3637 print "\n";
3640 foreach my $x (qw/raw stat diff/) {
3641 if ($c->{$x}) {
3642 print "\n";
3643 print $_ foreach @{$c->{$x}}
3648 sub cmd_show_log {
3649 my (@args) = @_;
3650 my ($r_min, $r_max);
3651 my $r_last = -1; # prevent dupes
3652 if (defined $TZ) {
3653 $ENV{TZ} = $TZ;
3654 } else {
3655 delete $ENV{TZ};
3657 if (defined $::_revision) {
3658 if ($::_revision =~ /^(\d+):(\d+)$/) {
3659 ($r_min, $r_max) = ($1, $2);
3660 } elsif ($::_revision =~ /^\d+$/) {
3661 $r_min = $r_max = $::_revision;
3662 } else {
3663 ::fatal "-r$::_revision is not supported, use ",
3664 "standard \'git log\' arguments instead\n";
3668 config_pager();
3669 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3670 my $log = command_output_pipe(@args);
3671 run_pager();
3672 my (@k, $c, $d, $stat);
3673 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3674 while (<$log>) {
3675 if (/^${esc_color}commit ($::sha1_short)/o) {
3676 my $cmt = $1;
3677 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3678 $r_last = $c->{r};
3679 process_commit($c, $r_min, $r_max, \@k) or
3680 goto out;
3682 $d = undef;
3683 $c = { c => $cmt };
3684 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3685 get_author_info($c, $1, $2, $3);
3686 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3687 # ignore
3688 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3689 push @{$c->{raw}}, $_;
3690 } elsif (/^${esc_color}[ACRMDT]\t/) {
3691 # we could add $SVN->{svn_path} here, but that requires
3692 # remote access at the moment (repo_path_split)...
3693 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3694 push @{$c->{changed}}, $_;
3695 } elsif (/^${esc_color}diff /o) {
3696 $d = 1;
3697 push @{$c->{diff}}, $_;
3698 } elsif ($d) {
3699 push @{$c->{diff}}, $_;
3700 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3701 $esc_color*[\+\-]*$esc_color$/x) {
3702 $stat = 1;
3703 push @{$c->{stat}}, $_;
3704 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3705 push @{$c->{stat}}, $_;
3706 $stat = undef;
3707 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3708 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3709 } elsif (s/^${esc_color} //o) {
3710 push @{$c->{l}}, $_;
3713 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3714 $r_last = $c->{r};
3715 process_commit($c, $r_min, $r_max, \@k);
3717 if (@k) {
3718 my $swap = $r_max;
3719 $r_max = $r_min;
3720 $r_min = $swap;
3721 process_commit($_, $r_min, $r_max) foreach reverse @k;
3723 out:
3724 close $log;
3725 print '-' x72,"\n" unless $incremental || $oneline;
3728 package Git::SVN::Migration;
3729 # these version numbers do NOT correspond to actual version numbers
3730 # of git nor git-svn. They are just relative.
3732 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3734 # v1 layout: .git/$id/info/url, refs/remotes/$id
3736 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3738 # v3 layout: .git/svn/$id, refs/remotes/$id
3739 # - info/url may remain for backwards compatibility
3740 # - this is what we migrate up to this layout automatically,
3741 # - this will be used by git svn init on single branches
3742 # v3.1 layout (auto migrated):
3743 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3744 # for backwards compatibility
3746 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3747 # - this is only created for newly multi-init-ed
3748 # repositories. Similar in spirit to the
3749 # --use-separate-remotes option in git-clone (now default)
3750 # - we do not automatically migrate to this (following
3751 # the example set by core git)
3752 use strict;
3753 use warnings;
3754 use Carp qw/croak/;
3755 use File::Path qw/mkpath/;
3756 use File::Basename qw/dirname basename/;
3757 use vars qw/$_minimize/;
3759 sub migrate_from_v0 {
3760 my $git_dir = $ENV{GIT_DIR};
3761 return undef unless -d $git_dir;
3762 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3763 my $migrated = 0;
3764 while (<$fh>) {
3765 chomp;
3766 my ($id, $orig_ref) = ($_, $_);
3767 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3768 next unless -f "$git_dir/$id/info/url";
3769 my $new_ref = "refs/remotes/$id";
3770 if (::verify_ref("$new_ref^0")) {
3771 print STDERR "W: $orig_ref is probably an old ",
3772 "branch used by an ancient version of ",
3773 "git-svn.\n",
3774 "However, $new_ref also exists.\n",
3775 "We will not be able ",
3776 "to use this branch until this ",
3777 "ambiguity is resolved.\n";
3778 next;
3780 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3781 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3782 command_noisy('update-ref', $new_ref, $orig_ref);
3783 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3784 $migrated++;
3786 command_close_pipe($fh, $ctx);
3787 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3788 $migrated;
3791 sub migrate_from_v1 {
3792 my $git_dir = $ENV{GIT_DIR};
3793 my $migrated = 0;
3794 return $migrated unless -d $git_dir;
3795 my $svn_dir = "$git_dir/svn";
3797 # just in case somebody used 'svn' as their $id at some point...
3798 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3800 print STDERR "Migrating from a git-svn v1 layout...\n";
3801 mkpath([$svn_dir]);
3802 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3803 "$svn_dir\n\t(required for this version ",
3804 "($::VERSION) of git-svn) does not. exist\n";
3805 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3806 while (<$fh>) {
3807 my $x = $_;
3808 next unless $x =~ s#^refs/remotes/##;
3809 chomp $x;
3810 next unless -f "$git_dir/$x/info/url";
3811 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3812 next unless $u;
3813 my $dn = dirname("$git_dir/svn/$x");
3814 mkpath([$dn]) unless -d $dn;
3815 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3816 mkpath(["$git_dir/svn/svn"]);
3817 print STDERR " - $git_dir/$x/info => ",
3818 "$git_dir/svn/$x/info\n";
3819 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3820 croak "$!: $x";
3821 # don't worry too much about these, they probably
3822 # don't exist with repos this old (save for index,
3823 # and we can easily regenerate that)
3824 foreach my $f (qw/unhandled.log index .rev_db/) {
3825 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3827 } else {
3828 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3829 rename "$git_dir/$x", "$git_dir/svn/$x" or
3830 croak "$!: $x";
3832 $migrated++;
3834 command_close_pipe($fh, $ctx);
3835 print STDERR "Done migrating from a git-svn v1 layout\n";
3836 $migrated;
3839 sub read_old_urls {
3840 my ($l_map, $pfx, $path) = @_;
3841 my @dir;
3842 foreach (<$path/*>) {
3843 if (-r "$_/info/url") {
3844 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3845 my $ref_id = $pfx . basename $_;
3846 my $url = ::file_to_s("$_/info/url");
3847 $l_map->{$ref_id} = $url;
3848 } elsif (-d $_) {
3849 push @dir, $_;
3852 foreach (@dir) {
3853 my $x = $_;
3854 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3855 read_old_urls($l_map, $x, $_);
3859 sub migrate_from_v2 {
3860 my @cfg = command(qw/config -l/);
3861 return if grep /^svn-remote\..+\.url=/, @cfg;
3862 my %l_map;
3863 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3864 my $migrated = 0;
3866 foreach my $ref_id (sort keys %l_map) {
3867 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3868 if ($@) {
3869 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3871 $migrated++;
3873 $migrated;
3876 sub minimize_connections {
3877 my $r = Git::SVN::read_all_remotes();
3878 my $new_urls = {};
3879 my $root_repos = {};
3880 foreach my $repo_id (keys %$r) {
3881 my $url = $r->{$repo_id}->{url} or next;
3882 my $fetch = $r->{$repo_id}->{fetch} or next;
3883 my $ra = Git::SVN::Ra->new($url);
3885 # skip existing cases where we already connect to the root
3886 if (($ra->{url} eq $ra->{repos_root}) ||
3887 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3888 $repo_id)) {
3889 $root_repos->{$ra->{url}} = $repo_id;
3890 next;
3893 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3894 my $root_path = $ra->{url};
3895 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3896 foreach my $path (keys %$fetch) {
3897 my $ref_id = $fetch->{$path};
3898 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3900 # make sure we can read when connecting to
3901 # a higher level of a repository
3902 my ($last_rev, undef) = $gs->last_rev_commit;
3903 if (!defined $last_rev) {
3904 $last_rev = eval {
3905 $root_ra->get_latest_revnum;
3907 next if $@;
3909 my $new = $root_path;
3910 $new .= length $path ? "/$path" : '';
3911 eval {
3912 $root_ra->get_log([$new], $last_rev, $last_rev,
3913 0, 0, 1, sub { });
3915 next if $@;
3916 $new_urls->{$ra->{repos_root}}->{$new} =
3917 { ref_id => $ref_id,
3918 old_repo_id => $repo_id,
3919 old_path => $path };
3923 my @emptied;
3924 foreach my $url (keys %$new_urls) {
3925 # see if we can re-use an existing [svn-remote "repo_id"]
3926 # instead of creating a(n ugly) new section:
3927 my $repo_id = $root_repos->{$url} ||
3928 Git::SVN::sanitize_remote_name($url);
3930 my $fetch = $new_urls->{$url};
3931 foreach my $path (keys %$fetch) {
3932 my $x = $fetch->{$path};
3933 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3934 my $pfx = "svn-remote.$x->{old_repo_id}";
3936 my $old_fetch = quotemeta("$x->{old_path}:".
3937 "refs/remotes/$x->{ref_id}");
3938 command_noisy(qw/config --unset/,
3939 "$pfx.fetch", '^'. $old_fetch . '$');
3940 delete $r->{$x->{old_repo_id}}->
3941 {fetch}->{$x->{old_path}};
3942 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3943 command_noisy(qw/config --unset/,
3944 "$pfx.url");
3945 push @emptied, $x->{old_repo_id}
3949 if (@emptied) {
3950 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3951 "$ENV{GIT_DIR}/config";
3952 print STDERR <<EOF;
3953 The following [svn-remote] sections in your config file ($file) are empty
3954 and can be safely removed:
3956 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3960 sub migration_check {
3961 migrate_from_v0();
3962 migrate_from_v1();
3963 migrate_from_v2();
3964 minimize_connections() if $_minimize;
3967 package Git::IndexInfo;
3968 use strict;
3969 use warnings;
3970 use Git qw/command_input_pipe command_close_pipe/;
3972 sub new {
3973 my ($class) = @_;
3974 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3975 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3978 sub remove {
3979 my ($self, $path) = @_;
3980 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3981 return ++$self->{nr};
3983 undef;
3986 sub update {
3987 my ($self, $mode, $hash, $path) = @_;
3988 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3989 return ++$self->{nr};
3991 undef;
3994 sub DESTROY {
3995 my ($self) = @_;
3996 command_close_pipe($self->{gui}, $self->{ctx});
3999 package Git::SVN::GlobSpec;
4000 use strict;
4001 use warnings;
4003 sub new {
4004 my ($class, $glob) = @_;
4005 my $re = $glob;
4006 $re =~ s!/+$!!g; # no need for trailing slashes
4007 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4008 my ($left, $right) = ($1, $2);
4009 if ($nr > 1) {
4010 die "Only one '*' wildcard expansion ",
4011 "is supported (got $nr): '$glob'\n";
4012 } elsif ($nr == 0) {
4013 die "One '*' is needed for glob: '$glob'\n";
4015 $re = quotemeta($left) . $re . quotemeta($right);
4016 if (length $left && !($left =~ s!/+$!!g)) {
4017 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4019 if (length $right && !($right =~ s!^/+!!g)) {
4020 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4022 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4023 bless { left => $left, right => $right, left_regex => $left_re,
4024 regex => qr/$re/, glob => $glob }, $class;
4027 sub full_path {
4028 my ($self, $path) = @_;
4029 return (length $self->{left} ? "$self->{left}/" : '') .
4030 $path . (length $self->{right} ? "/$self->{right}" : '');
4033 __END__
4035 Data structures:
4038 $remotes = { # returned by read_all_remotes()
4039 'svn' => {
4040 # svn-remote.svn.url=https://svn.musicpd.org
4041 url => 'https://svn.musicpd.org',
4042 # svn-remote.svn.fetch=mpd/trunk:trunk
4043 fetch => {
4044 'mpd/trunk' => 'trunk',
4046 # svn-remote.svn.tags=mpd/tags/*:tags/*
4047 tags => {
4048 path => {
4049 left => 'mpd/tags',
4050 right => '',
4051 regex => qr!mpd/tags/([^/]+)$!,
4052 glob => 'tags/*',
4054 ref => {
4055 left => 'tags',
4056 right => '',
4057 regex => qr!tags/([^/]+)$!,
4058 glob => 'tags/*',
4064 $log_entry hashref as returned by libsvn_log_entry()
4066 log => 'whitespace-formatted log entry
4067 ', # trailing newline is preserved
4068 revision => '8', # integer
4069 date => '2004-02-24T17:01:44.108345Z', # commit date
4070 author => 'committer name'
4074 # this is generated by generate_diff();
4075 @mods = array of diff-index line hashes, each element represents one line
4076 of diff-index output
4078 diff-index line ($m hash)
4080 mode_a => first column of diff-index output, no leading ':',
4081 mode_b => second column of diff-index output,
4082 sha1_b => sha1sum of the final blob,
4083 chg => change type [MCRADT],
4084 file_a => original file name of a file (iff chg is 'C' or 'R')
4085 file_b => new/current file name of a file (any chg)
4089 # retval of read_url_paths{,_all}();
4090 $l_map = {
4091 # repository root url
4092 'https://svn.musicpd.org' => {
4093 # repository path # GIT_SVN_ID
4094 'mpd/trunk' => 'trunk',
4095 'mpd/tags/0.11.5' => 'tags/0.11.5',
4099 Notes:
4100 I don't trust the each() function on unless I created %hash myself
4101 because the internal iterator may not have started at base.