Fix t5516-fetch for systems where `wc -l` outputs whitespace.
[alt-git.git] / git-svn.perl
blob03d5e2d979c48159643256634861162d34a470ce
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 $c = $refs[-1];
378 my $last_rev;
379 foreach my $d (@refs) {
380 if (!verify_ref("$d~1")) {
381 fatal "Commit $d\n",
382 "has no parent commit, and therefore ",
383 "nothing to diff against.\n",
384 "You should be working from a repository ",
385 "originally created by git-svn\n";
387 unless (defined $last_rev) {
388 (undef, $last_rev, undef) = cmt_metadata("$d~1");
389 unless (defined $last_rev) {
390 fatal "Unable to extract revision information ",
391 "from commit $d~1\n";
394 if ($_dry_run) {
395 print "diff-tree $d~1 $d\n";
396 } else {
397 my %ed_opts = ( r => $last_rev,
398 log => get_commit_entry($d)->{log},
399 ra => Git::SVN::Ra->new($gs->full_url),
400 tree_a => "$d~1",
401 tree_b => $d,
402 editor_cb => sub {
403 print "Committed r$_[0]\n";
404 $last_rev = $_[0]; },
405 svn_path => '');
406 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
407 print "No changes\n$d~1 == $d\n";
411 return if $_dry_run;
412 unless ($gs) {
413 warn "Could not determine fetch information for $url\n",
414 "Will not attempt to fetch and rebase commits.\n",
415 "This probably means you have useSvmProps and should\n",
416 "now resync your SVN::Mirror repository.\n";
417 return;
419 $_fetch_all ? $gs->fetch_all : $gs->fetch;
420 unless ($_no_rebase) {
421 # we always want to rebase against the current HEAD, not any
422 # head that was passed to us
423 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
424 my @finish;
425 if (@diff) {
426 @finish = rebase_cmd();
427 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
428 "using @finish:\n", "@diff";
429 } else {
430 print "No changes between current HEAD and ",
431 $gs->refname, "\nResetting to the latest ",
432 $gs->refname, "\n";
433 @finish = qw/reset --mixed/;
435 command_noisy(@finish, $gs->refname);
439 sub cmd_find_rev {
440 my $revision_or_hash = shift;
441 my $result;
442 if ($revision_or_hash =~ /^r\d+$/) {
443 my $head = shift;
444 $head ||= 'HEAD';
445 my @refs;
446 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
447 unless ($gs) {
448 die "Unable to determine upstream SVN information from ",
449 "$head history\n";
451 my $desired_revision = substr($revision_or_hash, 1);
452 $result = $gs->rev_db_get($desired_revision);
453 } else {
454 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
455 $result = $rev;
457 print "$result\n" if $result;
460 sub cmd_rebase {
461 command_noisy(qw/update-index --refresh/);
462 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
463 unless ($gs) {
464 die "Unable to determine upstream SVN information from ",
465 "working tree history\n";
467 if (command(qw/diff-index HEAD --/)) {
468 print STDERR "Cannot rebase with uncommited changes:\n";
469 command_noisy('status');
470 exit 1;
472 unless ($_local) {
473 $_fetch_all ? $gs->fetch_all : $gs->fetch;
475 command_noisy(rebase_cmd(), $gs->refname);
478 sub cmd_show_ignore {
479 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
480 $gs ||= Git::SVN->new;
481 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
482 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
485 sub cmd_multi_init {
486 my $url = shift;
487 unless (defined $_trunk || defined $_branches || defined $_tags) {
488 usage(1);
491 # there are currently some bugs that prevent multi-init/multi-fetch
492 # setups from working well without this.
493 $Git::SVN::_minimize_url = 1;
495 $_prefix = '' unless defined $_prefix;
496 if (defined $url) {
497 $url =~ s#/+$##;
498 init_subdir(@_);
500 do_git_init_db();
501 if (defined $_trunk) {
502 my $trunk_ref = $_prefix . 'trunk';
503 # try both old-style and new-style lookups:
504 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
505 unless ($gs_trunk) {
506 my ($trunk_url, $trunk_path) =
507 complete_svn_url($url, $_trunk);
508 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
509 undef, $trunk_ref);
512 return unless defined $_branches || defined $_tags;
513 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
514 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
515 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
518 sub cmd_multi_fetch {
519 my $remotes = Git::SVN::read_all_remotes();
520 foreach my $repo_id (sort keys %$remotes) {
521 if ($remotes->{$repo_id}->{url}) {
522 Git::SVN::fetch_all($repo_id, $remotes);
527 # this command is special because it requires no metadata
528 sub cmd_commit_diff {
529 my ($ta, $tb, $url) = @_;
530 my $usage = "Usage: $0 commit-diff -r<revision> ".
531 "<tree-ish> <tree-ish> [<URL>]\n";
532 fatal($usage) if (!defined $ta || !defined $tb);
533 my $svn_path;
534 if (!defined $url) {
535 my $gs = eval { Git::SVN->new };
536 if (!$gs) {
537 fatal("Needed URL or usable git-svn --id in ",
538 "the command-line\n", $usage);
540 $url = $gs->{url};
541 $svn_path = $gs->{path};
543 unless (defined $_revision) {
544 fatal("-r|--revision is a required argument\n", $usage);
546 if (defined $_message && defined $_file) {
547 fatal("Both --message/-m and --file/-F specified ",
548 "for the commit message.\n",
549 "I have no idea what you mean\n");
551 if (defined $_file) {
552 $_message = file_to_s($_file);
553 } else {
554 $_message ||= get_commit_entry($tb)->{log};
556 my $ra ||= Git::SVN::Ra->new($url);
557 $svn_path ||= $ra->{svn_path};
558 my $r = $_revision;
559 if ($r eq 'HEAD') {
560 $r = $ra->get_latest_revnum;
561 } elsif ($r !~ /^\d+$/) {
562 die "revision argument: $r not understood by git-svn\n";
564 my %ed_opts = ( r => $r,
565 log => $_message,
566 ra => $ra,
567 tree_a => $ta,
568 tree_b => $tb,
569 editor_cb => sub { print "Committed r$_[0]\n" },
570 svn_path => $svn_path );
571 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
572 print "No changes\n$ta == $tb\n";
576 ########################### utility functions #########################
578 sub rebase_cmd {
579 my @cmd = qw/rebase/;
580 push @cmd, '-v' if $_verbose;
581 push @cmd, qw/--merge/ if $_merge;
582 push @cmd, "--strategy=$_strategy" if $_strategy;
583 @cmd;
586 sub post_fetch_checkout {
587 return if $_no_checkout;
588 my $gs = $Git::SVN::_head or return;
589 return if verify_ref('refs/heads/master^0');
591 my $valid_head = verify_ref('HEAD^0');
592 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
593 return if ($valid_head || !verify_ref('HEAD^0'));
595 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
596 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
597 return if -f $index;
599 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
600 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
601 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
602 print STDERR "Checked out HEAD:\n ",
603 $gs->full_url, " r", $gs->last_rev, "\n";
606 sub complete_svn_url {
607 my ($url, $path) = @_;
608 $path =~ s#/+$##;
609 if ($path !~ m#^[a-z\+]+://#) {
610 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
611 fatal("E: '$path' is not a complete URL ",
612 "and a separate URL is not specified\n");
614 return ($url, $path);
616 return ($path, '');
619 sub complete_url_ls_init {
620 my ($ra, $repo_path, $switch, $pfx) = @_;
621 unless ($repo_path) {
622 print STDERR "W: $switch not specified\n";
623 return;
625 $repo_path =~ s#/+$##;
626 if ($repo_path =~ m#^[a-z\+]+://#) {
627 $ra = Git::SVN::Ra->new($repo_path);
628 $repo_path = '';
629 } else {
630 $repo_path =~ s#^/+##;
631 unless ($ra) {
632 fatal("E: '$repo_path' is not a complete URL ",
633 "and a separate URL is not specified\n");
636 my $url = $ra->{url};
637 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
638 my $k = "svn-remote.$gs->{repo_id}.url";
639 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
640 if ($orig_url && ($orig_url ne $gs->{url})) {
641 die "$k already set: $orig_url\n",
642 "wanted to set to: $gs->{url}\n";
644 command_oneline('config', $k, $gs->{url}) unless $orig_url;
645 my $remote_path = "$ra->{svn_path}/$repo_path/*";
646 $remote_path =~ s#/+#/#g;
647 $remote_path =~ s#^/##g;
648 my ($n) = ($switch =~ /^--(\w+)/);
649 if (length $pfx && $pfx !~ m#/$#) {
650 die "--prefix='$pfx' must have a trailing slash '/'\n";
652 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
653 "$remote_path:refs/remotes/$pfx*");
656 sub verify_ref {
657 my ($ref) = @_;
658 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
659 { STDERR => 0 }); };
662 sub get_tree_from_treeish {
663 my ($treeish) = @_;
664 # $treeish can be a symbolic ref, too:
665 my $type = command_oneline(qw/cat-file -t/, $treeish);
666 my $expected;
667 while ($type eq 'tag') {
668 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
670 if ($type eq 'commit') {
671 $expected = (grep /^tree /, command(qw/cat-file commit/,
672 $treeish))[0];
673 ($expected) = ($expected =~ /^tree ($sha1)$/o);
674 die "Unable to get tree from $treeish\n" unless $expected;
675 } elsif ($type eq 'tree') {
676 $expected = $treeish;
677 } else {
678 die "$treeish is a $type, expected tree, tag or commit\n";
680 return $expected;
683 sub get_commit_entry {
684 my ($treeish) = shift;
685 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
686 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
687 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
688 open my $log_fh, '>', $commit_editmsg or croak $!;
690 my $type = command_oneline(qw/cat-file -t/, $treeish);
691 if ($type eq 'commit' || $type eq 'tag') {
692 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
693 $type, $treeish);
694 my $in_msg = 0;
695 while (<$msg_fh>) {
696 if (!$in_msg) {
697 $in_msg = 1 if (/^\s*$/);
698 } elsif (/^git-svn-id: /) {
699 # skip this for now, we regenerate the
700 # correct one on re-fetch anyways
701 # TODO: set *:merge properties or like...
702 } else {
703 print $log_fh $_ or croak $!;
706 command_close_pipe($msg_fh, $ctx);
708 close $log_fh or croak $!;
710 if ($_edit || ($type eq 'tree')) {
711 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
712 # TODO: strip out spaces, comments, like git-commit.sh
713 system($editor, $commit_editmsg);
715 rename $commit_editmsg, $commit_msg or croak $!;
716 open $log_fh, '<', $commit_msg or croak $!;
717 { local $/; chomp($log_entry{log} = <$log_fh>); }
718 close $log_fh or croak $!;
719 unlink $commit_msg;
720 \%log_entry;
723 sub s_to_file {
724 my ($str, $file, $mode) = @_;
725 open my $fd,'>',$file or croak $!;
726 print $fd $str,"\n" or croak $!;
727 close $fd or croak $!;
728 chmod ($mode &~ umask, $file) if (defined $mode);
731 sub file_to_s {
732 my $file = shift;
733 open my $fd,'<',$file or croak "$!: file: $file\n";
734 local $/;
735 my $ret = <$fd>;
736 close $fd or croak $!;
737 $ret =~ s/\s*$//s;
738 return $ret;
741 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
742 sub load_authors {
743 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
744 my $log = $cmd eq 'log';
745 while (<$authors>) {
746 chomp;
747 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
748 my ($user, $name, $email) = ($1, $2, $3);
749 if ($log) {
750 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
751 } else {
752 $users{$user} = [$name, $email];
755 close $authors or croak $!;
758 # convert GetOpt::Long specs for use by git-config
759 sub read_repo_config {
760 return unless -d $ENV{GIT_DIR};
761 my $opts = shift;
762 my @config_only;
763 foreach my $o (keys %$opts) {
764 # if we have mixedCase and a long option-only, then
765 # it's a config-only variable that we don't need for
766 # the command-line.
767 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
768 my $v = $opts->{$o};
769 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
770 $key =~ s/-//g;
771 my $arg = 'git-config';
772 $arg .= ' --int' if ($o =~ /[:=]i$/);
773 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
774 if (ref $v eq 'ARRAY') {
775 chomp(my @tmp = `$arg --get-all svn.$key`);
776 @$v = @tmp if @tmp;
777 } else {
778 chomp(my $tmp = `$arg --get svn.$key`);
779 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
780 $$v = $tmp;
784 delete @$opts{@config_only} if @config_only;
787 sub extract_metadata {
788 my $id = shift or return (undef, undef, undef);
789 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
790 \s([a-f\d\-]+)$/x);
791 if (!defined $rev || !$uuid || !$url) {
792 # some of the original repositories I made had
793 # identifiers like this:
794 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
796 return ($url, $rev, $uuid);
799 sub cmt_metadata {
800 return extract_metadata((grep(/^git-svn-id: /,
801 command(qw/cat-file commit/, shift)))[-1]);
804 sub working_head_info {
805 my ($head, $refs) = @_;
806 my ($fh, $ctx) = command_output_pipe('log', $head);
807 my $hash;
808 my %max;
809 while (<$fh>) {
810 if ( m{^commit ($::sha1)$} ) {
811 unshift @$refs, $hash if $hash and $refs;
812 $hash = $1;
813 next;
815 next unless s{^\s*(git-svn-id:)}{$1};
816 my ($url, $rev, $uuid) = extract_metadata($_);
817 if (defined $url && defined $rev) {
818 next if $max{$url} and $max{$url} < $rev;
819 if (my $gs = Git::SVN->find_by_url($url)) {
820 my $c = $gs->rev_db_get($rev);
821 if ($c && $c eq $hash) {
822 close $fh; # break the pipe
823 return ($url, $rev, $uuid, $gs);
824 } else {
825 $max{$url} ||= $gs->rev_db_max;
830 command_close_pipe($fh, $ctx);
831 (undef, undef, undef, undef);
834 package Git::SVN;
835 use strict;
836 use warnings;
837 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
838 $_repack $_repack_flags $_use_svm_props $_head
839 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
840 use Carp qw/croak/;
841 use File::Path qw/mkpath/;
842 use File::Copy qw/copy/;
843 use IPC::Open3;
845 my $_repack_nr;
846 # properties that we do not log:
847 my %SKIP_PROP;
848 BEGIN {
849 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
850 svn:special svn:executable
851 svn:entry:committed-rev
852 svn:entry:last-author
853 svn:entry:uuid
854 svn:entry:committed-date/;
856 # some options are read globally, but can be overridden locally
857 # per [svn-remote "..."] section. Command-line options will *NOT*
858 # override options set in an [svn-remote "..."] section
859 no strict 'refs';
860 for my $option (qw/follow_parent no_metadata use_svm_props
861 use_svnsync_props/) {
862 my $key = $option;
863 $key =~ tr/_//d;
864 my $prop = "-$option";
865 *$option = sub {
866 my ($self) = @_;
867 return $self->{$prop} if exists $self->{$prop};
868 my $k = "svn-remote.$self->{repo_id}.$key";
869 eval { command_oneline(qw/config --get/, $k) };
870 if ($@) {
871 $self->{$prop} = ${"Git::SVN::_$option"};
872 } else {
873 my $v = command_oneline(qw/config --bool/,$k);
874 $self->{$prop} = $v eq 'false' ? 0 : 1;
876 return $self->{$prop};
881 my %LOCKFILES;
882 END { unlink keys %LOCKFILES if %LOCKFILES }
884 sub resolve_local_globs {
885 my ($url, $fetch, $glob_spec) = @_;
886 return unless defined $glob_spec;
887 my $ref = $glob_spec->{ref};
888 my $path = $glob_spec->{path};
889 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
890 next unless m#^refs/remotes/$ref->{regex}$#;
891 my $p = $1;
892 my $pathname = $path->full_path($p);
893 my $refname = $ref->full_path($p);
894 if (my $existing = $fetch->{$pathname}) {
895 if ($existing ne $refname) {
896 die "Refspec conflict:\n",
897 "existing: refs/remotes/$existing\n",
898 " globbed: refs/remotes/$refname\n";
900 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
901 $u =~ s!^\Q$url\E(/|$)!! or die
902 "refs/remotes/$refname: '$url' not found in '$u'\n";
903 if ($pathname ne $u) {
904 warn "W: Refspec glob conflict ",
905 "(ref: refs/remotes/$refname):\n",
906 "expected path: $pathname\n",
907 " real path: $u\n",
908 "Continuing ahead with $u\n";
909 next;
911 } else {
912 $fetch->{$pathname} = $refname;
917 sub parse_revision_argument {
918 my ($base, $head) = @_;
919 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
920 return ($base, $head);
922 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
923 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
924 return ($head, $head) if ($::_revision eq 'HEAD');
925 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
926 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
927 die "revision argument: $::_revision not understood by git-svn\n";
930 sub fetch_all {
931 my ($repo_id, $remotes) = @_;
932 if (ref $repo_id) {
933 my $gs = $repo_id;
934 $repo_id = undef;
935 $repo_id = $gs->{repo_id};
937 $remotes ||= read_all_remotes();
938 my $remote = $remotes->{$repo_id} or
939 die "[svn-remote \"$repo_id\"] unknown\n";
940 my $fetch = $remote->{fetch};
941 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
942 my (@gs, @globs);
943 my $ra = Git::SVN::Ra->new($url);
944 my $uuid = $ra->get_uuid;
945 my $head = $ra->get_latest_revnum;
946 my $base = defined $fetch ? $head : 0;
948 # read the max revs for wildcard expansion (branches/*, tags/*)
949 foreach my $t (qw/branches tags/) {
950 defined $remote->{$t} or next;
951 push @globs, $remote->{$t};
952 my $max_rev = eval { tmp_config(qw/--int --get/,
953 "svn-remote.$repo_id.${t}-maxRev") };
954 if (defined $max_rev && ($max_rev < $base)) {
955 $base = $max_rev;
956 } elsif (!defined $max_rev) {
957 $base = 0;
961 if ($fetch) {
962 foreach my $p (sort keys %$fetch) {
963 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
964 my $lr = $gs->rev_db_max;
965 if (defined $lr) {
966 $base = $lr if ($lr < $base);
968 push @gs, $gs;
972 ($base, $head) = parse_revision_argument($base, $head);
973 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
976 sub read_all_remotes {
977 my $r = {};
978 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
979 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
980 $r->{$1}->{fetch}->{$2} = $3;
981 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
982 $r->{$1}->{url} = $2;
983 } elsif (m!^(.+)\.(branches|tags)=
984 (.*):refs/remotes/(.+)\s*$/!x) {
985 my ($p, $g) = ($3, $4);
986 my $rs = $r->{$1}->{$2} = {
987 t => $2,
988 remote => $1,
989 path => Git::SVN::GlobSpec->new($p),
990 ref => Git::SVN::GlobSpec->new($g) };
991 if (length($rs->{ref}->{right}) != 0) {
992 die "The '*' glob character must be the last ",
993 "character of '$g'\n";
1000 sub init_vars {
1001 if (defined $_repack) {
1002 $_repack = 1000 if ($_repack <= 0);
1003 $_repack_nr = $_repack;
1004 $_repack_flags ||= '-d';
1008 sub verify_remotes_sanity {
1009 return unless -d $ENV{GIT_DIR};
1010 my %seen;
1011 foreach (command(qw/config -l/)) {
1012 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1013 if ($seen{$1}) {
1014 die "Remote ref refs/remote/$1 is tracked by",
1015 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1016 "Please resolve this ambiguity in ",
1017 "your git configuration file before ",
1018 "continuing\n";
1020 $seen{$1} = $_;
1025 # we allow more chars than remotes2config.sh...
1026 sub sanitize_remote_name {
1027 my ($name) = @_;
1028 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1029 $name;
1032 sub find_existing_remote {
1033 my ($url, $remotes) = @_;
1034 return undef if $no_reuse_existing;
1035 my $existing;
1036 foreach my $repo_id (keys %$remotes) {
1037 my $u = $remotes->{$repo_id}->{url} or next;
1038 next if $u ne $url;
1039 $existing = $repo_id;
1040 last;
1042 $existing;
1045 sub init_remote_config {
1046 my ($self, $url, $no_write) = @_;
1047 $url =~ s!/+$!!; # strip trailing slash
1048 my $r = read_all_remotes();
1049 my $existing = find_existing_remote($url, $r);
1050 if ($existing) {
1051 unless ($no_write) {
1052 print STDERR "Using existing ",
1053 "[svn-remote \"$existing\"]\n";
1055 $self->{repo_id} = $existing;
1056 } elsif ($_minimize_url) {
1057 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1058 $existing = find_existing_remote($min_url, $r);
1059 if ($existing) {
1060 unless ($no_write) {
1061 print STDERR "Using existing ",
1062 "[svn-remote \"$existing\"]\n";
1064 $self->{repo_id} = $existing;
1066 if ($min_url ne $url) {
1067 unless ($no_write) {
1068 print STDERR "Using higher level of URL: ",
1069 "$url => $min_url\n";
1071 my $old_path = $self->{path};
1072 $self->{path} = $url;
1073 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1074 if (length $old_path) {
1075 $self->{path} .= "/$old_path";
1077 $url = $min_url;
1080 my $orig_url;
1081 if (!$existing) {
1082 # verify that we aren't overwriting anything:
1083 $orig_url = eval {
1084 command_oneline('config', '--get',
1085 "svn-remote.$self->{repo_id}.url")
1087 if ($orig_url && ($orig_url ne $url)) {
1088 die "svn-remote.$self->{repo_id}.url already set: ",
1089 "$orig_url\nwanted to set to: $url\n";
1092 my ($xrepo_id, $xpath) = find_ref($self->refname);
1093 if (defined $xpath) {
1094 die "svn-remote.$xrepo_id.fetch already set to track ",
1095 "$xpath:refs/remotes/", $self->refname, "\n";
1097 unless ($no_write) {
1098 command_noisy('config',
1099 "svn-remote.$self->{repo_id}.url", $url);
1100 command_noisy('config', '--add',
1101 "svn-remote.$self->{repo_id}.fetch",
1102 "$self->{path}:".$self->refname);
1104 $self->{url} = $url;
1107 sub find_by_url { # repos_root and, path are optional
1108 my ($class, $full_url, $repos_root, $path) = @_;
1110 return undef unless defined $full_url;
1111 remove_username($full_url);
1112 remove_username($repos_root) if defined $repos_root;
1113 my $remotes = read_all_remotes();
1114 if (defined $full_url && defined $repos_root && !defined $path) {
1115 $path = $full_url;
1116 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1118 foreach my $repo_id (keys %$remotes) {
1119 my $u = $remotes->{$repo_id}->{url} or next;
1120 remove_username($u);
1121 next if defined $repos_root && $repos_root ne $u;
1123 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1124 foreach (qw/branches tags/) {
1125 resolve_local_globs($u, $fetch,
1126 $remotes->{$repo_id}->{$_});
1128 my $p = $path;
1129 unless (defined $p) {
1130 $p = $full_url;
1131 $p =~ s#^\Q$u\E(?:/|$)## or next;
1133 foreach my $f (keys %$fetch) {
1134 next if $f ne $p;
1135 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1138 undef;
1141 sub init {
1142 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1143 my $self = _new($class, $repo_id, $ref_id, $path);
1144 if (defined $url) {
1145 $self->init_remote_config($url, $no_write);
1147 $self;
1150 sub find_ref {
1151 my ($ref_id) = @_;
1152 foreach (command(qw/config -l/)) {
1153 next unless m!^svn-remote\.(.+)\.fetch=
1154 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1155 my ($repo_id, $path, $ref) = ($1, $2, $3);
1156 if ($ref eq $ref_id) {
1157 $path = '' if ($path =~ m#^\./?#);
1158 return ($repo_id, $path);
1161 (undef, undef, undef);
1164 sub new {
1165 my ($class, $ref_id, $repo_id, $path) = @_;
1166 if (defined $ref_id && !defined $repo_id && !defined $path) {
1167 ($repo_id, $path) = find_ref($ref_id);
1168 if (!defined $repo_id) {
1169 die "Could not find a \"svn-remote.*.fetch\" key ",
1170 "in the repository configuration matching: ",
1171 "refs/remotes/$ref_id\n";
1174 my $self = _new($class, $repo_id, $ref_id, $path);
1175 if (!defined $self->{path} || !length $self->{path}) {
1176 my $fetch = command_oneline('config', '--get',
1177 "svn-remote.$repo_id.fetch",
1178 ":refs/remotes/$ref_id\$") or
1179 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1180 "\":refs/remotes/$ref_id\$\" in config\n";
1181 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1183 $self->{url} = command_oneline('config', '--get',
1184 "svn-remote.$repo_id.url") or
1185 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1186 $self->rebuild;
1187 $self;
1190 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1192 sub svm_uuid {
1193 my ($self) = @_;
1194 return $self->{svm}->{uuid} if $self->svm;
1195 $self->ra;
1196 unless ($self->{svm}) {
1197 die "SVM UUID not cached, and reading remotely failed\n";
1199 $self->{svm}->{uuid};
1202 sub svm {
1203 my ($self) = @_;
1204 return $self->{svm} if $self->{svm};
1205 my $svm;
1206 # see if we have it in our config, first:
1207 eval {
1208 my $section = "svn-remote.$self->{repo_id}";
1209 $svm = {
1210 source => tmp_config('--get', "$section.svm-source"),
1211 uuid => tmp_config('--get', "$section.svm-uuid"),
1212 replace => tmp_config('--get', "$section.svm-replace"),
1215 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1216 $self->{svm} = $svm;
1218 $self->{svm};
1221 sub _set_svm_vars {
1222 my ($self, $ra) = @_;
1223 return $ra if $self->svm;
1225 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1226 "(svm:source, svm:uuid) ",
1227 "from the following URLs:\n" );
1228 sub read_svm_props {
1229 my ($self, $ra, $path, $r) = @_;
1230 my $props = ($ra->get_dir($path, $r))[2];
1231 my $src = $props->{'svm:source'};
1232 my $uuid = $props->{'svm:uuid'};
1233 return undef if (!$src || !$uuid);
1235 chomp($src, $uuid);
1237 $uuid =~ m{^[0-9a-f\-]{30,}$}
1238 or die "doesn't look right - svm:uuid is '$uuid'\n";
1240 # the '!' is used to mark the repos_root!/relative/path
1241 $src =~ s{/?!/?}{/};
1242 $src =~ s{/+$}{}; # no trailing slashes please
1243 # username is of no interest
1244 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1246 my $replace = $ra->{url};
1247 $replace .= "/$path" if length $path;
1249 my $section = "svn-remote.$self->{repo_id}";
1250 tmp_config("$section.svm-source", $src);
1251 tmp_config("$section.svm-replace", $replace);
1252 tmp_config("$section.svm-uuid", $uuid);
1253 $self->{svm} = {
1254 source => $src,
1255 uuid => $uuid,
1256 replace => $replace
1260 my $r = $ra->get_latest_revnum;
1261 my $path = $self->{path};
1262 my %tried;
1263 while (length $path) {
1264 unless ($tried{"$self->{url}/$path"}) {
1265 return $ra if $self->read_svm_props($ra, $path, $r);
1266 $tried{"$self->{url}/$path"} = 1;
1268 $path =~ s#/?[^/]+$##;
1270 die "Path: '$path' should be ''\n" if $path ne '';
1271 return $ra if $self->read_svm_props($ra, $path, $r);
1272 $tried{"$self->{url}/$path"} = 1;
1274 if ($ra->{repos_root} eq $self->{url}) {
1275 die @err, (map { " $_\n" } keys %tried), "\n";
1278 # nope, make sure we're connected to the repository root:
1279 my $ok;
1280 my @tried_b;
1281 $path = $ra->{svn_path};
1282 $ra = Git::SVN::Ra->new($ra->{repos_root});
1283 while (length $path) {
1284 unless ($tried{"$ra->{url}/$path"}) {
1285 $ok = $self->read_svm_props($ra, $path, $r);
1286 last if $ok;
1287 $tried{"$ra->{url}/$path"} = 1;
1289 $path =~ s#/?[^/]+$##;
1291 die "Path: '$path' should be ''\n" if $path ne '';
1292 $ok ||= $self->read_svm_props($ra, $path, $r);
1293 $tried{"$ra->{url}/$path"} = 1;
1294 if (!$ok) {
1295 die @err, (map { " $_\n" } keys %tried), "\n";
1297 Git::SVN::Ra->new($self->{url});
1300 sub svnsync {
1301 my ($self) = @_;
1302 return $self->{svnsync} if $self->{svnsync};
1304 if ($self->no_metadata) {
1305 die "Can't have both 'noMetadata' and ",
1306 "'useSvnsyncProps' options set!\n";
1308 if ($self->rewrite_root) {
1309 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1310 "options set!\n";
1313 my $svnsync;
1314 # see if we have it in our config, first:
1315 eval {
1316 my $section = "svn-remote.$self->{repo_id}";
1317 $svnsync = {
1318 url => tmp_config('--get', "$section.svnsync-url"),
1319 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1322 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1323 return $self->{svnsync} = $svnsync;
1326 my $err = "useSvnsyncProps set, but failed to read " .
1327 "svnsync property: svn:sync-from-";
1328 my $rp = $self->ra->rev_proplist(0);
1330 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1331 $url =~ m{^[a-z\+]+://} or
1332 die "doesn't look right - svn:sync-from-url is '$url'\n";
1334 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1335 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1336 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1338 my $section = "svn-remote.$self->{repo_id}";
1339 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1340 tmp_config('--add', "$section.svnsync-url", $url);
1341 return $self->{svnsync} = { url => $url, uuid => $uuid };
1344 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1345 # remote lookup (useful for 'git svn log').
1346 sub ra_uuid {
1347 my ($self) = @_;
1348 unless ($self->{ra_uuid}) {
1349 my $key = "svn-remote.$self->{repo_id}.uuid";
1350 my $uuid = eval { tmp_config('--get', $key) };
1351 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1352 $self->{ra_uuid} = $uuid;
1353 } else {
1354 die "ra_uuid called without URL\n" unless $self->{url};
1355 $self->{ra_uuid} = $self->ra->get_uuid;
1356 tmp_config('--add', $key, $self->{ra_uuid});
1359 $self->{ra_uuid};
1362 sub ra {
1363 my ($self) = shift;
1364 my $ra = Git::SVN::Ra->new($self->{url});
1365 if ($self->use_svm_props && !$self->{svm}) {
1366 if ($self->no_metadata) {
1367 die "Can't have both 'noMetadata' and ",
1368 "'useSvmProps' options set!\n";
1369 } elsif ($self->use_svnsync_props) {
1370 die "Can't have both 'useSvnsyncProps' and ",
1371 "'useSvmProps' options set!\n";
1373 $ra = $self->_set_svm_vars($ra);
1374 $self->{-want_revprops} = 1;
1376 $ra;
1379 sub rel_path {
1380 my ($self) = @_;
1381 my $repos_root = $self->ra->{repos_root};
1382 return $self->{path} if ($self->{url} eq $repos_root);
1383 my $url = $self->{url} .
1384 (length $self->{path} ? "/$self->{path}" : $self->{path});
1385 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1386 $url;
1389 sub traverse_ignore {
1390 my ($self, $fh, $path, $r) = @_;
1391 $path =~ s#^/+##g;
1392 my $ra = $self->ra;
1393 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1394 my $p = $path;
1395 $p =~ s#^\Q$self->{path}\E(/|$)##;
1396 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1397 if (my $s = $props->{'svn:ignore'}) {
1398 $s =~ s/[\r\n]+/\n/g;
1399 chomp $s;
1400 if (length $p == 0) {
1401 $s =~ s#\n#\n/$p#g;
1402 print $fh "/$s\n";
1403 } else {
1404 $s =~ s#\n#\n/$p/#g;
1405 print $fh "/$p/$s\n";
1408 foreach (sort keys %$dirent) {
1409 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1410 $self->traverse_ignore($fh, "$path/$_", $r);
1414 sub last_rev { ($_[0]->last_rev_commit)[0] }
1415 sub last_commit { ($_[0]->last_rev_commit)[1] }
1417 # returns the newest SVN revision number and newest commit SHA1
1418 sub last_rev_commit {
1419 my ($self) = @_;
1420 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1421 return ($self->{last_rev}, $self->{last_commit});
1423 my $c = ::verify_ref($self->refname.'^0');
1424 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1425 my $rev = (::cmt_metadata($c))[1];
1426 if (defined $rev) {
1427 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1428 return ($rev, $c);
1431 my $db_path = $self->db_path;
1432 unless (-e $db_path) {
1433 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1434 return (undef, undef);
1436 my $offset = -41; # from tail
1437 my $rl;
1438 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1439 sysseek($fh, $offset, 2); # don't care for errors
1440 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1441 chomp $rl;
1442 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1443 $offset -= 41;
1444 sysseek($fh, $offset, 2); # don't care for errors
1445 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1446 chomp $rl;
1448 if ($c && $c ne $rl) {
1449 die "$db_path and ", $self->refname,
1450 " inconsistent!:\n$c != $rl\n";
1452 my $rev = sysseek($fh, 0, 1) or croak $!;
1453 $rev = ($rev - 41) / 41;
1454 close $fh or croak $!;
1455 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1456 return ($rev, $c);
1459 sub get_fetch_range {
1460 my ($self, $min, $max) = @_;
1461 $max ||= $self->ra->get_latest_revnum;
1462 $min ||= $self->rev_db_max;
1463 (++$min, $max);
1466 sub tmp_config {
1467 my (@args) = @_;
1468 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1469 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1470 if (! -f $config && -f $old_def_config) {
1471 rename $old_def_config, $config or
1472 die "Failed rename $old_def_config => $config: $!\n";
1474 my $old_config = $ENV{GIT_CONFIG};
1475 $ENV{GIT_CONFIG} = $config;
1476 $@ = undef;
1477 my @ret = eval {
1478 unless (-f $config) {
1479 mkfile($config);
1480 open my $fh, '>', $config or
1481 die "Can't open $config: $!\n";
1482 print $fh "; This file is used internally by ",
1483 "git-svn\n" or die
1484 "Couldn't write to $config: $!\n";
1485 print $fh "; You should not have to edit it\n" or
1486 die "Couldn't write to $config: $!\n";
1487 close $fh or die "Couldn't close $config: $!\n";
1489 command('config', @args);
1491 my $err = $@;
1492 if (defined $old_config) {
1493 $ENV{GIT_CONFIG} = $old_config;
1494 } else {
1495 delete $ENV{GIT_CONFIG};
1497 die $err if $err;
1498 wantarray ? @ret : $ret[0];
1501 sub tmp_index_do {
1502 my ($self, $sub) = @_;
1503 my $old_index = $ENV{GIT_INDEX_FILE};
1504 $ENV{GIT_INDEX_FILE} = $self->{index};
1505 $@ = undef;
1506 my @ret = eval {
1507 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1508 mkpath([$dir]) unless -d $dir;
1509 &$sub;
1511 my $err = $@;
1512 if (defined $old_index) {
1513 $ENV{GIT_INDEX_FILE} = $old_index;
1514 } else {
1515 delete $ENV{GIT_INDEX_FILE};
1517 die $err if $err;
1518 wantarray ? @ret : $ret[0];
1521 sub assert_index_clean {
1522 my ($self, $treeish) = @_;
1524 $self->tmp_index_do(sub {
1525 command_noisy('read-tree', $treeish) unless -e $self->{index};
1526 my $x = command_oneline('write-tree');
1527 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1528 /^tree ($::sha1)/mo);
1529 return if $y eq $x;
1531 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1532 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1533 command_noisy('read-tree', $treeish);
1534 $x = command_oneline('write-tree');
1535 if ($y ne $x) {
1536 ::fatal "trees ($treeish) $y != $x\n",
1537 "Something is seriously wrong...\n";
1542 sub get_commit_parents {
1543 my ($self, $log_entry) = @_;
1544 my (%seen, @ret, @tmp);
1545 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1546 if (my $ip = $self->{inject_parents}) {
1547 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1548 push @tmp, $commit;
1551 if (my $cur = ::verify_ref($self->refname.'^0')) {
1552 push @tmp, $cur;
1554 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1555 while (my $p = shift @tmp) {
1556 next if $seen{$p};
1557 $seen{$p} = 1;
1558 push @ret, $p;
1559 # MAXPARENT is defined to 16 in commit-tree.c:
1560 last if @ret >= 16;
1562 if (@tmp) {
1563 die "r$log_entry->{revision}: No room for parents:\n\t",
1564 join("\n\t", @tmp), "\n";
1566 @ret;
1569 sub rewrite_root {
1570 my ($self) = @_;
1571 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1572 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1573 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1574 if ($rwr) {
1575 $rwr =~ s#/+$##;
1576 if ($rwr !~ m#^[a-z\+]+://#) {
1577 die "$rwr is not a valid URL (key: $k)\n";
1580 $self->{-rewrite_root} = $rwr;
1583 sub metadata_url {
1584 my ($self) = @_;
1585 ($self->rewrite_root || $self->{url}) .
1586 (length $self->{path} ? '/' . $self->{path} : '');
1589 sub full_url {
1590 my ($self) = @_;
1591 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1594 sub do_git_commit {
1595 my ($self, $log_entry) = @_;
1596 my $lr = $self->last_rev;
1597 if (defined $lr && $lr >= $log_entry->{revision}) {
1598 die "Last fetched revision of ", $self->refname,
1599 " was r$lr, but we are about to fetch: ",
1600 "r$log_entry->{revision}!\n";
1602 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1603 croak "$log_entry->{revision} = $c already exists! ",
1604 "Why are we refetching it?\n";
1606 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1607 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1608 $log_entry->{email};
1609 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1611 my $tree = $log_entry->{tree};
1612 if (!defined $tree) {
1613 $tree = $self->tmp_index_do(sub {
1614 command_oneline('write-tree') });
1616 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1618 my @exec = ('git-commit-tree', $tree);
1619 foreach ($self->get_commit_parents($log_entry)) {
1620 push @exec, '-p', $_;
1622 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1623 or croak $!;
1624 print $msg_fh $log_entry->{log} or croak $!;
1625 unless ($self->no_metadata) {
1626 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1627 or croak $!;
1629 $msg_fh->flush == 0 or croak $!;
1630 close $msg_fh or croak $!;
1631 chomp(my $commit = do { local $/; <$out_fh> });
1632 close $out_fh or croak $!;
1633 waitpid $pid, 0;
1634 croak $? if $?;
1635 if ($commit !~ /^$::sha1$/o) {
1636 die "Failed to commit, invalid sha1: $commit\n";
1639 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1641 $self->{last_rev} = $log_entry->{revision};
1642 $self->{last_commit} = $commit;
1643 print "r$log_entry->{revision}";
1644 if (defined $log_entry->{svm_revision}) {
1645 print " (\@$log_entry->{svm_revision})";
1646 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1647 0, $self->svm_uuid);
1649 print " = $commit ($self->{ref_id})\n";
1650 if (defined $_repack && (--$_repack_nr == 0)) {
1651 $_repack_nr = $_repack;
1652 # repack doesn't use any arguments with spaces in them, does it?
1653 print "Running git repack $_repack_flags ...\n";
1654 command_noisy('repack', split(/\s+/, $_repack_flags));
1655 print "Done repacking\n";
1657 return $commit;
1660 sub match_paths {
1661 my ($self, $paths, $r) = @_;
1662 return 1 if $self->{path} eq '';
1663 if (my $path = $paths->{"/$self->{path}"}) {
1664 return ($path->{action} eq 'D') ? 0 : 1;
1666 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1667 if (grep /$self->{path_regex}/, keys %$paths) {
1668 return 1;
1670 my $c = '';
1671 foreach (split m#/#, $self->{path}) {
1672 $c .= "/$_";
1673 next unless ($paths->{$c} &&
1674 ($paths->{$c}->{action} =~ /^[AR]$/));
1675 if ($self->ra->check_path($self->{path}, $r) ==
1676 $SVN::Node::dir) {
1677 return 1;
1680 return 0;
1683 sub find_parent_branch {
1684 my ($self, $paths, $rev) = @_;
1685 return undef unless $self->follow_parent;
1686 unless (defined $paths) {
1687 my $err_handler = $SVN::Error::handler;
1688 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1689 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1690 $paths =
1691 Git::SVN::Ra::dup_changed_paths($_[0]) });
1692 $SVN::Error::handler = $err_handler;
1694 return undef unless defined $paths;
1696 # look for a parent from another branch:
1697 my @b_path_components = split m#/#, $self->rel_path;
1698 my @a_path_components;
1699 my $i;
1700 while (@b_path_components) {
1701 $i = $paths->{'/'.join('/', @b_path_components)};
1702 last if $i && defined $i->{copyfrom_path};
1703 unshift(@a_path_components, pop(@b_path_components));
1705 return undef unless defined $i && defined $i->{copyfrom_path};
1706 my $branch_from = $i->{copyfrom_path};
1707 if (@a_path_components) {
1708 print STDERR "branch_from: $branch_from => ";
1709 $branch_from .= '/'.join('/', @a_path_components);
1710 print STDERR $branch_from, "\n";
1712 my $r = $i->{copyfrom_rev};
1713 my $repos_root = $self->ra->{repos_root};
1714 my $url = $self->ra->{url};
1715 my $new_url = $repos_root . $branch_from;
1716 print STDERR "Found possible branch point: ",
1717 "$new_url => ", $self->full_url, ", $r\n";
1718 $branch_from =~ s#^/##;
1719 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1720 unless ($gs) {
1721 my $ref_id = $self->{ref_id};
1722 $ref_id =~ s/\@\d+$//;
1723 $ref_id .= "\@$r";
1724 # just grow a tail if we're not unique enough :x
1725 $ref_id .= '-' while find_ref($ref_id);
1726 print STDERR "Initializing parent: $ref_id\n";
1727 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1729 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1730 if (!defined $r0 || !defined $parent) {
1731 my ($base, $head) = parse_revision_argument(0, $r);
1732 if ($base <= $r) {
1733 $gs->fetch($base, $r);
1735 ($r0, $parent) = $gs->last_rev_commit;
1737 if (defined $r0 && defined $parent) {
1738 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1739 my $ed;
1740 if ($self->ra->can_do_switch) {
1741 $self->assert_index_clean($parent);
1742 print STDERR "Following parent with do_switch\n";
1743 # do_switch works with svn/trunk >= r22312, but that
1744 # is not included with SVN 1.4.3 (the latest version
1745 # at the moment), so we can't rely on it
1746 $self->{last_commit} = $parent;
1747 $ed = SVN::Git::Fetcher->new($self);
1748 $gs->ra->gs_do_switch($r0, $rev, $gs,
1749 $self->full_url, $ed)
1750 or die "SVN connection failed somewhere...\n";
1751 } else {
1752 print STDERR "Following parent with do_update\n";
1753 $ed = SVN::Git::Fetcher->new($self);
1754 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1755 or die "SVN connection failed somewhere...\n";
1757 print STDERR "Successfully followed parent\n";
1758 return $self->make_log_entry($rev, [$parent], $ed);
1760 return undef;
1763 sub do_fetch {
1764 my ($self, $paths, $rev) = @_;
1765 my $ed;
1766 my ($last_rev, @parents);
1767 if (my $lc = $self->last_commit) {
1768 # we can have a branch that was deleted, then re-added
1769 # under the same name but copied from another path, in
1770 # which case we'll have multiple parents (we don't
1771 # want to break the original ref, nor lose copypath info):
1772 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1773 push @{$log_entry->{parents}}, $lc;
1774 return $log_entry;
1776 $ed = SVN::Git::Fetcher->new($self);
1777 $last_rev = $self->{last_rev};
1778 $ed->{c} = $lc;
1779 @parents = ($lc);
1780 } else {
1781 $last_rev = $rev;
1782 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1783 return $log_entry;
1785 $ed = SVN::Git::Fetcher->new($self);
1787 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1788 die "SVN connection failed somewhere...\n";
1790 $self->make_log_entry($rev, \@parents, $ed);
1793 sub get_untracked {
1794 my ($self, $ed) = @_;
1795 my @out;
1796 my $h = $ed->{empty};
1797 foreach (sort keys %$h) {
1798 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1799 push @out, " $act: " . uri_encode($_);
1800 warn "W: $act: $_\n";
1802 foreach my $t (qw/dir_prop file_prop/) {
1803 $h = $ed->{$t} or next;
1804 foreach my $path (sort keys %$h) {
1805 my $ppath = $path eq '' ? '.' : $path;
1806 foreach my $prop (sort keys %{$h->{$path}}) {
1807 next if $SKIP_PROP{$prop};
1808 my $v = $h->{$path}->{$prop};
1809 my $t_ppath_prop = "$t: " .
1810 uri_encode($ppath) . ' ' .
1811 uri_encode($prop);
1812 if (defined $v) {
1813 push @out, " +$t_ppath_prop " .
1814 uri_encode($v);
1815 } else {
1816 push @out, " -$t_ppath_prop";
1821 foreach my $t (qw/absent_file absent_directory/) {
1822 $h = $ed->{$t} or next;
1823 foreach my $parent (sort keys %$h) {
1824 foreach my $path (sort @{$h->{$parent}}) {
1825 push @out, " $t: " .
1826 uri_encode("$parent/$path");
1827 warn "W: $t: $parent/$path ",
1828 "Insufficient permissions?\n";
1832 \@out;
1835 sub parse_svn_date {
1836 my $date = shift || return '+0000 1970-01-01 00:00:00';
1837 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1838 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1839 croak "Unable to parse date: $date\n";
1840 "+0000 $Y-$m-$d $H:$M:$S";
1843 sub check_author {
1844 my ($author) = @_;
1845 if (!defined $author || length $author == 0) {
1846 $author = '(no author)';
1848 if (defined $::_authors && ! defined $::users{$author}) {
1849 die "Author: $author not defined in $::_authors file\n";
1851 $author;
1854 sub make_log_entry {
1855 my ($self, $rev, $parents, $ed) = @_;
1856 my $untracked = $self->get_untracked($ed);
1858 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1859 print $un "r$rev\n" or croak $!;
1860 print $un $_, "\n" foreach @$untracked;
1861 my %log_entry = ( parents => $parents || [], revision => $rev,
1862 log => '');
1864 my $headrev;
1865 my $logged = delete $self->{logged_rev_props};
1866 if (!$logged || $self->{-want_revprops}) {
1867 my $rp = $self->ra->rev_proplist($rev);
1868 foreach (sort keys %$rp) {
1869 my $v = $rp->{$_};
1870 if (/^svn:(author|date|log)$/) {
1871 $log_entry{$1} = $v;
1872 } elsif ($_ eq 'svm:headrev') {
1873 $headrev = $v;
1874 } else {
1875 print $un " rev_prop: ", uri_encode($_), ' ',
1876 uri_encode($v), "\n";
1879 } else {
1880 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1882 close $un or croak $!;
1884 $log_entry{date} = parse_svn_date($log_entry{date});
1885 $log_entry{log} .= "\n";
1886 my $author = $log_entry{author} = check_author($log_entry{author});
1887 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1888 : ($author, undef);
1889 if (defined $headrev && $self->use_svm_props) {
1890 if ($self->rewrite_root) {
1891 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1892 "options set!\n";
1894 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1895 # we don't want "SVM: initializing mirror for junk" ...
1896 return undef if $r == 0;
1897 my $svm = $self->svm;
1898 if ($uuid ne $svm->{uuid}) {
1899 die "UUID mismatch on SVM path:\n",
1900 "expected: $svm->{uuid}\n",
1901 " got: $uuid\n";
1903 my $full_url = $self->full_url;
1904 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1905 die "Failed to replace '$svm->{replace}' with ",
1906 "'$svm->{source}' in $full_url\n";
1907 # throw away username for storing in records
1908 remove_username($full_url);
1909 $log_entry{metadata} = "$full_url\@$r $uuid";
1910 $log_entry{svm_revision} = $r;
1911 $email ||= "$author\@$uuid"
1912 } elsif ($self->use_svnsync_props) {
1913 my $full_url = $self->svnsync->{url};
1914 $full_url .= "/$self->{path}" if length $self->{path};
1915 remove_username($full_url);
1916 my $uuid = $self->svnsync->{uuid};
1917 $log_entry{metadata} = "$full_url\@$rev $uuid";
1918 $email ||= "$author\@$uuid"
1919 } else {
1920 my $url = $self->metadata_url;
1921 remove_username($url);
1922 $log_entry{metadata} = "$url\@$rev " .
1923 $self->ra->get_uuid;
1924 $email ||= "$author\@" . $self->ra->get_uuid;
1926 $log_entry{name} = $name;
1927 $log_entry{email} = $email;
1928 \%log_entry;
1931 sub fetch {
1932 my ($self, $min_rev, $max_rev, @parents) = @_;
1933 my ($last_rev, $last_commit) = $self->last_rev_commit;
1934 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1935 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1938 sub set_tree_cb {
1939 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1940 $self->{inject_parents} = { $rev => $tree };
1941 $self->fetch(undef, undef);
1944 sub set_tree {
1945 my ($self, $tree) = (shift, shift);
1946 my $log_entry = ::get_commit_entry($tree);
1947 unless ($self->{last_rev}) {
1948 fatal("Must have an existing revision to commit\n");
1950 my %ed_opts = ( r => $self->{last_rev},
1951 log => $log_entry->{log},
1952 ra => $self->ra,
1953 tree_a => $self->{last_commit},
1954 tree_b => $tree,
1955 editor_cb => sub {
1956 $self->set_tree_cb($log_entry, $tree, @_) },
1957 svn_path => $self->{path} );
1958 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1959 print "No changes\nr$self->{last_rev} = $tree\n";
1963 sub rebuild {
1964 my ($self) = @_;
1965 my $db_path = $self->db_path;
1966 return if (-e $db_path && ! -z $db_path);
1967 return unless ::verify_ref($self->refname.'^0');
1968 if (-f $self->{db_root}) {
1969 rename $self->{db_root}, $db_path or die
1970 "rename $self->{db_root} => $db_path failed: $!\n";
1971 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1972 symlink $base, $self->{db_root} or die
1973 "symlink $base => $self->{db_root} failed: $!\n";
1974 return;
1976 print "Rebuilding $db_path ...\n";
1977 my ($log, $ctx) = command_output_pipe("log", $self->refname);
1978 my $latest;
1979 my $full_url = $self->full_url;
1980 remove_username($full_url);
1981 my $svn_uuid;
1982 my $c;
1983 while (<$log>) {
1984 if ( m{^commit ($::sha1)$} ) {
1985 $c = $1;
1986 next;
1988 next unless s{^\s*(git-svn-id:)}{$1};
1989 my ($url, $rev, $uuid) = ::extract_metadata($_);
1990 remove_username($url);
1992 # ignore merges (from set-tree)
1993 next if (!defined $rev || !$uuid);
1995 # if we merged or otherwise started elsewhere, this is
1996 # how we break out of it
1997 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1998 ($full_url && $url && ($url ne $full_url))) {
1999 next;
2001 $latest ||= $rev;
2002 $svn_uuid ||= $uuid;
2004 $self->rev_db_set($rev, $c);
2005 print "r$rev = $c\n";
2007 command_close_pipe($log, $ctx);
2008 print "Done rebuilding $db_path\n";
2011 # rev_db:
2012 # Tie::File seems to be prone to offset errors if revisions get sparse,
2013 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2014 # one of my favorite modules is out :< Next up would be one of the DBM
2015 # modules, but I'm not sure which is most portable... So I'll just
2016 # go with something that's plain-text, but still capable of
2017 # being randomly accessed. So here's my ultra-simple fixed-width
2018 # database. All records are 40 characters + "\n", so it's easy to seek
2019 # to a revision: (41 * rev) is the byte offset.
2020 # A record of 40 0s denotes an empty revision.
2021 # And yes, it's still pretty fast (faster than Tie::File).
2022 # These files are disposable unless noMetadata or useSvmProps is set
2024 sub _rev_db_set {
2025 my ($fh, $rev, $commit) = @_;
2026 my $offset = $rev * 41;
2027 # assume that append is the common case:
2028 seek $fh, 0, 2 or croak $!;
2029 my $pos = tell $fh;
2030 if ($pos < $offset) {
2031 for (1 .. (($offset - $pos) / 41)) {
2032 print $fh (('0' x 40),"\n") or croak $!;
2035 seek $fh, $offset, 0 or croak $!;
2036 print $fh $commit,"\n" or croak $!;
2039 sub mkfile {
2040 my ($path) = @_;
2041 unless (-e $path) {
2042 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2043 mkpath([$dir]) unless -d $dir;
2044 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2045 close $fh or die "Couldn't close (create) $path: $!\n";
2049 sub rev_db_set {
2050 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2051 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2052 my $db = $self->db_path($uuid);
2053 my $db_lock = "$db.lock";
2054 my $sig;
2055 if ($update_ref) {
2056 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2057 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2059 mkfile($db);
2061 $LOCKFILES{$db_lock} = 1;
2062 my $sync;
2063 # both of these options make our .rev_db file very, very important
2064 # and we can't afford to lose it because rebuild() won't work
2065 if ($self->use_svm_props || $self->no_metadata) {
2066 $sync = 1;
2067 copy($db, $db_lock) or die "rev_db_set(@_): ",
2068 "Failed to copy: ",
2069 "$db => $db_lock ($!)\n";
2070 } else {
2071 rename $db, $db_lock or die "rev_db_set(@_): ",
2072 "Failed to rename: ",
2073 "$db => $db_lock ($!)\n";
2075 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2076 _rev_db_set($fh, $rev, $commit);
2077 if ($sync) {
2078 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2079 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2081 close $fh or croak $!;
2082 if ($update_ref) {
2083 $_head = $self;
2084 command_noisy('update-ref', '-m', "r$rev",
2085 $self->refname, $commit);
2087 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2088 "$db_lock => $db ($!)\n";
2089 delete $LOCKFILES{$db_lock};
2090 if ($update_ref) {
2091 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2092 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2093 kill $sig, $$ if defined $sig;
2097 sub rev_db_max {
2098 my ($self) = @_;
2099 $self->rebuild;
2100 my $db_path = $self->db_path;
2101 my @stat = stat $db_path or return 0;
2102 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2103 my $max = $stat[7] / 41;
2104 (($max > 0) ? $max - 1 : 0);
2107 sub rev_db_get {
2108 my ($self, $rev, $uuid) = @_;
2109 my $ret;
2110 my $offset = $rev * 41;
2111 my $db_path = $self->db_path($uuid);
2112 return undef unless -e $db_path;
2113 open my $fh, '<', $db_path or croak $!;
2114 if (sysseek($fh, $offset, 0) == $offset) {
2115 my $read = sysread($fh, $ret, 40);
2116 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2118 close $fh or croak $!;
2119 $ret;
2122 sub find_rev_before {
2123 my ($self, $rev, $eq_ok) = @_;
2124 --$rev unless $eq_ok;
2125 while ($rev > 0) {
2126 if (my $c = $self->rev_db_get($rev)) {
2127 return ($rev, $c);
2129 --$rev;
2131 return (undef, undef);
2134 sub _new {
2135 my ($class, $repo_id, $ref_id, $path) = @_;
2136 unless (defined $repo_id && length $repo_id) {
2137 $repo_id = $Git::SVN::default_repo_id;
2139 unless (defined $ref_id && length $ref_id) {
2140 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2142 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2143 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2144 $_[3] = $path = '' unless (defined $path);
2145 mkpath(["$ENV{GIT_DIR}/svn"]);
2146 bless {
2147 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2148 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2149 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2152 sub db_path {
2153 my ($self, $uuid) = @_;
2154 $uuid ||= $self->ra_uuid;
2155 "$self->{db_root}.$uuid";
2158 sub uri_encode {
2159 my ($f) = @_;
2160 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2164 sub remove_username {
2165 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2168 package Git::SVN::Prompt;
2169 use strict;
2170 use warnings;
2171 require SVN::Core;
2172 use vars qw/$_no_auth_cache $_username/;
2174 sub simple {
2175 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2176 $may_save = undef if $_no_auth_cache;
2177 $default_username = $_username if defined $_username;
2178 if (defined $default_username && length $default_username) {
2179 if (defined $realm && length $realm) {
2180 print STDERR "Authentication realm: $realm\n";
2181 STDERR->flush;
2183 $cred->username($default_username);
2184 } else {
2185 username($cred, $realm, $may_save, $pool);
2187 $cred->password(_read_password("Password for '" .
2188 $cred->username . "': ", $realm));
2189 $cred->may_save($may_save);
2190 $SVN::_Core::SVN_NO_ERROR;
2193 sub ssl_server_trust {
2194 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2195 $may_save = undef if $_no_auth_cache;
2196 print STDERR "Error validating server certificate for '$realm':\n";
2197 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2198 print STDERR " - The certificate is not issued by a trusted ",
2199 "authority. Use the\n",
2200 " fingerprint to validate the certificate manually!\n";
2202 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2203 print STDERR " - The certificate hostname does not match.\n";
2205 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2206 print STDERR " - The certificate is not yet valid.\n";
2208 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2209 print STDERR " - The certificate has expired.\n";
2211 if ($failures & $SVN::Auth::SSL::OTHER) {
2212 print STDERR " - The certificate has an unknown error.\n";
2214 printf STDERR
2215 "Certificate information:\n".
2216 " - Hostname: %s\n".
2217 " - Valid: from %s until %s\n".
2218 " - Issuer: %s\n".
2219 " - Fingerprint: %s\n",
2220 map $cert_info->$_, qw(hostname valid_from valid_until
2221 issuer_dname fingerprint);
2222 my $choice;
2223 prompt:
2224 print STDERR $may_save ?
2225 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2226 "(R)eject or accept (t)emporarily? ";
2227 STDERR->flush;
2228 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2229 if ($choice =~ /^t$/i) {
2230 $cred->may_save(undef);
2231 } elsif ($choice =~ /^r$/i) {
2232 return -1;
2233 } elsif ($may_save && $choice =~ /^p$/i) {
2234 $cred->may_save($may_save);
2235 } else {
2236 goto prompt;
2238 $cred->accepted_failures($failures);
2239 $SVN::_Core::SVN_NO_ERROR;
2242 sub ssl_client_cert {
2243 my ($cred, $realm, $may_save, $pool) = @_;
2244 $may_save = undef if $_no_auth_cache;
2245 print STDERR "Client certificate filename: ";
2246 STDERR->flush;
2247 chomp(my $filename = <STDIN>);
2248 $cred->cert_file($filename);
2249 $cred->may_save($may_save);
2250 $SVN::_Core::SVN_NO_ERROR;
2253 sub ssl_client_cert_pw {
2254 my ($cred, $realm, $may_save, $pool) = @_;
2255 $may_save = undef if $_no_auth_cache;
2256 $cred->password(_read_password("Password: ", $realm));
2257 $cred->may_save($may_save);
2258 $SVN::_Core::SVN_NO_ERROR;
2261 sub username {
2262 my ($cred, $realm, $may_save, $pool) = @_;
2263 $may_save = undef if $_no_auth_cache;
2264 if (defined $realm && length $realm) {
2265 print STDERR "Authentication realm: $realm\n";
2267 my $username;
2268 if (defined $_username) {
2269 $username = $_username;
2270 } else {
2271 print STDERR "Username: ";
2272 STDERR->flush;
2273 chomp($username = <STDIN>);
2275 $cred->username($username);
2276 $cred->may_save($may_save);
2277 $SVN::_Core::SVN_NO_ERROR;
2280 sub _read_password {
2281 my ($prompt, $realm) = @_;
2282 print STDERR $prompt;
2283 STDERR->flush;
2284 require Term::ReadKey;
2285 Term::ReadKey::ReadMode('noecho');
2286 my $password = '';
2287 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2288 last if $key =~ /[\012\015]/; # \n\r
2289 $password .= $key;
2291 Term::ReadKey::ReadMode('restore');
2292 print STDERR "\n";
2293 STDERR->flush;
2294 $password;
2297 package main;
2300 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2301 $SVN::Node::dir.$SVN::Node::unknown.
2302 $SVN::Node::none.$SVN::Node::file.
2303 $SVN::Node::dir.$SVN::Node::unknown.
2304 $SVN::Auth::SSL::CNMISMATCH.
2305 $SVN::Auth::SSL::NOTYETVALID.
2306 $SVN::Auth::SSL::EXPIRED.
2307 $SVN::Auth::SSL::UNKNOWNCA.
2308 $SVN::Auth::SSL::OTHER;
2311 package SVN::Git::Fetcher;
2312 use vars qw/@ISA/;
2313 use strict;
2314 use warnings;
2315 use Carp qw/croak/;
2316 use IO::File qw//;
2317 use Digest::MD5;
2319 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2320 sub new {
2321 my ($class, $git_svn) = @_;
2322 my $self = SVN::Delta::Editor->new;
2323 bless $self, $class;
2324 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2325 $self->{empty} = {};
2326 $self->{dir_prop} = {};
2327 $self->{file_prop} = {};
2328 $self->{absent_dir} = {};
2329 $self->{absent_file} = {};
2330 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2331 $self;
2334 sub set_path_strip {
2335 my ($self, $path) = @_;
2336 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2339 sub open_root {
2340 { path => '' };
2343 sub open_directory {
2344 my ($self, $path, $pb, $rev) = @_;
2345 { path => $path };
2348 sub git_path {
2349 my ($self, $path) = @_;
2350 if ($self->{path_strip}) {
2351 $path =~ s!$self->{path_strip}!! or
2352 die "Failed to strip path '$path' ($self->{path_strip})\n";
2354 $path;
2357 sub delete_entry {
2358 my ($self, $path, $rev, $pb) = @_;
2360 my $gpath = $self->git_path($path);
2361 return undef if ($gpath eq '');
2363 # remove entire directories.
2364 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2365 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2366 -r --name-only -z/,
2367 $self->{c}, '--', $gpath);
2368 local $/ = "\0";
2369 while (<$ls>) {
2370 chomp;
2371 $self->{gii}->remove($_);
2372 print "\tD\t$_\n" unless $::_q;
2374 print "\tD\t$gpath/\n" unless $::_q;
2375 command_close_pipe($ls, $ctx);
2376 $self->{empty}->{$path} = 0
2377 } else {
2378 $self->{gii}->remove($gpath);
2379 print "\tD\t$gpath\n" unless $::_q;
2381 undef;
2384 sub open_file {
2385 my ($self, $path, $pb, $rev) = @_;
2386 my $gpath = $self->git_path($path);
2387 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2388 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2389 unless (defined $mode && defined $blob) {
2390 die "$path was not found in commit $self->{c} (r$rev)\n";
2392 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2393 pool => SVN::Pool->new, action => 'M' };
2396 sub add_file {
2397 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2398 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2399 delete $self->{empty}->{$dir};
2400 { path => $path, mode_a => 100644, mode_b => 100644,
2401 pool => SVN::Pool->new, action => 'A' };
2404 sub add_directory {
2405 my ($self, $path, $cp_path, $cp_rev) = @_;
2406 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2407 delete $self->{empty}->{$dir};
2408 $self->{empty}->{$path} = 1;
2409 { path => $path };
2412 sub change_dir_prop {
2413 my ($self, $db, $prop, $value) = @_;
2414 $self->{dir_prop}->{$db->{path}} ||= {};
2415 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2416 undef;
2419 sub absent_directory {
2420 my ($self, $path, $pb) = @_;
2421 $self->{absent_dir}->{$pb->{path}} ||= [];
2422 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2423 undef;
2426 sub absent_file {
2427 my ($self, $path, $pb) = @_;
2428 $self->{absent_file}->{$pb->{path}} ||= [];
2429 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2430 undef;
2433 sub change_file_prop {
2434 my ($self, $fb, $prop, $value) = @_;
2435 if ($prop eq 'svn:executable') {
2436 if ($fb->{mode_b} != 120000) {
2437 $fb->{mode_b} = defined $value ? 100755 : 100644;
2439 } elsif ($prop eq 'svn:special') {
2440 $fb->{mode_b} = defined $value ? 120000 : 100644;
2441 } else {
2442 $self->{file_prop}->{$fb->{path}} ||= {};
2443 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2445 undef;
2448 sub apply_textdelta {
2449 my ($self, $fb, $exp) = @_;
2450 my $fh = IO::File->new_tmpfile;
2451 $fh->autoflush(1);
2452 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2453 # (but $base does not,) so dup() it for reading in close_file
2454 open my $dup, '<&', $fh or croak $!;
2455 my $base = IO::File->new_tmpfile;
2456 $base->autoflush(1);
2457 if ($fb->{blob}) {
2458 defined (my $pid = fork) or croak $!;
2459 if (!$pid) {
2460 open STDOUT, '>&', $base or croak $!;
2461 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2462 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2464 waitpid $pid, 0;
2465 croak $? if $?;
2467 if (defined $exp) {
2468 seek $base, 0, 0 or croak $!;
2469 my $md5 = Digest::MD5->new;
2470 $md5->addfile($base);
2471 my $got = $md5->hexdigest;
2472 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2473 "expected: $exp\n",
2474 " got: $got\n" if ($got ne $exp);
2477 seek $base, 0, 0 or croak $!;
2478 $fb->{fh} = $dup;
2479 $fb->{base} = $base;
2480 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2483 sub close_file {
2484 my ($self, $fb, $exp) = @_;
2485 my $hash;
2486 my $path = $self->git_path($fb->{path});
2487 if (my $fh = $fb->{fh}) {
2488 if (defined $exp) {
2489 seek($fh, 0, 0) or croak $!;
2490 my $md5 = Digest::MD5->new;
2491 $md5->addfile($fh);
2492 my $got = $md5->hexdigest;
2493 if ($got ne $exp) {
2494 die "Checksum mismatch: $path\n",
2495 "expected: $exp\n got: $got\n";
2498 sysseek($fh, 0, 0) or croak $!;
2499 if ($fb->{mode_b} == 120000) {
2500 sysread($fh, my $buf, 5) == 5 or croak $!;
2501 $buf eq 'link ' or die "$path has mode 120000",
2502 "but is not a link\n";
2504 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2505 if (!$pid) {
2506 open STDIN, '<&', $fh or croak $!;
2507 exec qw/git-hash-object -w --stdin/ or croak $!;
2509 chomp($hash = do { local $/; <$out> });
2510 close $out or croak $!;
2511 close $fh or croak $!;
2512 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2513 close $fb->{base} or croak $!;
2514 } else {
2515 $hash = $fb->{blob} or die "no blob information\n";
2517 $fb->{pool}->clear;
2518 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2519 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2520 undef;
2523 sub abort_edit {
2524 my $self = shift;
2525 $self->{nr} = $self->{gii}->{nr};
2526 delete $self->{gii};
2527 $self->SUPER::abort_edit(@_);
2530 sub close_edit {
2531 my $self = shift;
2532 $self->{git_commit_ok} = 1;
2533 $self->{nr} = $self->{gii}->{nr};
2534 delete $self->{gii};
2535 $self->SUPER::close_edit(@_);
2538 package SVN::Git::Editor;
2539 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2540 use strict;
2541 use warnings;
2542 use Carp qw/croak/;
2543 use IO::File;
2544 use Digest::MD5;
2546 sub new {
2547 my ($class, $opts) = @_;
2548 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2549 die "$_ required!\n" unless (defined $opts->{$_});
2552 my $pool = SVN::Pool->new;
2553 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2554 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2555 $opts->{r}, $mods);
2557 # $opts->{ra} functions should not be used after this:
2558 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2559 $opts->{editor_cb}, $pool);
2560 my $self = SVN::Delta::Editor->new(@ce, $pool);
2561 bless $self, $class;
2562 foreach (qw/svn_path r tree_a tree_b/) {
2563 $self->{$_} = $opts->{$_};
2565 $self->{url} = $opts->{ra}->{url};
2566 $self->{mods} = $mods;
2567 $self->{types} = $types;
2568 $self->{pool} = $pool;
2569 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2570 $self->{rm} = { };
2571 $self->{path_prefix} = length $self->{svn_path} ?
2572 "$self->{svn_path}/" : '';
2573 return $self;
2576 sub generate_diff {
2577 my ($tree_a, $tree_b) = @_;
2578 my @diff_tree = qw(diff-tree -z -r);
2579 if ($_cp_similarity) {
2580 push @diff_tree, "-C$_cp_similarity";
2581 } else {
2582 push @diff_tree, '-C';
2584 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2585 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2586 push @diff_tree, $tree_a, $tree_b;
2587 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2588 local $/ = "\0";
2589 my $state = 'meta';
2590 my @mods;
2591 while (<$diff_fh>) {
2592 chomp $_; # this gets rid of the trailing "\0"
2593 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2594 $::sha1\s($::sha1)\s
2595 ([MTCRAD])\d*$/xo) {
2596 push @mods, { mode_a => $1, mode_b => $2,
2597 sha1_b => $3, chg => $4 };
2598 if ($4 =~ /^(?:C|R)$/) {
2599 $state = 'file_a';
2600 } else {
2601 $state = 'file_b';
2603 } elsif ($state eq 'file_a') {
2604 my $x = $mods[$#mods] or croak "Empty array\n";
2605 if ($x->{chg} !~ /^(?:C|R)$/) {
2606 croak "Error parsing $_, $x->{chg}\n";
2608 $x->{file_a} = $_;
2609 $state = 'file_b';
2610 } elsif ($state eq 'file_b') {
2611 my $x = $mods[$#mods] or croak "Empty array\n";
2612 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2613 croak "Error parsing $_, $x->{chg}\n";
2615 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2616 croak "Error parsing $_, $x->{chg}\n";
2618 $x->{file_b} = $_;
2619 $state = 'meta';
2620 } else {
2621 croak "Error parsing $_\n";
2624 command_close_pipe($diff_fh, $ctx);
2625 \@mods;
2628 sub check_diff_paths {
2629 my ($ra, $pfx, $rev, $mods) = @_;
2630 my %types;
2631 $pfx .= '/' if length $pfx;
2633 sub type_diff_paths {
2634 my ($ra, $types, $path, $rev) = @_;
2635 my @p = split m#/+#, $path;
2636 my $c = shift @p;
2637 unless (defined $types->{$c}) {
2638 $types->{$c} = $ra->check_path($c, $rev);
2640 while (@p) {
2641 $c .= '/' . shift @p;
2642 next if defined $types->{$c};
2643 $types->{$c} = $ra->check_path($c, $rev);
2647 foreach my $m (@$mods) {
2648 foreach my $f (qw/file_a file_b/) {
2649 next unless defined $m->{$f};
2650 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2651 if (length $pfx.$dir && ! defined $types{$dir}) {
2652 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2656 \%types;
2659 sub split_path {
2660 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2663 sub repo_path {
2664 my ($self, $path) = @_;
2665 $self->{path_prefix}.(defined $path ? $path : '');
2668 sub url_path {
2669 my ($self, $path) = @_;
2670 $self->{url} . '/' . $self->repo_path($path);
2673 sub rmdirs {
2674 my ($self) = @_;
2675 my $rm = $self->{rm};
2676 delete $rm->{''}; # we never delete the url we're tracking
2677 return unless %$rm;
2679 foreach (keys %$rm) {
2680 my @d = split m#/#, $_;
2681 my $c = shift @d;
2682 $rm->{$c} = 1;
2683 while (@d) {
2684 $c .= '/' . shift @d;
2685 $rm->{$c} = 1;
2688 delete $rm->{$self->{svn_path}};
2689 delete $rm->{''}; # we never delete the url we're tracking
2690 return unless %$rm;
2692 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2693 $self->{tree_b});
2694 local $/ = "\0";
2695 while (<$fh>) {
2696 chomp;
2697 my @dn = split m#/#, $_;
2698 while (pop @dn) {
2699 delete $rm->{join '/', @dn};
2701 unless (%$rm) {
2702 close $fh;
2703 return;
2706 command_close_pipe($fh, $ctx);
2708 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2709 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2710 $self->close_directory($bat->{$d}, $p);
2711 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2712 print "\tD+\t$d/\n" unless $::_q;
2713 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2714 delete $bat->{$d};
2718 sub open_or_add_dir {
2719 my ($self, $full_path, $baton) = @_;
2720 my $t = $self->{types}->{$full_path};
2721 if (!defined $t) {
2722 die "$full_path not known in r$self->{r} or we have a bug!\n";
2724 if ($t == $SVN::Node::none) {
2725 return $self->add_directory($full_path, $baton,
2726 undef, -1, $self->{pool});
2727 } elsif ($t == $SVN::Node::dir) {
2728 return $self->open_directory($full_path, $baton,
2729 $self->{r}, $self->{pool});
2731 print STDERR "$full_path already exists in repository at ",
2732 "r$self->{r} and it is not a directory (",
2733 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2734 exit 1;
2737 sub ensure_path {
2738 my ($self, $path) = @_;
2739 my $bat = $self->{bat};
2740 my $repo_path = $self->repo_path($path);
2741 return $bat->{''} unless (length $repo_path);
2742 my @p = split m#/+#, $repo_path;
2743 my $c = shift @p;
2744 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2745 while (@p) {
2746 my $c0 = $c;
2747 $c .= '/' . shift @p;
2748 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2750 return $bat->{$c};
2753 sub A {
2754 my ($self, $m) = @_;
2755 my ($dir, $file) = split_path($m->{file_b});
2756 my $pbat = $self->ensure_path($dir);
2757 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2758 undef, -1);
2759 print "\tA\t$m->{file_b}\n" unless $::_q;
2760 $self->chg_file($fbat, $m);
2761 $self->close_file($fbat,undef,$self->{pool});
2764 sub C {
2765 my ($self, $m) = @_;
2766 my ($dir, $file) = split_path($m->{file_b});
2767 my $pbat = $self->ensure_path($dir);
2768 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2769 $self->url_path($m->{file_a}), $self->{r});
2770 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2771 $self->chg_file($fbat, $m);
2772 $self->close_file($fbat,undef,$self->{pool});
2775 sub delete_entry {
2776 my ($self, $path, $pbat) = @_;
2777 my $rpath = $self->repo_path($path);
2778 my ($dir, $file) = split_path($rpath);
2779 $self->{rm}->{$dir} = 1;
2780 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2783 sub R {
2784 my ($self, $m) = @_;
2785 my ($dir, $file) = split_path($m->{file_b});
2786 my $pbat = $self->ensure_path($dir);
2787 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2788 $self->url_path($m->{file_a}), $self->{r});
2789 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2790 $self->chg_file($fbat, $m);
2791 $self->close_file($fbat,undef,$self->{pool});
2793 ($dir, $file) = split_path($m->{file_a});
2794 $pbat = $self->ensure_path($dir);
2795 $self->delete_entry($m->{file_a}, $pbat);
2798 sub M {
2799 my ($self, $m) = @_;
2800 my ($dir, $file) = split_path($m->{file_b});
2801 my $pbat = $self->ensure_path($dir);
2802 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2803 $pbat,$self->{r},$self->{pool});
2804 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2805 $self->chg_file($fbat, $m);
2806 $self->close_file($fbat,undef,$self->{pool});
2809 sub T { shift->M(@_) }
2811 sub change_file_prop {
2812 my ($self, $fbat, $pname, $pval) = @_;
2813 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2816 sub chg_file {
2817 my ($self, $fbat, $m) = @_;
2818 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2819 $self->change_file_prop($fbat,'svn:executable','*');
2820 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2821 $self->change_file_prop($fbat,'svn:executable',undef);
2823 my $fh = IO::File->new_tmpfile or croak $!;
2824 if ($m->{mode_b} =~ /^120/) {
2825 print $fh 'link ' or croak $!;
2826 $self->change_file_prop($fbat,'svn:special','*');
2827 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2828 $self->change_file_prop($fbat,'svn:special',undef);
2830 defined(my $pid = fork) or croak $!;
2831 if (!$pid) {
2832 open STDOUT, '>&', $fh or croak $!;
2833 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2835 waitpid $pid, 0;
2836 croak $? if $?;
2837 $fh->flush == 0 or croak $!;
2838 seek $fh, 0, 0 or croak $!;
2840 my $md5 = Digest::MD5->new;
2841 $md5->addfile($fh) or croak $!;
2842 seek $fh, 0, 0 or croak $!;
2844 my $exp = $md5->hexdigest;
2845 my $pool = SVN::Pool->new;
2846 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2847 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2848 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2849 $pool->clear;
2851 close $fh or croak $!;
2854 sub D {
2855 my ($self, $m) = @_;
2856 my ($dir, $file) = split_path($m->{file_b});
2857 my $pbat = $self->ensure_path($dir);
2858 print "\tD\t$m->{file_b}\n" unless $::_q;
2859 $self->delete_entry($m->{file_b}, $pbat);
2862 sub close_edit {
2863 my ($self) = @_;
2864 my ($p,$bat) = ($self->{pool}, $self->{bat});
2865 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2866 next if $_ eq '';
2867 $self->close_directory($bat->{$_}, $p);
2869 $self->close_directory($bat->{''}, $p);
2870 $self->SUPER::close_edit($p);
2871 $p->clear;
2874 sub abort_edit {
2875 my ($self) = @_;
2876 $self->SUPER::abort_edit($self->{pool});
2879 sub DESTROY {
2880 my $self = shift;
2881 $self->SUPER::DESTROY(@_);
2882 $self->{pool}->clear;
2885 # this drives the editor
2886 sub apply_diff {
2887 my ($self) = @_;
2888 my $mods = $self->{mods};
2889 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2890 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2891 my $f = $m->{chg};
2892 if (defined $o{$f}) {
2893 $self->$f($m);
2894 } else {
2895 fatal("Invalid change type: $f\n");
2898 $self->rmdirs if $_rmdir;
2899 if (@$mods == 0) {
2900 $self->abort_edit;
2901 } else {
2902 $self->close_edit;
2904 return scalar @$mods;
2907 package Git::SVN::Ra;
2908 use vars qw/@ISA $config_dir $_log_window_size/;
2909 use strict;
2910 use warnings;
2911 my ($can_do_switch, %ignored_err, $RA);
2913 BEGIN {
2914 # enforce temporary pool usage for some simple functions
2915 no strict 'refs';
2916 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
2917 my $SUPER = "SUPER::$f";
2918 *$f = sub {
2919 my $self = shift;
2920 my $pool = SVN::Pool->new;
2921 my @ret = $self->$SUPER(@_,$pool);
2922 $pool->clear;
2923 wantarray ? @ret : $ret[0];
2928 sub new {
2929 my ($class, $url) = @_;
2930 $url =~ s!/+$!!;
2931 return $RA if ($RA && $RA->{url} eq $url);
2933 SVN::_Core::svn_config_ensure($config_dir, undef);
2934 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2935 SVN::Client::get_simple_provider(),
2936 SVN::Client::get_ssl_server_trust_file_provider(),
2937 SVN::Client::get_simple_prompt_provider(
2938 \&Git::SVN::Prompt::simple, 2),
2939 SVN::Client::get_ssl_client_cert_file_provider(),
2940 SVN::Client::get_ssl_client_cert_prompt_provider(
2941 \&Git::SVN::Prompt::ssl_client_cert, 2),
2942 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2943 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2944 SVN::Client::get_username_provider(),
2945 SVN::Client::get_ssl_server_trust_prompt_provider(
2946 \&Git::SVN::Prompt::ssl_server_trust),
2947 SVN::Client::get_username_prompt_provider(
2948 \&Git::SVN::Prompt::username, 2),
2950 my $config = SVN::Core::config_get_config($config_dir);
2951 my $self = SVN::Ra->new(url => $url, auth => $baton,
2952 config => $config,
2953 pool => SVN::Pool->new,
2954 auth_provider_callbacks => $callbacks);
2955 $self->{svn_path} = $url;
2956 $self->{repos_root} = $self->get_repos_root;
2957 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2958 $self->{cache} = { check_path => { r => 0, data => {} },
2959 get_dir => { r => 0, data => {} } };
2960 $RA = bless $self, $class;
2963 sub check_path {
2964 my ($self, $path, $r) = @_;
2965 my $cache = $self->{cache}->{check_path};
2966 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
2967 return $cache->{data}->{$path};
2969 my $pool = SVN::Pool->new;
2970 my $t = $self->SUPER::check_path($path, $r, $pool);
2971 $pool->clear;
2972 if ($r != $cache->{r}) {
2973 %{$cache->{data}} = ();
2974 $cache->{r} = $r;
2976 $cache->{data}->{$path} = $t;
2979 sub get_dir {
2980 my ($self, $dir, $r) = @_;
2981 my $cache = $self->{cache}->{get_dir};
2982 if ($r == $cache->{r}) {
2983 if (my $x = $cache->{data}->{$dir}) {
2984 return wantarray ? @$x : $x->[0];
2987 my $pool = SVN::Pool->new;
2988 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
2989 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
2990 $pool->clear;
2991 if ($r != $cache->{r}) {
2992 %{$cache->{data}} = ();
2993 $cache->{r} = $r;
2995 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
2996 wantarray ? (\%dirents, $r, $props) : \%dirents;
2999 sub DESTROY {
3000 # do not call the real DESTROY since we store ourselves in $RA
3003 sub get_log {
3004 my ($self, @args) = @_;
3005 my $pool = SVN::Pool->new;
3006 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3007 my $ret = $self->SUPER::get_log(@args, $pool);
3008 $pool->clear;
3009 $ret;
3012 sub get_commit_editor {
3013 my ($self, $log, $cb, $pool) = @_;
3014 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3015 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3018 sub gs_do_update {
3019 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3020 my $new = ($rev_a == $rev_b);
3021 my $path = $gs->{path};
3023 if ($new && -e $gs->{index}) {
3024 unlink $gs->{index} or die
3025 "Couldn't unlink index: $gs->{index}: $!\n";
3027 my $pool = SVN::Pool->new;
3028 $editor->set_path_strip($path);
3029 my (@pc) = split m#/#, $path;
3030 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3031 1, $editor, $pool);
3032 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3034 # Since we can't rely on svn_ra_reparent being available, we'll
3035 # just have to do some magic with set_path to make it so
3036 # we only want a partial path.
3037 my $sp = '';
3038 my $final = join('/', @pc);
3039 while (@pc) {
3040 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3041 $sp .= '/' if length $sp;
3042 $sp .= shift @pc;
3044 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3046 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3048 $reporter->finish_report($pool);
3049 $pool->clear;
3050 $editor->{git_commit_ok};
3053 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3054 # svn_ra_reparent didn't work before 1.4)
3055 sub gs_do_switch {
3056 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3057 my $path = $gs->{path};
3058 my $pool = SVN::Pool->new;
3060 my $full_url = $self->{url};
3061 my $old_url = $full_url;
3062 $full_url .= "/$path" if length $path;
3063 my ($ra, $reparented);
3064 if ($old_url ne $full_url) {
3065 if ($old_url !~ m#^svn(\+ssh)?://#) {
3066 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3067 $pool);
3068 $self->{url} = $full_url;
3069 $reparented = 1;
3070 } else {
3071 $ra = Git::SVN::Ra->new($full_url);
3074 $ra ||= $self;
3075 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3076 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3077 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3078 $reporter->finish_report($pool);
3080 if ($reparented) {
3081 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3082 $self->{url} = $old_url;
3085 $pool->clear;
3086 $editor->{git_commit_ok};
3089 sub longest_common_path {
3090 my ($gsv, $globs) = @_;
3091 my %common;
3092 my $common_max = scalar @$gsv;
3094 foreach my $gs (@$gsv) {
3095 my @tmp = split m#/#, $gs->{path};
3096 my $p = '';
3097 foreach (@tmp) {
3098 $p .= length($p) ? "/$_" : $_;
3099 $common{$p} ||= 0;
3100 $common{$p}++;
3103 $globs ||= [];
3104 $common_max += scalar @$globs;
3105 foreach my $glob (@$globs) {
3106 my @tmp = split m#/#, $glob->{path}->{left};
3107 my $p = '';
3108 foreach (@tmp) {
3109 $p .= length($p) ? "/$_" : $_;
3110 $common{$p} ||= 0;
3111 $common{$p}++;
3115 my $longest_path = '';
3116 foreach (sort {length $b <=> length $a} keys %common) {
3117 if ($common{$_} == $common_max) {
3118 $longest_path = $_;
3119 last;
3122 $longest_path;
3125 sub gs_fetch_loop_common {
3126 my ($self, $base, $head, $gsv, $globs) = @_;
3127 return if ($base > $head);
3128 my $inc = $_log_window_size;
3129 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3130 my $longest_path = longest_common_path($gsv, $globs);
3131 while (1) {
3132 my %revs;
3133 my $err;
3134 my $err_handler = $SVN::Error::handler;
3135 $SVN::Error::handler = sub {
3136 ($err) = @_;
3137 skip_unknown_revs($err);
3139 sub _cb {
3140 my ($paths, $r, $author, $date, $log) = @_;
3141 [ dup_changed_paths($paths),
3142 { author => $author, date => $date, log => $log } ];
3144 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3145 sub { $revs{$_[1]} = _cb(@_) });
3146 if ($err && $max >= $head) {
3147 print STDERR "Path '$longest_path' ",
3148 "was probably deleted:\n",
3149 $err->expanded_message,
3150 "\nWill attempt to follow ",
3151 "revisions r$min .. r$max ",
3152 "committed before the deletion\n";
3153 my $hi = $max;
3154 while (--$hi >= $min) {
3155 my $ok;
3156 $self->get_log([$longest_path], $min, $hi,
3157 0, 1, 1, sub {
3158 $ok ||= $_[1];
3159 $revs{$_[1]} = _cb(@_) });
3160 if ($ok) {
3161 print STDERR "r$min .. r$ok OK\n";
3162 last;
3166 $SVN::Error::handler = $err_handler;
3168 my %exists = map { $_->{path} => $_ } @$gsv;
3169 foreach my $r (sort {$a <=> $b} keys %revs) {
3170 my ($paths, $logged) = @{$revs{$r}};
3172 foreach my $gs ($self->match_globs(\%exists, $paths,
3173 $globs, $r)) {
3174 if ($gs->rev_db_max >= $r) {
3175 next;
3177 next unless $gs->match_paths($paths, $r);
3178 $gs->{logged_rev_props} = $logged;
3179 if (my $last_commit = $gs->last_commit) {
3180 $gs->assert_index_clean($last_commit);
3182 my $log_entry = $gs->do_fetch($paths, $r);
3183 if ($log_entry) {
3184 $gs->do_git_commit($log_entry);
3187 foreach my $g (@$globs) {
3188 my $k = "svn-remote.$g->{remote}." .
3189 "$g->{t}-maxRev";
3190 Git::SVN::tmp_config($k, $r);
3193 # pre-fill the .rev_db since it'll eventually get filled in
3194 # with '0' x40 if something new gets committed
3195 foreach my $gs (@$gsv) {
3196 next if defined $gs->rev_db_get($max);
3197 $gs->rev_db_set($max, 0 x40);
3199 foreach my $g (@$globs) {
3200 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3201 Git::SVN::tmp_config($k, $max);
3203 last if $max >= $head;
3204 $min = $max + 1;
3205 $max += $inc;
3206 $max = $head if ($max > $head);
3210 sub match_globs {
3211 my ($self, $exists, $paths, $globs, $r) = @_;
3213 sub get_dir_check {
3214 my ($self, $exists, $g, $r) = @_;
3215 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3216 return unless scalar @x == 3;
3217 my $dirents = $x[0];
3218 foreach my $de (keys %$dirents) {
3219 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3220 my $p = $g->{path}->full_path($de);
3221 next if $exists->{$p};
3222 next if (length $g->{path}->{right} &&
3223 ($self->check_path($p, $r) !=
3224 $SVN::Node::dir));
3225 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3226 $g->{ref}->full_path($de), 1);
3229 foreach my $g (@$globs) {
3230 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3231 if ($path->{action} =~ /^[AR]$/) {
3232 get_dir_check($self, $exists, $g, $r);
3235 foreach (keys %$paths) {
3236 if (/$g->{path}->{left_regex}/ &&
3237 !/$g->{path}->{regex}/) {
3238 next if $paths->{$_}->{action} !~ /^[AR]$/;
3239 get_dir_check($self, $exists, $g, $r);
3241 next unless /$g->{path}->{regex}/;
3242 my $p = $1;
3243 my $pathname = $g->{path}->full_path($p);
3244 next if $exists->{$pathname};
3245 next if ($self->check_path($pathname, $r) !=
3246 $SVN::Node::dir);
3247 $exists->{$pathname} = Git::SVN->init(
3248 $self->{url}, $pathname, undef,
3249 $g->{ref}->full_path($p), 1);
3251 my $c = '';
3252 foreach (split m#/#, $g->{path}->{left}) {
3253 $c .= "/$_";
3254 next unless ($paths->{$c} &&
3255 ($paths->{$c}->{action} =~ /^[AR]$/));
3256 get_dir_check($self, $exists, $g, $r);
3259 values %$exists;
3262 sub minimize_url {
3263 my ($self) = @_;
3264 return $self->{url} if ($self->{url} eq $self->{repos_root});
3265 my $url = $self->{repos_root};
3266 my @components = split(m!/!, $self->{svn_path});
3267 my $c = '';
3268 do {
3269 $url .= "/$c" if length $c;
3270 eval { (ref $self)->new($url)->get_latest_revnum };
3271 } while ($@ && ($c = shift @components));
3272 $url;
3275 sub can_do_switch {
3276 my $self = shift;
3277 unless (defined $can_do_switch) {
3278 my $pool = SVN::Pool->new;
3279 my $rep = eval {
3280 $self->do_switch(1, '', 0, $self->{url},
3281 SVN::Delta::Editor->new, $pool);
3283 if ($@) {
3284 $can_do_switch = 0;
3285 } else {
3286 $rep->abort_report($pool);
3287 $can_do_switch = 1;
3289 $pool->clear;
3291 $can_do_switch;
3294 sub skip_unknown_revs {
3295 my ($err) = @_;
3296 my $errno = $err->apr_err();
3297 # Maybe the branch we're tracking didn't
3298 # exist when the repo started, so it's
3299 # not an error if it doesn't, just continue
3301 # Wonderfully consistent library, eh?
3302 # 160013 - svn:// and file://
3303 # 175002 - http(s)://
3304 # 175007 - http(s):// (this repo required authorization, too...)
3305 # More codes may be discovered later...
3306 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3307 my $err_key = $err->expanded_message;
3308 # revision numbers change every time, filter them out
3309 $err_key =~ s/\d+/\0/g;
3310 $err_key = "$errno\0$err_key";
3311 unless ($ignored_err{$err_key}) {
3312 warn "W: Ignoring error from SVN, path probably ",
3313 "does not exist: ($errno): ",
3314 $err->expanded_message,"\n";
3315 $ignored_err{$err_key} = 1;
3317 return;
3319 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3322 # svn_log_changed_path_t objects passed to get_log are likely to be
3323 # overwritten even if only the refs are copied to an external variable,
3324 # so we should dup the structures in their entirety. Using an externally
3325 # passed pool (instead of our temporary and quickly cleared pool in
3326 # Git::SVN::Ra) does not help matters at all...
3327 sub dup_changed_paths {
3328 my ($paths) = @_;
3329 return undef unless $paths;
3330 my %ret;
3331 foreach my $p (keys %$paths) {
3332 my $i = $paths->{$p};
3333 my %s = map { $_ => $i->$_ }
3334 qw/copyfrom_path copyfrom_rev action/;
3335 $ret{$p} = \%s;
3337 \%ret;
3340 package Git::SVN::Log;
3341 use strict;
3342 use warnings;
3343 use POSIX qw/strftime/;
3344 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3345 %rusers $show_commit $incremental/;
3346 my $l_fmt;
3348 sub cmt_showable {
3349 my ($c) = @_;
3350 return 1 if defined $c->{r};
3352 # big commit message got truncated by the 16k pretty buffer in rev-list
3353 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3354 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3355 @{$c->{l}} = ();
3356 my @log = command(qw/cat-file commit/, $c->{c});
3358 # shift off the headers
3359 shift @log while ($log[0] ne '');
3360 shift @log;
3362 # TODO: make $c->{l} not have a trailing newline in the future
3363 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3365 (undef, $c->{r}, undef) = ::extract_metadata(
3366 (grep(/^git-svn-id: /, @log))[-1]);
3368 return defined $c->{r};
3371 sub log_use_color {
3372 return 1 if $color;
3373 my ($dc, $dcvar);
3374 $dcvar = 'color.diff';
3375 $dc = `git-config --get $dcvar`;
3376 if ($dc eq '') {
3377 # nothing at all; fallback to "diff.color"
3378 $dcvar = 'diff.color';
3379 $dc = `git-config --get $dcvar`;
3381 chomp($dc);
3382 if ($dc eq 'auto') {
3383 my $pc;
3384 $pc = `git-config --get color.pager`;
3385 if ($pc eq '') {
3386 # does not have it -- fallback to pager.color
3387 $pc = `git-config --bool --get pager.color`;
3389 else {
3390 $pc = `git-config --bool --get color.pager`;
3391 if ($?) {
3392 $pc = 'false';
3395 chomp($pc);
3396 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3397 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3399 return 0;
3401 return 0 if $dc eq 'never';
3402 return 1 if $dc eq 'always';
3403 chomp($dc = `git-config --bool --get $dcvar`);
3404 return ($dc eq 'true');
3407 sub git_svn_log_cmd {
3408 my ($r_min, $r_max, @args) = @_;
3409 my $head = 'HEAD';
3410 foreach my $x (@args) {
3411 last if $x eq '--';
3412 next unless ::verify_ref("$x^0");
3413 $head = $x;
3414 last;
3417 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3418 $gs ||= Git::SVN->_new;
3419 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3420 $gs->refname);
3421 push @cmd, '-r' unless $non_recursive;
3422 push @cmd, qw/--raw --name-status/ if $verbose;
3423 push @cmd, '--color' if log_use_color();
3424 return @cmd unless defined $r_max;
3425 if ($r_max == $r_min) {
3426 push @cmd, '--max-count=1';
3427 if (my $c = $gs->rev_db_get($r_max)) {
3428 push @cmd, $c;
3430 } else {
3431 my ($c_min, $c_max);
3432 $c_max = $gs->rev_db_get($r_max);
3433 $c_min = $gs->rev_db_get($r_min);
3434 if (defined $c_min && defined $c_max) {
3435 if ($r_max > $r_max) {
3436 push @cmd, "$c_min..$c_max";
3437 } else {
3438 push @cmd, "$c_max..$c_min";
3440 } elsif ($r_max > $r_min) {
3441 push @cmd, $c_max;
3442 } else {
3443 push @cmd, $c_min;
3446 return @cmd;
3449 # adapted from pager.c
3450 sub config_pager {
3451 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3452 if (!defined $pager) {
3453 $pager = 'less';
3454 } elsif (length $pager == 0 || $pager eq 'cat') {
3455 $pager = undef;
3459 sub run_pager {
3460 return unless -t *STDOUT;
3461 pipe my $rfd, my $wfd or return;
3462 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3463 if (!$pid) {
3464 open STDOUT, '>&', $wfd or
3465 ::fatal "Can't redirect to stdout: $!\n";
3466 return;
3468 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3469 $ENV{LESS} ||= 'FRSX';
3470 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3473 sub tz_to_s_offset {
3474 my ($tz) = @_;
3475 $tz =~ s/(\d\d)$//;
3476 return ($1 * 60) + ($tz * 3600);
3479 sub get_author_info {
3480 my ($dest, $author, $t, $tz) = @_;
3481 $author =~ s/(?:^\s*|\s*$)//g;
3482 $dest->{a_raw} = $author;
3483 my $au;
3484 if ($::_authors) {
3485 $au = $rusers{$author} || undef;
3487 if (!$au) {
3488 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3490 $dest->{t} = $t;
3491 $dest->{tz} = $tz;
3492 $dest->{a} = $au;
3493 # Date::Parse isn't in the standard Perl distro :(
3494 if ($tz =~ s/^\+//) {
3495 $t += tz_to_s_offset($tz);
3496 } elsif ($tz =~ s/^\-//) {
3497 $t -= tz_to_s_offset($tz);
3499 $dest->{t_utc} = $t;
3502 sub process_commit {
3503 my ($c, $r_min, $r_max, $defer) = @_;
3504 if (defined $r_min && defined $r_max) {
3505 if ($r_min == $c->{r} && $r_min == $r_max) {
3506 show_commit($c);
3507 return 0;
3509 return 1 if $r_min == $r_max;
3510 if ($r_min < $r_max) {
3511 # we need to reverse the print order
3512 return 0 if (defined $limit && --$limit < 0);
3513 push @$defer, $c;
3514 return 1;
3516 if ($r_min != $r_max) {
3517 return 1 if ($r_min < $c->{r});
3518 return 1 if ($r_max > $c->{r});
3521 return 0 if (defined $limit && --$limit < 0);
3522 show_commit($c);
3523 return 1;
3526 sub show_commit {
3527 my $c = shift;
3528 if ($oneline) {
3529 my $x = "\n";
3530 if (my $l = $c->{l}) {
3531 while ($l->[0] =~ /^\s*$/) { shift @$l }
3532 $x = $l->[0];
3534 $l_fmt ||= 'A' . length($c->{r});
3535 print 'r',pack($l_fmt, $c->{r}),' | ';
3536 print "$c->{c} | " if $show_commit;
3537 print $x;
3538 } else {
3539 show_commit_normal($c);
3543 sub show_commit_changed_paths {
3544 my ($c) = @_;
3545 return unless $c->{changed};
3546 print "Changed paths:\n", @{$c->{changed}};
3549 sub show_commit_normal {
3550 my ($c) = @_;
3551 print '-' x72, "\nr$c->{r} | ";
3552 print "$c->{c} | " if $show_commit;
3553 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3554 localtime($c->{t_utc})), ' | ';
3555 my $nr_line = 0;
3557 if (my $l = $c->{l}) {
3558 while ($l->[$#$l] eq "\n" && $#$l > 0
3559 && $l->[($#$l - 1)] eq "\n") {
3560 pop @$l;
3562 $nr_line = scalar @$l;
3563 if (!$nr_line) {
3564 print "1 line\n\n\n";
3565 } else {
3566 if ($nr_line == 1) {
3567 $nr_line = '1 line';
3568 } else {
3569 $nr_line .= ' lines';
3571 print $nr_line, "\n";
3572 show_commit_changed_paths($c);
3573 print "\n";
3574 print $_ foreach @$l;
3576 } else {
3577 print "1 line\n";
3578 show_commit_changed_paths($c);
3579 print "\n";
3582 foreach my $x (qw/raw stat diff/) {
3583 if ($c->{$x}) {
3584 print "\n";
3585 print $_ foreach @{$c->{$x}}
3590 sub cmd_show_log {
3591 my (@args) = @_;
3592 my ($r_min, $r_max);
3593 my $r_last = -1; # prevent dupes
3594 if (defined $TZ) {
3595 $ENV{TZ} = $TZ;
3596 } else {
3597 delete $ENV{TZ};
3599 if (defined $::_revision) {
3600 if ($::_revision =~ /^(\d+):(\d+)$/) {
3601 ($r_min, $r_max) = ($1, $2);
3602 } elsif ($::_revision =~ /^\d+$/) {
3603 $r_min = $r_max = $::_revision;
3604 } else {
3605 ::fatal "-r$::_revision is not supported, use ",
3606 "standard \'git log\' arguments instead\n";
3610 config_pager();
3611 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3612 my $log = command_output_pipe(@args);
3613 run_pager();
3614 my (@k, $c, $d, $stat);
3615 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3616 while (<$log>) {
3617 if (/^${esc_color}commit ($::sha1_short)/o) {
3618 my $cmt = $1;
3619 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3620 $r_last = $c->{r};
3621 process_commit($c, $r_min, $r_max, \@k) or
3622 goto out;
3624 $d = undef;
3625 $c = { c => $cmt };
3626 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3627 get_author_info($c, $1, $2, $3);
3628 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3629 # ignore
3630 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3631 push @{$c->{raw}}, $_;
3632 } elsif (/^${esc_color}[ACRMDT]\t/) {
3633 # we could add $SVN->{svn_path} here, but that requires
3634 # remote access at the moment (repo_path_split)...
3635 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3636 push @{$c->{changed}}, $_;
3637 } elsif (/^${esc_color}diff /o) {
3638 $d = 1;
3639 push @{$c->{diff}}, $_;
3640 } elsif ($d) {
3641 push @{$c->{diff}}, $_;
3642 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3643 $esc_color*[\+\-]*$esc_color$/x) {
3644 $stat = 1;
3645 push @{$c->{stat}}, $_;
3646 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3647 push @{$c->{stat}}, $_;
3648 $stat = undef;
3649 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3650 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3651 } elsif (s/^${esc_color} //o) {
3652 push @{$c->{l}}, $_;
3655 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3656 $r_last = $c->{r};
3657 process_commit($c, $r_min, $r_max, \@k);
3659 if (@k) {
3660 my $swap = $r_max;
3661 $r_max = $r_min;
3662 $r_min = $swap;
3663 process_commit($_, $r_min, $r_max) foreach reverse @k;
3665 out:
3666 close $log;
3667 print '-' x72,"\n" unless $incremental || $oneline;
3670 package Git::SVN::Migration;
3671 # these version numbers do NOT correspond to actual version numbers
3672 # of git nor git-svn. They are just relative.
3674 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3676 # v1 layout: .git/$id/info/url, refs/remotes/$id
3678 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3680 # v3 layout: .git/svn/$id, refs/remotes/$id
3681 # - info/url may remain for backwards compatibility
3682 # - this is what we migrate up to this layout automatically,
3683 # - this will be used by git svn init on single branches
3684 # v3.1 layout (auto migrated):
3685 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3686 # for backwards compatibility
3688 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3689 # - this is only created for newly multi-init-ed
3690 # repositories. Similar in spirit to the
3691 # --use-separate-remotes option in git-clone (now default)
3692 # - we do not automatically migrate to this (following
3693 # the example set by core git)
3694 use strict;
3695 use warnings;
3696 use Carp qw/croak/;
3697 use File::Path qw/mkpath/;
3698 use File::Basename qw/dirname basename/;
3699 use vars qw/$_minimize/;
3701 sub migrate_from_v0 {
3702 my $git_dir = $ENV{GIT_DIR};
3703 return undef unless -d $git_dir;
3704 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3705 my $migrated = 0;
3706 while (<$fh>) {
3707 chomp;
3708 my ($id, $orig_ref) = ($_, $_);
3709 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3710 next unless -f "$git_dir/$id/info/url";
3711 my $new_ref = "refs/remotes/$id";
3712 if (::verify_ref("$new_ref^0")) {
3713 print STDERR "W: $orig_ref is probably an old ",
3714 "branch used by an ancient version of ",
3715 "git-svn.\n",
3716 "However, $new_ref also exists.\n",
3717 "We will not be able ",
3718 "to use this branch until this ",
3719 "ambiguity is resolved.\n";
3720 next;
3722 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3723 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3724 command_noisy('update-ref', $new_ref, $orig_ref);
3725 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3726 $migrated++;
3728 command_close_pipe($fh, $ctx);
3729 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3730 $migrated;
3733 sub migrate_from_v1 {
3734 my $git_dir = $ENV{GIT_DIR};
3735 my $migrated = 0;
3736 return $migrated unless -d $git_dir;
3737 my $svn_dir = "$git_dir/svn";
3739 # just in case somebody used 'svn' as their $id at some point...
3740 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3742 print STDERR "Migrating from a git-svn v1 layout...\n";
3743 mkpath([$svn_dir]);
3744 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3745 "$svn_dir\n\t(required for this version ",
3746 "($::VERSION) of git-svn) does not. exist\n";
3747 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3748 while (<$fh>) {
3749 my $x = $_;
3750 next unless $x =~ s#^refs/remotes/##;
3751 chomp $x;
3752 next unless -f "$git_dir/$x/info/url";
3753 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3754 next unless $u;
3755 my $dn = dirname("$git_dir/svn/$x");
3756 mkpath([$dn]) unless -d $dn;
3757 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3758 mkpath(["$git_dir/svn/svn"]);
3759 print STDERR " - $git_dir/$x/info => ",
3760 "$git_dir/svn/$x/info\n";
3761 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3762 croak "$!: $x";
3763 # don't worry too much about these, they probably
3764 # don't exist with repos this old (save for index,
3765 # and we can easily regenerate that)
3766 foreach my $f (qw/unhandled.log index .rev_db/) {
3767 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3769 } else {
3770 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3771 rename "$git_dir/$x", "$git_dir/svn/$x" or
3772 croak "$!: $x";
3774 $migrated++;
3776 command_close_pipe($fh, $ctx);
3777 print STDERR "Done migrating from a git-svn v1 layout\n";
3778 $migrated;
3781 sub read_old_urls {
3782 my ($l_map, $pfx, $path) = @_;
3783 my @dir;
3784 foreach (<$path/*>) {
3785 if (-r "$_/info/url") {
3786 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3787 my $ref_id = $pfx . basename $_;
3788 my $url = ::file_to_s("$_/info/url");
3789 $l_map->{$ref_id} = $url;
3790 } elsif (-d $_) {
3791 push @dir, $_;
3794 foreach (@dir) {
3795 my $x = $_;
3796 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3797 read_old_urls($l_map, $x, $_);
3801 sub migrate_from_v2 {
3802 my @cfg = command(qw/config -l/);
3803 return if grep /^svn-remote\..+\.url=/, @cfg;
3804 my %l_map;
3805 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3806 my $migrated = 0;
3808 foreach my $ref_id (sort keys %l_map) {
3809 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3810 if ($@) {
3811 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3813 $migrated++;
3815 $migrated;
3818 sub minimize_connections {
3819 my $r = Git::SVN::read_all_remotes();
3820 my $new_urls = {};
3821 my $root_repos = {};
3822 foreach my $repo_id (keys %$r) {
3823 my $url = $r->{$repo_id}->{url} or next;
3824 my $fetch = $r->{$repo_id}->{fetch} or next;
3825 my $ra = Git::SVN::Ra->new($url);
3827 # skip existing cases where we already connect to the root
3828 if (($ra->{url} eq $ra->{repos_root}) ||
3829 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3830 $repo_id)) {
3831 $root_repos->{$ra->{url}} = $repo_id;
3832 next;
3835 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3836 my $root_path = $ra->{url};
3837 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3838 foreach my $path (keys %$fetch) {
3839 my $ref_id = $fetch->{$path};
3840 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3842 # make sure we can read when connecting to
3843 # a higher level of a repository
3844 my ($last_rev, undef) = $gs->last_rev_commit;
3845 if (!defined $last_rev) {
3846 $last_rev = eval {
3847 $root_ra->get_latest_revnum;
3849 next if $@;
3851 my $new = $root_path;
3852 $new .= length $path ? "/$path" : '';
3853 eval {
3854 $root_ra->get_log([$new], $last_rev, $last_rev,
3855 0, 0, 1, sub { });
3857 next if $@;
3858 $new_urls->{$ra->{repos_root}}->{$new} =
3859 { ref_id => $ref_id,
3860 old_repo_id => $repo_id,
3861 old_path => $path };
3865 my @emptied;
3866 foreach my $url (keys %$new_urls) {
3867 # see if we can re-use an existing [svn-remote "repo_id"]
3868 # instead of creating a(n ugly) new section:
3869 my $repo_id = $root_repos->{$url} ||
3870 Git::SVN::sanitize_remote_name($url);
3872 my $fetch = $new_urls->{$url};
3873 foreach my $path (keys %$fetch) {
3874 my $x = $fetch->{$path};
3875 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3876 my $pfx = "svn-remote.$x->{old_repo_id}";
3878 my $old_fetch = quotemeta("$x->{old_path}:".
3879 "refs/remotes/$x->{ref_id}");
3880 command_noisy(qw/config --unset/,
3881 "$pfx.fetch", '^'. $old_fetch . '$');
3882 delete $r->{$x->{old_repo_id}}->
3883 {fetch}->{$x->{old_path}};
3884 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3885 command_noisy(qw/config --unset/,
3886 "$pfx.url");
3887 push @emptied, $x->{old_repo_id}
3891 if (@emptied) {
3892 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3893 "$ENV{GIT_DIR}/config";
3894 print STDERR <<EOF;
3895 The following [svn-remote] sections in your config file ($file) are empty
3896 and can be safely removed:
3898 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3902 sub migration_check {
3903 migrate_from_v0();
3904 migrate_from_v1();
3905 migrate_from_v2();
3906 minimize_connections() if $_minimize;
3909 package Git::IndexInfo;
3910 use strict;
3911 use warnings;
3912 use Git qw/command_input_pipe command_close_pipe/;
3914 sub new {
3915 my ($class) = @_;
3916 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3917 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3920 sub remove {
3921 my ($self, $path) = @_;
3922 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3923 return ++$self->{nr};
3925 undef;
3928 sub update {
3929 my ($self, $mode, $hash, $path) = @_;
3930 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3931 return ++$self->{nr};
3933 undef;
3936 sub DESTROY {
3937 my ($self) = @_;
3938 command_close_pipe($self->{gui}, $self->{ctx});
3941 package Git::SVN::GlobSpec;
3942 use strict;
3943 use warnings;
3945 sub new {
3946 my ($class, $glob) = @_;
3947 my $re = $glob;
3948 $re =~ s!/+$!!g; # no need for trailing slashes
3949 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3950 my ($left, $right) = ($1, $2);
3951 if ($nr > 1) {
3952 die "Only one '*' wildcard expansion ",
3953 "is supported (got $nr): '$glob'\n";
3954 } elsif ($nr == 0) {
3955 die "One '*' is needed for glob: '$glob'\n";
3957 $re = quotemeta($left) . $re . quotemeta($right);
3958 if (length $left && !($left =~ s!/+$!!g)) {
3959 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3961 if (length $right && !($right =~ s!^/+!!g)) {
3962 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3964 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3965 bless { left => $left, right => $right, left_regex => $left_re,
3966 regex => qr/$re/, glob => $glob }, $class;
3969 sub full_path {
3970 my ($self, $path) = @_;
3971 return (length $self->{left} ? "$self->{left}/" : '') .
3972 $path . (length $self->{right} ? "/$self->{right}" : '');
3975 __END__
3977 Data structures:
3980 $remotes = { # returned by read_all_remotes()
3981 'svn' => {
3982 # svn-remote.svn.url=https://svn.musicpd.org
3983 url => 'https://svn.musicpd.org',
3984 # svn-remote.svn.fetch=mpd/trunk:trunk
3985 fetch => {
3986 'mpd/trunk' => 'trunk',
3988 # svn-remote.svn.tags=mpd/tags/*:tags/*
3989 tags => {
3990 path => {
3991 left => 'mpd/tags',
3992 right => '',
3993 regex => qr!mpd/tags/([^/]+)$!,
3994 glob => 'tags/*',
3996 ref => {
3997 left => 'tags',
3998 right => '',
3999 regex => qr!tags/([^/]+)$!,
4000 glob => 'tags/*',
4006 $log_entry hashref as returned by libsvn_log_entry()
4008 log => 'whitespace-formatted log entry
4009 ', # trailing newline is preserved
4010 revision => '8', # integer
4011 date => '2004-02-24T17:01:44.108345Z', # commit date
4012 author => 'committer name'
4016 # this is generated by generate_diff();
4017 @mods = array of diff-index line hashes, each element represents one line
4018 of diff-index output
4020 diff-index line ($m hash)
4022 mode_a => first column of diff-index output, no leading ':',
4023 mode_b => second column of diff-index output,
4024 sha1_b => sha1sum of the final blob,
4025 chg => change type [MCRADT],
4026 file_a => original file name of a file (iff chg is 'C' or 'R')
4027 file_b => new/current file name of a file (any chg)
4031 # retval of read_url_paths{,_all}();
4032 $l_map = {
4033 # repository root url
4034 'https://svn.musicpd.org' => {
4035 # repository path # GIT_SVN_ID
4036 'mpd/trunk' => 'trunk',
4037 'mpd/tags/0.11.5' => 'tags/0.11.5',
4041 Notes:
4042 I don't trust the each() function on unless I created %hash myself
4043 because the internal iterator may not have started at base.