git-stash: allow more descriptive reminder message when saving
[git/jnareb-git/bp-gitweb.git] / git-svn.perl
blobb3dffccf38a52714f000f1f90b6c32ecdeb43f82
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41 # import functions from Git into our packages, en masse
42 no strict 'refs';
43 foreach (qw/command command_oneline command_noisy command_output_pipe
44 command_input_pipe command_close_pipe/) {
45 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
46 Git::SVN::Migration Git::SVN::Log Git::SVN),
47 __PACKAGE__) {
48 *{"${package}::$_"} = \&{"Git::$_"};
53 my ($SVN);
55 $sha1 = qr/[a-f\d]{40}/;
56 $sha1_short = qr/[a-f\d]{4,40}/;
57 my ($_stdin, $_help, $_edit,
58 $_message, $_file,
59 $_template, $_shared,
60 $_version, $_fetch_all, $_no_rebase,
61 $_merge, $_strategy, $_dry_run, $_local,
62 $_prefix, $_no_checkout, $_verbose);
63 $Git::SVN::_follow_parent = 1;
64 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
65 'config-dir=s' => \$Git::SVN::Ra::config_dir,
66 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
67 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
68 'authors-file|A=s' => \$_authors,
69 'repack:i' => \$Git::SVN::_repack,
70 'noMetadata' => \$Git::SVN::_no_metadata,
71 'useSvmProps' => \$Git::SVN::_use_svm_props,
72 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
73 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
74 'no-checkout' => \$_no_checkout,
75 'quiet|q' => \$_q,
76 'repack-flags|repack-args|repack-opts=s' =>
77 \$Git::SVN::_repack_flags,
78 %remote_opts );
80 my ($_trunk, $_tags, $_branches);
81 my %icv;
82 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
83 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
84 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
85 'minimize-url|m' => \$Git::SVN::_minimize_url,
86 'no-metadata' => sub { $icv{noMetadata} = 1 },
87 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
88 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
89 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
90 %remote_opts );
91 my %cmt_opts = ( 'edit|e' => \$_edit,
92 'rmdir' => \$SVN::Git::Editor::_rmdir,
93 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
94 'l=i' => \$SVN::Git::Editor::_rename_limit,
95 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
98 my %cmd = (
99 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
100 { 'revision|r=s' => \$_revision,
101 'fetch-all|all' => \$_fetch_all,
102 %fc_opts } ],
103 clone => [ \&cmd_clone, "Initialize and fetch revisions",
104 { 'revision|r=s' => \$_revision,
105 %fc_opts, %init_opts } ],
106 init => [ \&cmd_init, "Initialize a repo for tracking" .
107 " (requires URL argument)",
108 \%init_opts ],
109 'multi-init' => [ \&cmd_multi_init,
110 "Deprecated alias for ".
111 "'$0 init -T<trunk> -b<branches> -t<tags>'",
112 \%init_opts ],
113 dcommit => [ \&cmd_dcommit,
114 'Commit several diffs to merge with upstream',
115 { 'merge|m|M' => \$_merge,
116 'strategy|s=s' => \$_strategy,
117 'verbose|v' => \$_verbose,
118 'dry-run|n' => \$_dry_run,
119 'fetch-all|all' => \$_fetch_all,
120 'no-rebase' => \$_no_rebase,
121 %cmt_opts, %fc_opts } ],
122 'set-tree' => [ \&cmd_set_tree,
123 "Set an SVN repository to a git tree-ish",
124 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
125 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
126 { 'revision|r=i' => \$_revision } ],
127 'multi-fetch' => [ \&cmd_multi_fetch,
128 "Deprecated alias for $0 fetch --all",
129 { 'revision|r=s' => \$_revision, %fc_opts } ],
130 'migrate' => [ sub { },
131 # no-op, we automatically run this anyways,
132 'Migrate configuration/metadata/layout from
133 previous versions of git-svn',
134 { 'minimize' => \$Git::SVN::Migration::_minimize,
135 %remote_opts } ],
136 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
137 { 'limit=i' => \$Git::SVN::Log::limit,
138 'revision|r=s' => \$_revision,
139 'verbose|v' => \$Git::SVN::Log::verbose,
140 'incremental' => \$Git::SVN::Log::incremental,
141 'oneline' => \$Git::SVN::Log::oneline,
142 'show-commit' => \$Git::SVN::Log::show_commit,
143 'non-recursive' => \$Git::SVN::Log::non_recursive,
144 'authors-file|A=s' => \$_authors,
145 'color' => \$Git::SVN::Log::color,
146 'pager=s' => \$Git::SVN::Log::pager,
147 } ],
148 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
149 { } ],
150 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
151 { 'merge|m|M' => \$_merge,
152 'verbose|v' => \$_verbose,
153 'strategy|s=s' => \$_strategy,
154 'local|l' => \$_local,
155 'fetch-all|all' => \$_fetch_all,
156 %fc_opts } ],
157 'commit-diff' => [ \&cmd_commit_diff,
158 'Commit a diff between two trees',
159 { 'message|m=s' => \$_message,
160 'file|F=s' => \$_file,
161 'revision|r=s' => \$_revision,
162 %cmt_opts } ],
165 my $cmd;
166 for (my $i = 0; $i < @ARGV; $i++) {
167 if (defined $cmd{$ARGV[$i]}) {
168 $cmd = $ARGV[$i];
169 splice @ARGV, $i, 1;
170 last;
174 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
176 read_repo_config(\%opts);
177 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
178 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
179 'minimize-connections' => \$Git::SVN::Migration::_minimize,
180 'id|i=s' => \$Git::SVN::default_ref_id,
181 'svn-remote|remote|R=s' => sub {
182 $Git::SVN::no_reuse_existing = 1;
183 $Git::SVN::default_repo_id = $_[1] });
184 exit 1 if (!$rv && $cmd && $cmd ne 'log');
186 usage(0) if $_help;
187 version() if $_version;
188 usage(1) unless defined $cmd;
189 load_authors() if $_authors;
191 # make sure we're always running
192 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
193 unless (-d $ENV{GIT_DIR}) {
194 if ($git_dir_user_set) {
195 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
196 "but it is not a directory\n";
198 my $git_dir = delete $ENV{GIT_DIR};
199 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
200 unless (length $cdup) {
201 die "Already at toplevel, but $git_dir ",
202 "not found '$cdup'\n";
204 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
205 unless (-d $git_dir) {
206 die "$git_dir still not found after going to ",
207 "'$cdup'\n";
209 $ENV{GIT_DIR} = $git_dir;
212 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
213 Git::SVN::Migration::migration_check();
215 Git::SVN::init_vars();
216 eval {
217 Git::SVN::verify_remotes_sanity();
218 $cmd{$cmd}->[0]->(@ARGV);
220 fatal $@ if $@;
221 post_fetch_checkout();
222 exit 0;
224 ####################### primary functions ######################
225 sub usage {
226 my $exit = shift || 0;
227 my $fd = $exit ? \*STDERR : \*STDOUT;
228 print $fd <<"";
229 git-svn - bidirectional operations between a single Subversion tree and git
230 Usage: $0 <command> [options] [arguments]\n
232 print $fd "Available commands:\n" unless $cmd;
234 foreach (sort keys %cmd) {
235 next if $cmd && $cmd ne $_;
236 next if /^multi-/; # don't show deprecated commands
237 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
238 foreach (keys %{$cmd{$_}->[2]}) {
239 # mixed-case options are for .git/config only
240 next if /[A-Z]/ && /^[a-z]+$/i;
241 # prints out arguments as they should be passed:
242 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
243 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
244 "--$_" : "-$_" }
245 split /\|/,$_)," $x\n";
248 print $fd <<"";
249 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
250 arbitrary identifier if you're tracking multiple SVN branches/repositories in
251 one git repository and want to keep them separate. See git-svn(1) for more
252 information.
254 exit $exit;
257 sub version {
258 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
259 exit 0;
262 sub do_git_init_db {
263 unless (-d $ENV{GIT_DIR}) {
264 my @init_db = ('init');
265 push @init_db, "--template=$_template" if defined $_template;
266 if (defined $_shared) {
267 if ($_shared =~ /[a-z]/) {
268 push @init_db, "--shared=$_shared";
269 } else {
270 push @init_db, "--shared";
273 command_noisy(@init_db);
275 my $set;
276 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
277 foreach my $i (keys %icv) {
278 die "'$set' and '$i' cannot both be set\n" if $set;
279 next unless defined $icv{$i};
280 command_noisy('config', "$pfx.$i", $icv{$i});
281 $set = $i;
285 sub init_subdir {
286 my $repo_path = shift or return;
287 mkpath([$repo_path]) unless -d $repo_path;
288 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
289 $ENV{GIT_DIR} = '.git';
292 sub cmd_clone {
293 my ($url, $path) = @_;
294 if (!defined $path &&
295 (defined $_trunk || defined $_branches || defined $_tags) &&
296 $url !~ m#^[a-z\+]+://#) {
297 $path = $url;
299 $path = basename($url) if !defined $path || !length $path;
300 cmd_init($url, $path);
301 Git::SVN::fetch_all($Git::SVN::default_repo_id);
304 sub cmd_init {
305 if (defined $_trunk || defined $_branches || defined $_tags) {
306 return cmd_multi_init(@_);
308 my $url = shift or die "SVN repository location required ",
309 "as a command-line argument\n";
310 init_subdir(@_);
311 do_git_init_db();
313 Git::SVN->init($url);
316 sub cmd_fetch {
317 if (grep /^\d+=./, @_) {
318 die "'<rev>=<commit>' fetch arguments are ",
319 "no longer supported.\n";
321 my ($remote) = @_;
322 if (@_ > 1) {
323 die "Usage: $0 fetch [--all] [svn-remote]\n";
325 $remote ||= $Git::SVN::default_repo_id;
326 if ($_fetch_all) {
327 cmd_multi_fetch();
328 } else {
329 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
333 sub cmd_set_tree {
334 my (@commits) = @_;
335 if ($_stdin || !@commits) {
336 print "Reading from stdin...\n";
337 @commits = ();
338 while (<STDIN>) {
339 if (/\b($sha1_short)\b/o) {
340 unshift @commits, $1;
344 my @revs;
345 foreach my $c (@commits) {
346 my @tmp = command('rev-parse',$c);
347 if (scalar @tmp == 1) {
348 push @revs, $tmp[0];
349 } elsif (scalar @tmp > 1) {
350 push @revs, reverse(command('rev-list',@tmp));
351 } else {
352 fatal "Failed to rev-parse $c\n";
355 my $gs = Git::SVN->new;
356 my ($r_last, $cmt_last) = $gs->last_rev_commit;
357 $gs->fetch;
358 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
359 fatal "There are new revisions that were fetched ",
360 "and need to be merged (or acknowledged) ",
361 "before committing.\nlast rev: $r_last\n",
362 " current: $gs->{last_rev}\n";
364 $gs->set_tree($_) foreach @revs;
365 print "Done committing ",scalar @revs," revisions to SVN\n";
368 sub cmd_dcommit {
369 my $head = shift;
370 $head ||= 'HEAD';
371 my @refs;
372 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
373 unless ($gs) {
374 die "Unable to determine upstream SVN information from ",
375 "$head history\n";
377 my $last_rev;
378 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
379 foreach my $d (@$linear_refs) {
380 unless (defined $last_rev) {
381 (undef, $last_rev, undef) = cmt_metadata("$d~1");
382 unless (defined $last_rev) {
383 fatal "Unable to extract revision information ",
384 "from commit $d~1\n";
387 if ($_dry_run) {
388 print "diff-tree $d~1 $d\n";
389 } else {
390 my %ed_opts = ( r => $last_rev,
391 log => get_commit_entry($d)->{log},
392 ra => Git::SVN::Ra->new($gs->full_url),
393 tree_a => "$d~1",
394 tree_b => $d,
395 editor_cb => sub {
396 print "Committed r$_[0]\n";
397 $last_rev = $_[0]; },
398 svn_path => '');
399 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
400 print "No changes\n$d~1 == $d\n";
401 } elsif ($parents->{$d} && @{$parents->{$d}}) {
402 $gs->{inject_parents_dcommit}->{$last_rev} =
403 $parents->{$d};
407 return if $_dry_run;
408 unless ($gs) {
409 warn "Could not determine fetch information for $url\n",
410 "Will not attempt to fetch and rebase commits.\n",
411 "This probably means you have useSvmProps and should\n",
412 "now resync your SVN::Mirror repository.\n";
413 return;
415 $_fetch_all ? $gs->fetch_all : $gs->fetch;
416 unless ($_no_rebase) {
417 # we always want to rebase against the current HEAD, not any
418 # head that was passed to us
419 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
420 my @finish;
421 if (@diff) {
422 @finish = rebase_cmd();
423 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
424 "using @finish:\n", "@diff";
425 } else {
426 print "No changes between current HEAD and ",
427 $gs->refname, "\nResetting to the latest ",
428 $gs->refname, "\n";
429 @finish = qw/reset --mixed/;
431 command_noisy(@finish, $gs->refname);
435 sub cmd_find_rev {
436 my $revision_or_hash = shift;
437 my $result;
438 if ($revision_or_hash =~ /^r\d+$/) {
439 my $head = shift;
440 $head ||= 'HEAD';
441 my @refs;
442 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
443 unless ($gs) {
444 die "Unable to determine upstream SVN information from ",
445 "$head history\n";
447 my $desired_revision = substr($revision_or_hash, 1);
448 $result = $gs->rev_db_get($desired_revision);
449 } else {
450 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
451 $result = $rev;
453 print "$result\n" if $result;
456 sub cmd_rebase {
457 command_noisy(qw/update-index --refresh/);
458 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
459 unless ($gs) {
460 die "Unable to determine upstream SVN information from ",
461 "working tree history\n";
463 if (command(qw/diff-index HEAD --/)) {
464 print STDERR "Cannot rebase with uncommited changes:\n";
465 command_noisy('status');
466 exit 1;
468 unless ($_local) {
469 $_fetch_all ? $gs->fetch_all : $gs->fetch;
471 command_noisy(rebase_cmd(), $gs->refname);
474 sub cmd_show_ignore {
475 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
476 $gs ||= Git::SVN->new;
477 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
478 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
481 sub cmd_multi_init {
482 my $url = shift;
483 unless (defined $_trunk || defined $_branches || defined $_tags) {
484 usage(1);
487 # there are currently some bugs that prevent multi-init/multi-fetch
488 # setups from working well without this.
489 $Git::SVN::_minimize_url = 1;
491 $_prefix = '' unless defined $_prefix;
492 if (defined $url) {
493 $url =~ s#/+$##;
494 init_subdir(@_);
496 do_git_init_db();
497 if (defined $_trunk) {
498 my $trunk_ref = $_prefix . 'trunk';
499 # try both old-style and new-style lookups:
500 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
501 unless ($gs_trunk) {
502 my ($trunk_url, $trunk_path) =
503 complete_svn_url($url, $_trunk);
504 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
505 undef, $trunk_ref);
508 return unless defined $_branches || defined $_tags;
509 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
510 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
511 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
514 sub cmd_multi_fetch {
515 my $remotes = Git::SVN::read_all_remotes();
516 foreach my $repo_id (sort keys %$remotes) {
517 if ($remotes->{$repo_id}->{url}) {
518 Git::SVN::fetch_all($repo_id, $remotes);
523 # this command is special because it requires no metadata
524 sub cmd_commit_diff {
525 my ($ta, $tb, $url) = @_;
526 my $usage = "Usage: $0 commit-diff -r<revision> ".
527 "<tree-ish> <tree-ish> [<URL>]\n";
528 fatal($usage) if (!defined $ta || !defined $tb);
529 my $svn_path;
530 if (!defined $url) {
531 my $gs = eval { Git::SVN->new };
532 if (!$gs) {
533 fatal("Needed URL or usable git-svn --id in ",
534 "the command-line\n", $usage);
536 $url = $gs->{url};
537 $svn_path = $gs->{path};
539 unless (defined $_revision) {
540 fatal("-r|--revision is a required argument\n", $usage);
542 if (defined $_message && defined $_file) {
543 fatal("Both --message/-m and --file/-F specified ",
544 "for the commit message.\n",
545 "I have no idea what you mean\n");
547 if (defined $_file) {
548 $_message = file_to_s($_file);
549 } else {
550 $_message ||= get_commit_entry($tb)->{log};
552 my $ra ||= Git::SVN::Ra->new($url);
553 $svn_path ||= $ra->{svn_path};
554 my $r = $_revision;
555 if ($r eq 'HEAD') {
556 $r = $ra->get_latest_revnum;
557 } elsif ($r !~ /^\d+$/) {
558 die "revision argument: $r not understood by git-svn\n";
560 my %ed_opts = ( r => $r,
561 log => $_message,
562 ra => $ra,
563 tree_a => $ta,
564 tree_b => $tb,
565 editor_cb => sub { print "Committed r$_[0]\n" },
566 svn_path => $svn_path );
567 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
568 print "No changes\n$ta == $tb\n";
572 ########################### utility functions #########################
574 sub rebase_cmd {
575 my @cmd = qw/rebase/;
576 push @cmd, '-v' if $_verbose;
577 push @cmd, qw/--merge/ if $_merge;
578 push @cmd, "--strategy=$_strategy" if $_strategy;
579 @cmd;
582 sub post_fetch_checkout {
583 return if $_no_checkout;
584 my $gs = $Git::SVN::_head or return;
585 return if verify_ref('refs/heads/master^0');
587 my $valid_head = verify_ref('HEAD^0');
588 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
589 return if ($valid_head || !verify_ref('HEAD^0'));
591 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
592 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
593 return if -f $index;
595 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
596 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
597 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
598 print STDERR "Checked out HEAD:\n ",
599 $gs->full_url, " r", $gs->last_rev, "\n";
602 sub complete_svn_url {
603 my ($url, $path) = @_;
604 $path =~ s#/+$##;
605 if ($path !~ m#^[a-z\+]+://#) {
606 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
607 fatal("E: '$path' is not a complete URL ",
608 "and a separate URL is not specified\n");
610 return ($url, $path);
612 return ($path, '');
615 sub complete_url_ls_init {
616 my ($ra, $repo_path, $switch, $pfx) = @_;
617 unless ($repo_path) {
618 print STDERR "W: $switch not specified\n";
619 return;
621 $repo_path =~ s#/+$##;
622 if ($repo_path =~ m#^[a-z\+]+://#) {
623 $ra = Git::SVN::Ra->new($repo_path);
624 $repo_path = '';
625 } else {
626 $repo_path =~ s#^/+##;
627 unless ($ra) {
628 fatal("E: '$repo_path' is not a complete URL ",
629 "and a separate URL is not specified\n");
632 my $url = $ra->{url};
633 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
634 my $k = "svn-remote.$gs->{repo_id}.url";
635 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
636 if ($orig_url && ($orig_url ne $gs->{url})) {
637 die "$k already set: $orig_url\n",
638 "wanted to set to: $gs->{url}\n";
640 command_oneline('config', $k, $gs->{url}) unless $orig_url;
641 my $remote_path = "$ra->{svn_path}/$repo_path/*";
642 $remote_path =~ s#/+#/#g;
643 $remote_path =~ s#^/##g;
644 my ($n) = ($switch =~ /^--(\w+)/);
645 if (length $pfx && $pfx !~ m#/$#) {
646 die "--prefix='$pfx' must have a trailing slash '/'\n";
648 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
649 "$remote_path:refs/remotes/$pfx*");
652 sub verify_ref {
653 my ($ref) = @_;
654 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
655 { STDERR => 0 }); };
658 sub get_tree_from_treeish {
659 my ($treeish) = @_;
660 # $treeish can be a symbolic ref, too:
661 my $type = command_oneline(qw/cat-file -t/, $treeish);
662 my $expected;
663 while ($type eq 'tag') {
664 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
666 if ($type eq 'commit') {
667 $expected = (grep /^tree /, command(qw/cat-file commit/,
668 $treeish))[0];
669 ($expected) = ($expected =~ /^tree ($sha1)$/o);
670 die "Unable to get tree from $treeish\n" unless $expected;
671 } elsif ($type eq 'tree') {
672 $expected = $treeish;
673 } else {
674 die "$treeish is a $type, expected tree, tag or commit\n";
676 return $expected;
679 sub get_commit_entry {
680 my ($treeish) = shift;
681 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
682 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
683 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
684 open my $log_fh, '>', $commit_editmsg or croak $!;
686 my $type = command_oneline(qw/cat-file -t/, $treeish);
687 if ($type eq 'commit' || $type eq 'tag') {
688 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
689 $type, $treeish);
690 my $in_msg = 0;
691 while (<$msg_fh>) {
692 if (!$in_msg) {
693 $in_msg = 1 if (/^\s*$/);
694 } elsif (/^git-svn-id: /) {
695 # skip this for now, we regenerate the
696 # correct one on re-fetch anyways
697 # TODO: set *:merge properties or like...
698 } else {
699 print $log_fh $_ or croak $!;
702 command_close_pipe($msg_fh, $ctx);
704 close $log_fh or croak $!;
706 if ($_edit || ($type eq 'tree')) {
707 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
708 # TODO: strip out spaces, comments, like git-commit.sh
709 system($editor, $commit_editmsg);
711 rename $commit_editmsg, $commit_msg or croak $!;
712 open $log_fh, '<', $commit_msg or croak $!;
713 { local $/; chomp($log_entry{log} = <$log_fh>); }
714 close $log_fh or croak $!;
715 unlink $commit_msg;
716 \%log_entry;
719 sub s_to_file {
720 my ($str, $file, $mode) = @_;
721 open my $fd,'>',$file or croak $!;
722 print $fd $str,"\n" or croak $!;
723 close $fd or croak $!;
724 chmod ($mode &~ umask, $file) if (defined $mode);
727 sub file_to_s {
728 my $file = shift;
729 open my $fd,'<',$file or croak "$!: file: $file\n";
730 local $/;
731 my $ret = <$fd>;
732 close $fd or croak $!;
733 $ret =~ s/\s*$//s;
734 return $ret;
737 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
738 sub load_authors {
739 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
740 my $log = $cmd eq 'log';
741 while (<$authors>) {
742 chomp;
743 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
744 my ($user, $name, $email) = ($1, $2, $3);
745 if ($log) {
746 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
747 } else {
748 $users{$user} = [$name, $email];
751 close $authors or croak $!;
754 # convert GetOpt::Long specs for use by git-config
755 sub read_repo_config {
756 return unless -d $ENV{GIT_DIR};
757 my $opts = shift;
758 my @config_only;
759 foreach my $o (keys %$opts) {
760 # if we have mixedCase and a long option-only, then
761 # it's a config-only variable that we don't need for
762 # the command-line.
763 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
764 my $v = $opts->{$o};
765 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
766 $key =~ s/-//g;
767 my $arg = 'git-config';
768 $arg .= ' --int' if ($o =~ /[:=]i$/);
769 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
770 if (ref $v eq 'ARRAY') {
771 chomp(my @tmp = `$arg --get-all svn.$key`);
772 @$v = @tmp if @tmp;
773 } else {
774 chomp(my $tmp = `$arg --get svn.$key`);
775 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
776 $$v = $tmp;
780 delete @$opts{@config_only} if @config_only;
783 sub extract_metadata {
784 my $id = shift or return (undef, undef, undef);
785 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
786 \s([a-f\d\-]+)$/x);
787 if (!defined $rev || !$uuid || !$url) {
788 # some of the original repositories I made had
789 # identifiers like this:
790 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
792 return ($url, $rev, $uuid);
795 sub cmt_metadata {
796 return extract_metadata((grep(/^git-svn-id: /,
797 command(qw/cat-file commit/, shift)))[-1]);
800 sub working_head_info {
801 my ($head, $refs) = @_;
802 my ($fh, $ctx) = command_output_pipe('log', $head);
803 my $hash;
804 my %max;
805 while (<$fh>) {
806 if ( m{^commit ($::sha1)$} ) {
807 unshift @$refs, $hash if $hash and $refs;
808 $hash = $1;
809 next;
811 next unless s{^\s*(git-svn-id:)}{$1};
812 my ($url, $rev, $uuid) = extract_metadata($_);
813 if (defined $url && defined $rev) {
814 next if $max{$url} and $max{$url} < $rev;
815 if (my $gs = Git::SVN->find_by_url($url)) {
816 my $c = $gs->rev_db_get($rev);
817 if ($c && $c eq $hash) {
818 close $fh; # break the pipe
819 return ($url, $rev, $uuid, $gs);
820 } else {
821 $max{$url} ||= $gs->rev_db_max;
826 command_close_pipe($fh, $ctx);
827 (undef, undef, undef, undef);
830 sub read_commit_parents {
831 my ($parents, $c) = @_;
832 my ($fh, $ctx) = command_output_pipe(qw/cat-file commit/, $c);
833 while (<$fh>) {
834 chomp;
835 last if '';
836 /^parent ($sha1)/ or next;
837 push @{$parents->{$c}}, $1;
839 close $fh; # break the pipe
842 sub linearize_history {
843 my ($gs, $refs) = @_;
844 my %parents;
845 foreach my $c (@$refs) {
846 read_commit_parents(\%parents, $c);
849 my @linear_refs;
850 my %skip = ();
851 my $last_svn_commit = $gs->last_commit;
852 foreach my $c (reverse @$refs) {
853 next if $c eq $last_svn_commit;
854 last if $skip{$c};
856 unshift @linear_refs, $c;
857 $skip{$c} = 1;
859 # we only want the first parent to diff against for linear
860 # history, we save the rest to inject when we finalize the
861 # svn commit
862 my $fp_a = verify_ref("$c~1");
863 my $fp_b = shift @{$parents{$c}} if $parents{$c};
864 if (!$fp_a || !$fp_b) {
865 die "Commit $c\n",
866 "has no parent commit, and therefore ",
867 "nothing to diff against.\n",
868 "You should be working from a repository ",
869 "originally created by git-svn\n";
871 if ($fp_a ne $fp_b) {
872 die "$c~1 = $fp_a, however parsing commit $c ",
873 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
876 foreach my $p (@{$parents{$c}}) {
877 $skip{$p} = 1;
880 (\@linear_refs, \%parents);
883 package Git::SVN;
884 use strict;
885 use warnings;
886 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
887 $_repack $_repack_flags $_use_svm_props $_head
888 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
889 use Carp qw/croak/;
890 use File::Path qw/mkpath/;
891 use File::Copy qw/copy/;
892 use IPC::Open3;
894 my $_repack_nr;
895 # properties that we do not log:
896 my %SKIP_PROP;
897 BEGIN {
898 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
899 svn:special svn:executable
900 svn:entry:committed-rev
901 svn:entry:last-author
902 svn:entry:uuid
903 svn:entry:committed-date/;
905 # some options are read globally, but can be overridden locally
906 # per [svn-remote "..."] section. Command-line options will *NOT*
907 # override options set in an [svn-remote "..."] section
908 no strict 'refs';
909 for my $option (qw/follow_parent no_metadata use_svm_props
910 use_svnsync_props/) {
911 my $key = $option;
912 $key =~ tr/_//d;
913 my $prop = "-$option";
914 *$option = sub {
915 my ($self) = @_;
916 return $self->{$prop} if exists $self->{$prop};
917 my $k = "svn-remote.$self->{repo_id}.$key";
918 eval { command_oneline(qw/config --get/, $k) };
919 if ($@) {
920 $self->{$prop} = ${"Git::SVN::_$option"};
921 } else {
922 my $v = command_oneline(qw/config --bool/,$k);
923 $self->{$prop} = $v eq 'false' ? 0 : 1;
925 return $self->{$prop};
930 my %LOCKFILES;
931 END { unlink keys %LOCKFILES if %LOCKFILES }
933 sub resolve_local_globs {
934 my ($url, $fetch, $glob_spec) = @_;
935 return unless defined $glob_spec;
936 my $ref = $glob_spec->{ref};
937 my $path = $glob_spec->{path};
938 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
939 next unless m#^refs/remotes/$ref->{regex}$#;
940 my $p = $1;
941 my $pathname = $path->full_path($p);
942 my $refname = $ref->full_path($p);
943 if (my $existing = $fetch->{$pathname}) {
944 if ($existing ne $refname) {
945 die "Refspec conflict:\n",
946 "existing: refs/remotes/$existing\n",
947 " globbed: refs/remotes/$refname\n";
949 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
950 $u =~ s!^\Q$url\E(/|$)!! or die
951 "refs/remotes/$refname: '$url' not found in '$u'\n";
952 if ($pathname ne $u) {
953 warn "W: Refspec glob conflict ",
954 "(ref: refs/remotes/$refname):\n",
955 "expected path: $pathname\n",
956 " real path: $u\n",
957 "Continuing ahead with $u\n";
958 next;
960 } else {
961 $fetch->{$pathname} = $refname;
966 sub parse_revision_argument {
967 my ($base, $head) = @_;
968 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
969 return ($base, $head);
971 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
972 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
973 return ($head, $head) if ($::_revision eq 'HEAD');
974 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
975 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
976 die "revision argument: $::_revision not understood by git-svn\n";
979 sub fetch_all {
980 my ($repo_id, $remotes) = @_;
981 if (ref $repo_id) {
982 my $gs = $repo_id;
983 $repo_id = undef;
984 $repo_id = $gs->{repo_id};
986 $remotes ||= read_all_remotes();
987 my $remote = $remotes->{$repo_id} or
988 die "[svn-remote \"$repo_id\"] unknown\n";
989 my $fetch = $remote->{fetch};
990 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
991 my (@gs, @globs);
992 my $ra = Git::SVN::Ra->new($url);
993 my $uuid = $ra->get_uuid;
994 my $head = $ra->get_latest_revnum;
995 my $base = defined $fetch ? $head : 0;
997 # read the max revs for wildcard expansion (branches/*, tags/*)
998 foreach my $t (qw/branches tags/) {
999 defined $remote->{$t} or next;
1000 push @globs, $remote->{$t};
1001 my $max_rev = eval { tmp_config(qw/--int --get/,
1002 "svn-remote.$repo_id.${t}-maxRev") };
1003 if (defined $max_rev && ($max_rev < $base)) {
1004 $base = $max_rev;
1005 } elsif (!defined $max_rev) {
1006 $base = 0;
1010 if ($fetch) {
1011 foreach my $p (sort keys %$fetch) {
1012 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1013 my $lr = $gs->rev_db_max;
1014 if (defined $lr) {
1015 $base = $lr if ($lr < $base);
1017 push @gs, $gs;
1021 ($base, $head) = parse_revision_argument($base, $head);
1022 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1025 sub read_all_remotes {
1026 my $r = {};
1027 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1028 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1029 $r->{$1}->{fetch}->{$2} = $3;
1030 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1031 $r->{$1}->{url} = $2;
1032 } elsif (m!^(.+)\.(branches|tags)=
1033 (.*):refs/remotes/(.+)\s*$/!x) {
1034 my ($p, $g) = ($3, $4);
1035 my $rs = $r->{$1}->{$2} = {
1036 t => $2,
1037 remote => $1,
1038 path => Git::SVN::GlobSpec->new($p),
1039 ref => Git::SVN::GlobSpec->new($g) };
1040 if (length($rs->{ref}->{right}) != 0) {
1041 die "The '*' glob character must be the last ",
1042 "character of '$g'\n";
1049 sub init_vars {
1050 if (defined $_repack) {
1051 $_repack = 1000 if ($_repack <= 0);
1052 $_repack_nr = $_repack;
1053 $_repack_flags ||= '-d';
1057 sub verify_remotes_sanity {
1058 return unless -d $ENV{GIT_DIR};
1059 my %seen;
1060 foreach (command(qw/config -l/)) {
1061 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1062 if ($seen{$1}) {
1063 die "Remote ref refs/remote/$1 is tracked by",
1064 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1065 "Please resolve this ambiguity in ",
1066 "your git configuration file before ",
1067 "continuing\n";
1069 $seen{$1} = $_;
1074 # we allow more chars than remotes2config.sh...
1075 sub sanitize_remote_name {
1076 my ($name) = @_;
1077 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1078 $name;
1081 sub find_existing_remote {
1082 my ($url, $remotes) = @_;
1083 return undef if $no_reuse_existing;
1084 my $existing;
1085 foreach my $repo_id (keys %$remotes) {
1086 my $u = $remotes->{$repo_id}->{url} or next;
1087 next if $u ne $url;
1088 $existing = $repo_id;
1089 last;
1091 $existing;
1094 sub init_remote_config {
1095 my ($self, $url, $no_write) = @_;
1096 $url =~ s!/+$!!; # strip trailing slash
1097 my $r = read_all_remotes();
1098 my $existing = find_existing_remote($url, $r);
1099 if ($existing) {
1100 unless ($no_write) {
1101 print STDERR "Using existing ",
1102 "[svn-remote \"$existing\"]\n";
1104 $self->{repo_id} = $existing;
1105 } elsif ($_minimize_url) {
1106 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1107 $existing = find_existing_remote($min_url, $r);
1108 if ($existing) {
1109 unless ($no_write) {
1110 print STDERR "Using existing ",
1111 "[svn-remote \"$existing\"]\n";
1113 $self->{repo_id} = $existing;
1115 if ($min_url ne $url) {
1116 unless ($no_write) {
1117 print STDERR "Using higher level of URL: ",
1118 "$url => $min_url\n";
1120 my $old_path = $self->{path};
1121 $self->{path} = $url;
1122 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1123 if (length $old_path) {
1124 $self->{path} .= "/$old_path";
1126 $url = $min_url;
1129 my $orig_url;
1130 if (!$existing) {
1131 # verify that we aren't overwriting anything:
1132 $orig_url = eval {
1133 command_oneline('config', '--get',
1134 "svn-remote.$self->{repo_id}.url")
1136 if ($orig_url && ($orig_url ne $url)) {
1137 die "svn-remote.$self->{repo_id}.url already set: ",
1138 "$orig_url\nwanted to set to: $url\n";
1141 my ($xrepo_id, $xpath) = find_ref($self->refname);
1142 if (defined $xpath) {
1143 die "svn-remote.$xrepo_id.fetch already set to track ",
1144 "$xpath:refs/remotes/", $self->refname, "\n";
1146 unless ($no_write) {
1147 command_noisy('config',
1148 "svn-remote.$self->{repo_id}.url", $url);
1149 command_noisy('config', '--add',
1150 "svn-remote.$self->{repo_id}.fetch",
1151 "$self->{path}:".$self->refname);
1153 $self->{url} = $url;
1156 sub find_by_url { # repos_root and, path are optional
1157 my ($class, $full_url, $repos_root, $path) = @_;
1159 return undef unless defined $full_url;
1160 remove_username($full_url);
1161 remove_username($repos_root) if defined $repos_root;
1162 my $remotes = read_all_remotes();
1163 if (defined $full_url && defined $repos_root && !defined $path) {
1164 $path = $full_url;
1165 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1167 foreach my $repo_id (keys %$remotes) {
1168 my $u = $remotes->{$repo_id}->{url} or next;
1169 remove_username($u);
1170 next if defined $repos_root && $repos_root ne $u;
1172 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1173 foreach (qw/branches tags/) {
1174 resolve_local_globs($u, $fetch,
1175 $remotes->{$repo_id}->{$_});
1177 my $p = $path;
1178 unless (defined $p) {
1179 $p = $full_url;
1180 $p =~ s#^\Q$u\E(?:/|$)## or next;
1182 foreach my $f (keys %$fetch) {
1183 next if $f ne $p;
1184 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1187 undef;
1190 sub init {
1191 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1192 my $self = _new($class, $repo_id, $ref_id, $path);
1193 if (defined $url) {
1194 $self->init_remote_config($url, $no_write);
1196 $self;
1199 sub find_ref {
1200 my ($ref_id) = @_;
1201 foreach (command(qw/config -l/)) {
1202 next unless m!^svn-remote\.(.+)\.fetch=
1203 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1204 my ($repo_id, $path, $ref) = ($1, $2, $3);
1205 if ($ref eq $ref_id) {
1206 $path = '' if ($path =~ m#^\./?#);
1207 return ($repo_id, $path);
1210 (undef, undef, undef);
1213 sub new {
1214 my ($class, $ref_id, $repo_id, $path) = @_;
1215 if (defined $ref_id && !defined $repo_id && !defined $path) {
1216 ($repo_id, $path) = find_ref($ref_id);
1217 if (!defined $repo_id) {
1218 die "Could not find a \"svn-remote.*.fetch\" key ",
1219 "in the repository configuration matching: ",
1220 "refs/remotes/$ref_id\n";
1223 my $self = _new($class, $repo_id, $ref_id, $path);
1224 if (!defined $self->{path} || !length $self->{path}) {
1225 my $fetch = command_oneline('config', '--get',
1226 "svn-remote.$repo_id.fetch",
1227 ":refs/remotes/$ref_id\$") or
1228 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1229 "\":refs/remotes/$ref_id\$\" in config\n";
1230 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1232 $self->{url} = command_oneline('config', '--get',
1233 "svn-remote.$repo_id.url") or
1234 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1235 $self->rebuild;
1236 $self;
1239 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1241 sub svm_uuid {
1242 my ($self) = @_;
1243 return $self->{svm}->{uuid} if $self->svm;
1244 $self->ra;
1245 unless ($self->{svm}) {
1246 die "SVM UUID not cached, and reading remotely failed\n";
1248 $self->{svm}->{uuid};
1251 sub svm {
1252 my ($self) = @_;
1253 return $self->{svm} if $self->{svm};
1254 my $svm;
1255 # see if we have it in our config, first:
1256 eval {
1257 my $section = "svn-remote.$self->{repo_id}";
1258 $svm = {
1259 source => tmp_config('--get', "$section.svm-source"),
1260 uuid => tmp_config('--get', "$section.svm-uuid"),
1261 replace => tmp_config('--get', "$section.svm-replace"),
1264 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1265 $self->{svm} = $svm;
1267 $self->{svm};
1270 sub _set_svm_vars {
1271 my ($self, $ra) = @_;
1272 return $ra if $self->svm;
1274 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1275 "(svm:source, svm:uuid) ",
1276 "from the following URLs:\n" );
1277 sub read_svm_props {
1278 my ($self, $ra, $path, $r) = @_;
1279 my $props = ($ra->get_dir($path, $r))[2];
1280 my $src = $props->{'svm:source'};
1281 my $uuid = $props->{'svm:uuid'};
1282 return undef if (!$src || !$uuid);
1284 chomp($src, $uuid);
1286 $uuid =~ m{^[0-9a-f\-]{30,}$}
1287 or die "doesn't look right - svm:uuid is '$uuid'\n";
1289 # the '!' is used to mark the repos_root!/relative/path
1290 $src =~ s{/?!/?}{/};
1291 $src =~ s{/+$}{}; # no trailing slashes please
1292 # username is of no interest
1293 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1295 my $replace = $ra->{url};
1296 $replace .= "/$path" if length $path;
1298 my $section = "svn-remote.$self->{repo_id}";
1299 tmp_config("$section.svm-source", $src);
1300 tmp_config("$section.svm-replace", $replace);
1301 tmp_config("$section.svm-uuid", $uuid);
1302 $self->{svm} = {
1303 source => $src,
1304 uuid => $uuid,
1305 replace => $replace
1309 my $r = $ra->get_latest_revnum;
1310 my $path = $self->{path};
1311 my %tried;
1312 while (length $path) {
1313 unless ($tried{"$self->{url}/$path"}) {
1314 return $ra if $self->read_svm_props($ra, $path, $r);
1315 $tried{"$self->{url}/$path"} = 1;
1317 $path =~ s#/?[^/]+$##;
1319 die "Path: '$path' should be ''\n" if $path ne '';
1320 return $ra if $self->read_svm_props($ra, $path, $r);
1321 $tried{"$self->{url}/$path"} = 1;
1323 if ($ra->{repos_root} eq $self->{url}) {
1324 die @err, (map { " $_\n" } keys %tried), "\n";
1327 # nope, make sure we're connected to the repository root:
1328 my $ok;
1329 my @tried_b;
1330 $path = $ra->{svn_path};
1331 $ra = Git::SVN::Ra->new($ra->{repos_root});
1332 while (length $path) {
1333 unless ($tried{"$ra->{url}/$path"}) {
1334 $ok = $self->read_svm_props($ra, $path, $r);
1335 last if $ok;
1336 $tried{"$ra->{url}/$path"} = 1;
1338 $path =~ s#/?[^/]+$##;
1340 die "Path: '$path' should be ''\n" if $path ne '';
1341 $ok ||= $self->read_svm_props($ra, $path, $r);
1342 $tried{"$ra->{url}/$path"} = 1;
1343 if (!$ok) {
1344 die @err, (map { " $_\n" } keys %tried), "\n";
1346 Git::SVN::Ra->new($self->{url});
1349 sub svnsync {
1350 my ($self) = @_;
1351 return $self->{svnsync} if $self->{svnsync};
1353 if ($self->no_metadata) {
1354 die "Can't have both 'noMetadata' and ",
1355 "'useSvnsyncProps' options set!\n";
1357 if ($self->rewrite_root) {
1358 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1359 "options set!\n";
1362 my $svnsync;
1363 # see if we have it in our config, first:
1364 eval {
1365 my $section = "svn-remote.$self->{repo_id}";
1366 $svnsync = {
1367 url => tmp_config('--get', "$section.svnsync-url"),
1368 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1371 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1372 return $self->{svnsync} = $svnsync;
1375 my $err = "useSvnsyncProps set, but failed to read " .
1376 "svnsync property: svn:sync-from-";
1377 my $rp = $self->ra->rev_proplist(0);
1379 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1380 $url =~ m{^[a-z\+]+://} or
1381 die "doesn't look right - svn:sync-from-url is '$url'\n";
1383 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1384 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1385 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1387 my $section = "svn-remote.$self->{repo_id}";
1388 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1389 tmp_config('--add', "$section.svnsync-url", $url);
1390 return $self->{svnsync} = { url => $url, uuid => $uuid };
1393 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1394 # remote lookup (useful for 'git svn log').
1395 sub ra_uuid {
1396 my ($self) = @_;
1397 unless ($self->{ra_uuid}) {
1398 my $key = "svn-remote.$self->{repo_id}.uuid";
1399 my $uuid = eval { tmp_config('--get', $key) };
1400 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1401 $self->{ra_uuid} = $uuid;
1402 } else {
1403 die "ra_uuid called without URL\n" unless $self->{url};
1404 $self->{ra_uuid} = $self->ra->get_uuid;
1405 tmp_config('--add', $key, $self->{ra_uuid});
1408 $self->{ra_uuid};
1411 sub ra {
1412 my ($self) = shift;
1413 my $ra = Git::SVN::Ra->new($self->{url});
1414 if ($self->use_svm_props && !$self->{svm}) {
1415 if ($self->no_metadata) {
1416 die "Can't have both 'noMetadata' and ",
1417 "'useSvmProps' options set!\n";
1418 } elsif ($self->use_svnsync_props) {
1419 die "Can't have both 'useSvnsyncProps' and ",
1420 "'useSvmProps' options set!\n";
1422 $ra = $self->_set_svm_vars($ra);
1423 $self->{-want_revprops} = 1;
1425 $ra;
1428 sub rel_path {
1429 my ($self) = @_;
1430 my $repos_root = $self->ra->{repos_root};
1431 return $self->{path} if ($self->{url} eq $repos_root);
1432 my $url = $self->{url} .
1433 (length $self->{path} ? "/$self->{path}" : $self->{path});
1434 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1435 $url;
1438 sub traverse_ignore {
1439 my ($self, $fh, $path, $r) = @_;
1440 $path =~ s#^/+##g;
1441 my $ra = $self->ra;
1442 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1443 my $p = $path;
1444 $p =~ s#^\Q$self->{path}\E(/|$)##;
1445 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1446 if (my $s = $props->{'svn:ignore'}) {
1447 $s =~ s/[\r\n]+/\n/g;
1448 chomp $s;
1449 if (length $p == 0) {
1450 $s =~ s#\n#\n/$p#g;
1451 print $fh "/$s\n";
1452 } else {
1453 $s =~ s#\n#\n/$p/#g;
1454 print $fh "/$p/$s\n";
1457 foreach (sort keys %$dirent) {
1458 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1459 $self->traverse_ignore($fh, "$path/$_", $r);
1463 sub last_rev { ($_[0]->last_rev_commit)[0] }
1464 sub last_commit { ($_[0]->last_rev_commit)[1] }
1466 # returns the newest SVN revision number and newest commit SHA1
1467 sub last_rev_commit {
1468 my ($self) = @_;
1469 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1470 return ($self->{last_rev}, $self->{last_commit});
1472 my $c = ::verify_ref($self->refname.'^0');
1473 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1474 my $rev = (::cmt_metadata($c))[1];
1475 if (defined $rev) {
1476 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1477 return ($rev, $c);
1480 my $db_path = $self->db_path;
1481 unless (-e $db_path) {
1482 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1483 return (undef, undef);
1485 my $offset = -41; # from tail
1486 my $rl;
1487 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1488 sysseek($fh, $offset, 2); # don't care for errors
1489 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1490 chomp $rl;
1491 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1492 $offset -= 41;
1493 sysseek($fh, $offset, 2); # don't care for errors
1494 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1495 chomp $rl;
1497 if ($c && $c ne $rl) {
1498 die "$db_path and ", $self->refname,
1499 " inconsistent!:\n$c != $rl\n";
1501 my $rev = sysseek($fh, 0, 1) or croak $!;
1502 $rev = ($rev - 41) / 41;
1503 close $fh or croak $!;
1504 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1505 return ($rev, $c);
1508 sub get_fetch_range {
1509 my ($self, $min, $max) = @_;
1510 $max ||= $self->ra->get_latest_revnum;
1511 $min ||= $self->rev_db_max;
1512 (++$min, $max);
1515 sub tmp_config {
1516 my (@args) = @_;
1517 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1518 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1519 if (! -f $config && -f $old_def_config) {
1520 rename $old_def_config, $config or
1521 die "Failed rename $old_def_config => $config: $!\n";
1523 my $old_config = $ENV{GIT_CONFIG};
1524 $ENV{GIT_CONFIG} = $config;
1525 $@ = undef;
1526 my @ret = eval {
1527 unless (-f $config) {
1528 mkfile($config);
1529 open my $fh, '>', $config or
1530 die "Can't open $config: $!\n";
1531 print $fh "; This file is used internally by ",
1532 "git-svn\n" or die
1533 "Couldn't write to $config: $!\n";
1534 print $fh "; You should not have to edit it\n" or
1535 die "Couldn't write to $config: $!\n";
1536 close $fh or die "Couldn't close $config: $!\n";
1538 command('config', @args);
1540 my $err = $@;
1541 if (defined $old_config) {
1542 $ENV{GIT_CONFIG} = $old_config;
1543 } else {
1544 delete $ENV{GIT_CONFIG};
1546 die $err if $err;
1547 wantarray ? @ret : $ret[0];
1550 sub tmp_index_do {
1551 my ($self, $sub) = @_;
1552 my $old_index = $ENV{GIT_INDEX_FILE};
1553 $ENV{GIT_INDEX_FILE} = $self->{index};
1554 $@ = undef;
1555 my @ret = eval {
1556 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1557 mkpath([$dir]) unless -d $dir;
1558 &$sub;
1560 my $err = $@;
1561 if (defined $old_index) {
1562 $ENV{GIT_INDEX_FILE} = $old_index;
1563 } else {
1564 delete $ENV{GIT_INDEX_FILE};
1566 die $err if $err;
1567 wantarray ? @ret : $ret[0];
1570 sub assert_index_clean {
1571 my ($self, $treeish) = @_;
1573 $self->tmp_index_do(sub {
1574 command_noisy('read-tree', $treeish) unless -e $self->{index};
1575 my $x = command_oneline('write-tree');
1576 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1577 /^tree ($::sha1)/mo);
1578 return if $y eq $x;
1580 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1581 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1582 command_noisy('read-tree', $treeish);
1583 $x = command_oneline('write-tree');
1584 if ($y ne $x) {
1585 ::fatal "trees ($treeish) $y != $x\n",
1586 "Something is seriously wrong...\n";
1591 sub get_commit_parents {
1592 my ($self, $log_entry) = @_;
1593 my (%seen, @ret, @tmp);
1594 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1595 if (my $ip = $self->{inject_parents}) {
1596 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1597 push @tmp, $commit;
1600 if (my $cur = ::verify_ref($self->refname.'^0')) {
1601 push @tmp, $cur;
1603 if (my $ipd = $self->{inject_parents_dcommit}) {
1604 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1605 push @tmp, @$commit;
1608 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1609 while (my $p = shift @tmp) {
1610 next if $seen{$p};
1611 $seen{$p} = 1;
1612 push @ret, $p;
1613 # MAXPARENT is defined to 16 in commit-tree.c:
1614 last if @ret >= 16;
1616 if (@tmp) {
1617 die "r$log_entry->{revision}: No room for parents:\n\t",
1618 join("\n\t", @tmp), "\n";
1620 @ret;
1623 sub rewrite_root {
1624 my ($self) = @_;
1625 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1626 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1627 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1628 if ($rwr) {
1629 $rwr =~ s#/+$##;
1630 if ($rwr !~ m#^[a-z\+]+://#) {
1631 die "$rwr is not a valid URL (key: $k)\n";
1634 $self->{-rewrite_root} = $rwr;
1637 sub metadata_url {
1638 my ($self) = @_;
1639 ($self->rewrite_root || $self->{url}) .
1640 (length $self->{path} ? '/' . $self->{path} : '');
1643 sub full_url {
1644 my ($self) = @_;
1645 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1648 sub do_git_commit {
1649 my ($self, $log_entry) = @_;
1650 my $lr = $self->last_rev;
1651 if (defined $lr && $lr >= $log_entry->{revision}) {
1652 die "Last fetched revision of ", $self->refname,
1653 " was r$lr, but we are about to fetch: ",
1654 "r$log_entry->{revision}!\n";
1656 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1657 croak "$log_entry->{revision} = $c already exists! ",
1658 "Why are we refetching it?\n";
1660 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1661 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1662 $log_entry->{email};
1663 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1665 my $tree = $log_entry->{tree};
1666 if (!defined $tree) {
1667 $tree = $self->tmp_index_do(sub {
1668 command_oneline('write-tree') });
1670 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1672 my @exec = ('git-commit-tree', $tree);
1673 foreach ($self->get_commit_parents($log_entry)) {
1674 push @exec, '-p', $_;
1676 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1677 or croak $!;
1678 print $msg_fh $log_entry->{log} or croak $!;
1679 unless ($self->no_metadata) {
1680 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1681 or croak $!;
1683 $msg_fh->flush == 0 or croak $!;
1684 close $msg_fh or croak $!;
1685 chomp(my $commit = do { local $/; <$out_fh> });
1686 close $out_fh or croak $!;
1687 waitpid $pid, 0;
1688 croak $? if $?;
1689 if ($commit !~ /^$::sha1$/o) {
1690 die "Failed to commit, invalid sha1: $commit\n";
1693 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1695 $self->{last_rev} = $log_entry->{revision};
1696 $self->{last_commit} = $commit;
1697 print "r$log_entry->{revision}";
1698 if (defined $log_entry->{svm_revision}) {
1699 print " (\@$log_entry->{svm_revision})";
1700 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1701 0, $self->svm_uuid);
1703 print " = $commit ($self->{ref_id})\n";
1704 if (defined $_repack && (--$_repack_nr == 0)) {
1705 $_repack_nr = $_repack;
1706 # repack doesn't use any arguments with spaces in them, does it?
1707 print "Running git repack $_repack_flags ...\n";
1708 command_noisy('repack', split(/\s+/, $_repack_flags));
1709 print "Done repacking\n";
1711 return $commit;
1714 sub match_paths {
1715 my ($self, $paths, $r) = @_;
1716 return 1 if $self->{path} eq '';
1717 if (my $path = $paths->{"/$self->{path}"}) {
1718 return ($path->{action} eq 'D') ? 0 : 1;
1720 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1721 if (grep /$self->{path_regex}/, keys %$paths) {
1722 return 1;
1724 my $c = '';
1725 foreach (split m#/#, $self->{path}) {
1726 $c .= "/$_";
1727 next unless ($paths->{$c} &&
1728 ($paths->{$c}->{action} =~ /^[AR]$/));
1729 if ($self->ra->check_path($self->{path}, $r) ==
1730 $SVN::Node::dir) {
1731 return 1;
1734 return 0;
1737 sub find_parent_branch {
1738 my ($self, $paths, $rev) = @_;
1739 return undef unless $self->follow_parent;
1740 unless (defined $paths) {
1741 my $err_handler = $SVN::Error::handler;
1742 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1743 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1744 $paths =
1745 Git::SVN::Ra::dup_changed_paths($_[0]) });
1746 $SVN::Error::handler = $err_handler;
1748 return undef unless defined $paths;
1750 # look for a parent from another branch:
1751 my @b_path_components = split m#/#, $self->rel_path;
1752 my @a_path_components;
1753 my $i;
1754 while (@b_path_components) {
1755 $i = $paths->{'/'.join('/', @b_path_components)};
1756 last if $i && defined $i->{copyfrom_path};
1757 unshift(@a_path_components, pop(@b_path_components));
1759 return undef unless defined $i && defined $i->{copyfrom_path};
1760 my $branch_from = $i->{copyfrom_path};
1761 if (@a_path_components) {
1762 print STDERR "branch_from: $branch_from => ";
1763 $branch_from .= '/'.join('/', @a_path_components);
1764 print STDERR $branch_from, "\n";
1766 my $r = $i->{copyfrom_rev};
1767 my $repos_root = $self->ra->{repos_root};
1768 my $url = $self->ra->{url};
1769 my $new_url = $repos_root . $branch_from;
1770 print STDERR "Found possible branch point: ",
1771 "$new_url => ", $self->full_url, ", $r\n";
1772 $branch_from =~ s#^/##;
1773 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1774 unless ($gs) {
1775 my $ref_id = $self->{ref_id};
1776 $ref_id =~ s/\@\d+$//;
1777 $ref_id .= "\@$r";
1778 # just grow a tail if we're not unique enough :x
1779 $ref_id .= '-' while find_ref($ref_id);
1780 print STDERR "Initializing parent: $ref_id\n";
1781 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1783 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1784 if (!defined $r0 || !defined $parent) {
1785 my ($base, $head) = parse_revision_argument(0, $r);
1786 if ($base <= $r) {
1787 $gs->fetch($base, $r);
1789 ($r0, $parent) = $gs->last_rev_commit;
1791 if (defined $r0 && defined $parent) {
1792 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1793 my $ed;
1794 if ($self->ra->can_do_switch) {
1795 $self->assert_index_clean($parent);
1796 print STDERR "Following parent with do_switch\n";
1797 # do_switch works with svn/trunk >= r22312, but that
1798 # is not included with SVN 1.4.3 (the latest version
1799 # at the moment), so we can't rely on it
1800 $self->{last_commit} = $parent;
1801 $ed = SVN::Git::Fetcher->new($self);
1802 $gs->ra->gs_do_switch($r0, $rev, $gs,
1803 $self->full_url, $ed)
1804 or die "SVN connection failed somewhere...\n";
1805 } else {
1806 print STDERR "Following parent with do_update\n";
1807 $ed = SVN::Git::Fetcher->new($self);
1808 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1809 or die "SVN connection failed somewhere...\n";
1811 print STDERR "Successfully followed parent\n";
1812 return $self->make_log_entry($rev, [$parent], $ed);
1814 return undef;
1817 sub do_fetch {
1818 my ($self, $paths, $rev) = @_;
1819 my $ed;
1820 my ($last_rev, @parents);
1821 if (my $lc = $self->last_commit) {
1822 # we can have a branch that was deleted, then re-added
1823 # under the same name but copied from another path, in
1824 # which case we'll have multiple parents (we don't
1825 # want to break the original ref, nor lose copypath info):
1826 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1827 push @{$log_entry->{parents}}, $lc;
1828 return $log_entry;
1830 $ed = SVN::Git::Fetcher->new($self);
1831 $last_rev = $self->{last_rev};
1832 $ed->{c} = $lc;
1833 @parents = ($lc);
1834 } else {
1835 $last_rev = $rev;
1836 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1837 return $log_entry;
1839 $ed = SVN::Git::Fetcher->new($self);
1841 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1842 die "SVN connection failed somewhere...\n";
1844 $self->make_log_entry($rev, \@parents, $ed);
1847 sub get_untracked {
1848 my ($self, $ed) = @_;
1849 my @out;
1850 my $h = $ed->{empty};
1851 foreach (sort keys %$h) {
1852 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1853 push @out, " $act: " . uri_encode($_);
1854 warn "W: $act: $_\n";
1856 foreach my $t (qw/dir_prop file_prop/) {
1857 $h = $ed->{$t} or next;
1858 foreach my $path (sort keys %$h) {
1859 my $ppath = $path eq '' ? '.' : $path;
1860 foreach my $prop (sort keys %{$h->{$path}}) {
1861 next if $SKIP_PROP{$prop};
1862 my $v = $h->{$path}->{$prop};
1863 my $t_ppath_prop = "$t: " .
1864 uri_encode($ppath) . ' ' .
1865 uri_encode($prop);
1866 if (defined $v) {
1867 push @out, " +$t_ppath_prop " .
1868 uri_encode($v);
1869 } else {
1870 push @out, " -$t_ppath_prop";
1875 foreach my $t (qw/absent_file absent_directory/) {
1876 $h = $ed->{$t} or next;
1877 foreach my $parent (sort keys %$h) {
1878 foreach my $path (sort @{$h->{$parent}}) {
1879 push @out, " $t: " .
1880 uri_encode("$parent/$path");
1881 warn "W: $t: $parent/$path ",
1882 "Insufficient permissions?\n";
1886 \@out;
1889 sub parse_svn_date {
1890 my $date = shift || return '+0000 1970-01-01 00:00:00';
1891 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1892 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1893 croak "Unable to parse date: $date\n";
1894 "+0000 $Y-$m-$d $H:$M:$S";
1897 sub check_author {
1898 my ($author) = @_;
1899 if (!defined $author || length $author == 0) {
1900 $author = '(no author)';
1902 if (defined $::_authors && ! defined $::users{$author}) {
1903 die "Author: $author not defined in $::_authors file\n";
1905 $author;
1908 sub make_log_entry {
1909 my ($self, $rev, $parents, $ed) = @_;
1910 my $untracked = $self->get_untracked($ed);
1912 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1913 print $un "r$rev\n" or croak $!;
1914 print $un $_, "\n" foreach @$untracked;
1915 my %log_entry = ( parents => $parents || [], revision => $rev,
1916 log => '');
1918 my $headrev;
1919 my $logged = delete $self->{logged_rev_props};
1920 if (!$logged || $self->{-want_revprops}) {
1921 my $rp = $self->ra->rev_proplist($rev);
1922 foreach (sort keys %$rp) {
1923 my $v = $rp->{$_};
1924 if (/^svn:(author|date|log)$/) {
1925 $log_entry{$1} = $v;
1926 } elsif ($_ eq 'svm:headrev') {
1927 $headrev = $v;
1928 } else {
1929 print $un " rev_prop: ", uri_encode($_), ' ',
1930 uri_encode($v), "\n";
1933 } else {
1934 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1936 close $un or croak $!;
1938 $log_entry{date} = parse_svn_date($log_entry{date});
1939 $log_entry{log} .= "\n";
1940 my $author = $log_entry{author} = check_author($log_entry{author});
1941 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1942 : ($author, undef);
1943 if (defined $headrev && $self->use_svm_props) {
1944 if ($self->rewrite_root) {
1945 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1946 "options set!\n";
1948 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1949 # we don't want "SVM: initializing mirror for junk" ...
1950 return undef if $r == 0;
1951 my $svm = $self->svm;
1952 if ($uuid ne $svm->{uuid}) {
1953 die "UUID mismatch on SVM path:\n",
1954 "expected: $svm->{uuid}\n",
1955 " got: $uuid\n";
1957 my $full_url = $self->full_url;
1958 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1959 die "Failed to replace '$svm->{replace}' with ",
1960 "'$svm->{source}' in $full_url\n";
1961 # throw away username for storing in records
1962 remove_username($full_url);
1963 $log_entry{metadata} = "$full_url\@$r $uuid";
1964 $log_entry{svm_revision} = $r;
1965 $email ||= "$author\@$uuid"
1966 } elsif ($self->use_svnsync_props) {
1967 my $full_url = $self->svnsync->{url};
1968 $full_url .= "/$self->{path}" if length $self->{path};
1969 remove_username($full_url);
1970 my $uuid = $self->svnsync->{uuid};
1971 $log_entry{metadata} = "$full_url\@$rev $uuid";
1972 $email ||= "$author\@$uuid"
1973 } else {
1974 my $url = $self->metadata_url;
1975 remove_username($url);
1976 $log_entry{metadata} = "$url\@$rev " .
1977 $self->ra->get_uuid;
1978 $email ||= "$author\@" . $self->ra->get_uuid;
1980 $log_entry{name} = $name;
1981 $log_entry{email} = $email;
1982 \%log_entry;
1985 sub fetch {
1986 my ($self, $min_rev, $max_rev, @parents) = @_;
1987 my ($last_rev, $last_commit) = $self->last_rev_commit;
1988 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1989 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1992 sub set_tree_cb {
1993 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1994 $self->{inject_parents} = { $rev => $tree };
1995 $self->fetch(undef, undef);
1998 sub set_tree {
1999 my ($self, $tree) = (shift, shift);
2000 my $log_entry = ::get_commit_entry($tree);
2001 unless ($self->{last_rev}) {
2002 fatal("Must have an existing revision to commit\n");
2004 my %ed_opts = ( r => $self->{last_rev},
2005 log => $log_entry->{log},
2006 ra => $self->ra,
2007 tree_a => $self->{last_commit},
2008 tree_b => $tree,
2009 editor_cb => sub {
2010 $self->set_tree_cb($log_entry, $tree, @_) },
2011 svn_path => $self->{path} );
2012 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2013 print "No changes\nr$self->{last_rev} = $tree\n";
2017 sub rebuild {
2018 my ($self) = @_;
2019 my $db_path = $self->db_path;
2020 return if (-e $db_path && ! -z $db_path);
2021 return unless ::verify_ref($self->refname.'^0');
2022 if (-f $self->{db_root}) {
2023 rename $self->{db_root}, $db_path or die
2024 "rename $self->{db_root} => $db_path failed: $!\n";
2025 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2026 symlink $base, $self->{db_root} or die
2027 "symlink $base => $self->{db_root} failed: $!\n";
2028 return;
2030 print "Rebuilding $db_path ...\n";
2031 my ($log, $ctx) = command_output_pipe("log", $self->refname);
2032 my $latest;
2033 my $full_url = $self->full_url;
2034 remove_username($full_url);
2035 my $svn_uuid;
2036 my $c;
2037 while (<$log>) {
2038 if ( m{^commit ($::sha1)$} ) {
2039 $c = $1;
2040 next;
2042 next unless s{^\s*(git-svn-id:)}{$1};
2043 my ($url, $rev, $uuid) = ::extract_metadata($_);
2044 remove_username($url);
2046 # ignore merges (from set-tree)
2047 next if (!defined $rev || !$uuid);
2049 # if we merged or otherwise started elsewhere, this is
2050 # how we break out of it
2051 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2052 ($full_url && $url && ($url ne $full_url))) {
2053 next;
2055 $latest ||= $rev;
2056 $svn_uuid ||= $uuid;
2058 $self->rev_db_set($rev, $c);
2059 print "r$rev = $c\n";
2061 command_close_pipe($log, $ctx);
2062 print "Done rebuilding $db_path\n";
2065 # rev_db:
2066 # Tie::File seems to be prone to offset errors if revisions get sparse,
2067 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2068 # one of my favorite modules is out :< Next up would be one of the DBM
2069 # modules, but I'm not sure which is most portable... So I'll just
2070 # go with something that's plain-text, but still capable of
2071 # being randomly accessed. So here's my ultra-simple fixed-width
2072 # database. All records are 40 characters + "\n", so it's easy to seek
2073 # to a revision: (41 * rev) is the byte offset.
2074 # A record of 40 0s denotes an empty revision.
2075 # And yes, it's still pretty fast (faster than Tie::File).
2076 # These files are disposable unless noMetadata or useSvmProps is set
2078 sub _rev_db_set {
2079 my ($fh, $rev, $commit) = @_;
2080 my $offset = $rev * 41;
2081 # assume that append is the common case:
2082 seek $fh, 0, 2 or croak $!;
2083 my $pos = tell $fh;
2084 if ($pos < $offset) {
2085 for (1 .. (($offset - $pos) / 41)) {
2086 print $fh (('0' x 40),"\n") or croak $!;
2089 seek $fh, $offset, 0 or croak $!;
2090 print $fh $commit,"\n" or croak $!;
2093 sub mkfile {
2094 my ($path) = @_;
2095 unless (-e $path) {
2096 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2097 mkpath([$dir]) unless -d $dir;
2098 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2099 close $fh or die "Couldn't close (create) $path: $!\n";
2103 sub rev_db_set {
2104 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2105 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2106 my $db = $self->db_path($uuid);
2107 my $db_lock = "$db.lock";
2108 my $sig;
2109 if ($update_ref) {
2110 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2111 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2113 mkfile($db);
2115 $LOCKFILES{$db_lock} = 1;
2116 my $sync;
2117 # both of these options make our .rev_db file very, very important
2118 # and we can't afford to lose it because rebuild() won't work
2119 if ($self->use_svm_props || $self->no_metadata) {
2120 $sync = 1;
2121 copy($db, $db_lock) or die "rev_db_set(@_): ",
2122 "Failed to copy: ",
2123 "$db => $db_lock ($!)\n";
2124 } else {
2125 rename $db, $db_lock or die "rev_db_set(@_): ",
2126 "Failed to rename: ",
2127 "$db => $db_lock ($!)\n";
2129 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2130 _rev_db_set($fh, $rev, $commit);
2131 if ($sync) {
2132 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2133 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2135 close $fh or croak $!;
2136 if ($update_ref) {
2137 $_head = $self;
2138 command_noisy('update-ref', '-m', "r$rev",
2139 $self->refname, $commit);
2141 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2142 "$db_lock => $db ($!)\n";
2143 delete $LOCKFILES{$db_lock};
2144 if ($update_ref) {
2145 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2146 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2147 kill $sig, $$ if defined $sig;
2151 sub rev_db_max {
2152 my ($self) = @_;
2153 $self->rebuild;
2154 my $db_path = $self->db_path;
2155 my @stat = stat $db_path or return 0;
2156 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2157 my $max = $stat[7] / 41;
2158 (($max > 0) ? $max - 1 : 0);
2161 sub rev_db_get {
2162 my ($self, $rev, $uuid) = @_;
2163 my $ret;
2164 my $offset = $rev * 41;
2165 my $db_path = $self->db_path($uuid);
2166 return undef unless -e $db_path;
2167 open my $fh, '<', $db_path or croak $!;
2168 if (sysseek($fh, $offset, 0) == $offset) {
2169 my $read = sysread($fh, $ret, 40);
2170 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2172 close $fh or croak $!;
2173 $ret;
2176 sub find_rev_before {
2177 my ($self, $rev, $eq_ok) = @_;
2178 --$rev unless $eq_ok;
2179 while ($rev > 0) {
2180 if (my $c = $self->rev_db_get($rev)) {
2181 return ($rev, $c);
2183 --$rev;
2185 return (undef, undef);
2188 sub _new {
2189 my ($class, $repo_id, $ref_id, $path) = @_;
2190 unless (defined $repo_id && length $repo_id) {
2191 $repo_id = $Git::SVN::default_repo_id;
2193 unless (defined $ref_id && length $ref_id) {
2194 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2196 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2197 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2198 $_[3] = $path = '' unless (defined $path);
2199 mkpath(["$ENV{GIT_DIR}/svn"]);
2200 bless {
2201 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2202 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2203 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2206 sub db_path {
2207 my ($self, $uuid) = @_;
2208 $uuid ||= $self->ra_uuid;
2209 "$self->{db_root}.$uuid";
2212 sub uri_encode {
2213 my ($f) = @_;
2214 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2218 sub remove_username {
2219 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2222 package Git::SVN::Prompt;
2223 use strict;
2224 use warnings;
2225 require SVN::Core;
2226 use vars qw/$_no_auth_cache $_username/;
2228 sub simple {
2229 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2230 $may_save = undef if $_no_auth_cache;
2231 $default_username = $_username if defined $_username;
2232 if (defined $default_username && length $default_username) {
2233 if (defined $realm && length $realm) {
2234 print STDERR "Authentication realm: $realm\n";
2235 STDERR->flush;
2237 $cred->username($default_username);
2238 } else {
2239 username($cred, $realm, $may_save, $pool);
2241 $cred->password(_read_password("Password for '" .
2242 $cred->username . "': ", $realm));
2243 $cred->may_save($may_save);
2244 $SVN::_Core::SVN_NO_ERROR;
2247 sub ssl_server_trust {
2248 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2249 $may_save = undef if $_no_auth_cache;
2250 print STDERR "Error validating server certificate for '$realm':\n";
2251 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2252 print STDERR " - The certificate is not issued by a trusted ",
2253 "authority. Use the\n",
2254 " fingerprint to validate the certificate manually!\n";
2256 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2257 print STDERR " - The certificate hostname does not match.\n";
2259 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2260 print STDERR " - The certificate is not yet valid.\n";
2262 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2263 print STDERR " - The certificate has expired.\n";
2265 if ($failures & $SVN::Auth::SSL::OTHER) {
2266 print STDERR " - The certificate has an unknown error.\n";
2268 printf STDERR
2269 "Certificate information:\n".
2270 " - Hostname: %s\n".
2271 " - Valid: from %s until %s\n".
2272 " - Issuer: %s\n".
2273 " - Fingerprint: %s\n",
2274 map $cert_info->$_, qw(hostname valid_from valid_until
2275 issuer_dname fingerprint);
2276 my $choice;
2277 prompt:
2278 print STDERR $may_save ?
2279 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2280 "(R)eject or accept (t)emporarily? ";
2281 STDERR->flush;
2282 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2283 if ($choice =~ /^t$/i) {
2284 $cred->may_save(undef);
2285 } elsif ($choice =~ /^r$/i) {
2286 return -1;
2287 } elsif ($may_save && $choice =~ /^p$/i) {
2288 $cred->may_save($may_save);
2289 } else {
2290 goto prompt;
2292 $cred->accepted_failures($failures);
2293 $SVN::_Core::SVN_NO_ERROR;
2296 sub ssl_client_cert {
2297 my ($cred, $realm, $may_save, $pool) = @_;
2298 $may_save = undef if $_no_auth_cache;
2299 print STDERR "Client certificate filename: ";
2300 STDERR->flush;
2301 chomp(my $filename = <STDIN>);
2302 $cred->cert_file($filename);
2303 $cred->may_save($may_save);
2304 $SVN::_Core::SVN_NO_ERROR;
2307 sub ssl_client_cert_pw {
2308 my ($cred, $realm, $may_save, $pool) = @_;
2309 $may_save = undef if $_no_auth_cache;
2310 $cred->password(_read_password("Password: ", $realm));
2311 $cred->may_save($may_save);
2312 $SVN::_Core::SVN_NO_ERROR;
2315 sub username {
2316 my ($cred, $realm, $may_save, $pool) = @_;
2317 $may_save = undef if $_no_auth_cache;
2318 if (defined $realm && length $realm) {
2319 print STDERR "Authentication realm: $realm\n";
2321 my $username;
2322 if (defined $_username) {
2323 $username = $_username;
2324 } else {
2325 print STDERR "Username: ";
2326 STDERR->flush;
2327 chomp($username = <STDIN>);
2329 $cred->username($username);
2330 $cred->may_save($may_save);
2331 $SVN::_Core::SVN_NO_ERROR;
2334 sub _read_password {
2335 my ($prompt, $realm) = @_;
2336 print STDERR $prompt;
2337 STDERR->flush;
2338 require Term::ReadKey;
2339 Term::ReadKey::ReadMode('noecho');
2340 my $password = '';
2341 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2342 last if $key =~ /[\012\015]/; # \n\r
2343 $password .= $key;
2345 Term::ReadKey::ReadMode('restore');
2346 print STDERR "\n";
2347 STDERR->flush;
2348 $password;
2351 package main;
2354 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2355 $SVN::Node::dir.$SVN::Node::unknown.
2356 $SVN::Node::none.$SVN::Node::file.
2357 $SVN::Node::dir.$SVN::Node::unknown.
2358 $SVN::Auth::SSL::CNMISMATCH.
2359 $SVN::Auth::SSL::NOTYETVALID.
2360 $SVN::Auth::SSL::EXPIRED.
2361 $SVN::Auth::SSL::UNKNOWNCA.
2362 $SVN::Auth::SSL::OTHER;
2365 package SVN::Git::Fetcher;
2366 use vars qw/@ISA/;
2367 use strict;
2368 use warnings;
2369 use Carp qw/croak/;
2370 use IO::File qw//;
2371 use Digest::MD5;
2373 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2374 sub new {
2375 my ($class, $git_svn) = @_;
2376 my $self = SVN::Delta::Editor->new;
2377 bless $self, $class;
2378 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2379 $self->{empty} = {};
2380 $self->{dir_prop} = {};
2381 $self->{file_prop} = {};
2382 $self->{absent_dir} = {};
2383 $self->{absent_file} = {};
2384 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2385 $self;
2388 sub set_path_strip {
2389 my ($self, $path) = @_;
2390 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2393 sub open_root {
2394 { path => '' };
2397 sub open_directory {
2398 my ($self, $path, $pb, $rev) = @_;
2399 { path => $path };
2402 sub git_path {
2403 my ($self, $path) = @_;
2404 if ($self->{path_strip}) {
2405 $path =~ s!$self->{path_strip}!! or
2406 die "Failed to strip path '$path' ($self->{path_strip})\n";
2408 $path;
2411 sub delete_entry {
2412 my ($self, $path, $rev, $pb) = @_;
2414 my $gpath = $self->git_path($path);
2415 return undef if ($gpath eq '');
2417 # remove entire directories.
2418 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2419 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2420 -r --name-only -z/,
2421 $self->{c}, '--', $gpath);
2422 local $/ = "\0";
2423 while (<$ls>) {
2424 chomp;
2425 $self->{gii}->remove($_);
2426 print "\tD\t$_\n" unless $::_q;
2428 print "\tD\t$gpath/\n" unless $::_q;
2429 command_close_pipe($ls, $ctx);
2430 $self->{empty}->{$path} = 0
2431 } else {
2432 $self->{gii}->remove($gpath);
2433 print "\tD\t$gpath\n" unless $::_q;
2435 undef;
2438 sub open_file {
2439 my ($self, $path, $pb, $rev) = @_;
2440 my $gpath = $self->git_path($path);
2441 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2442 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2443 unless (defined $mode && defined $blob) {
2444 die "$path was not found in commit $self->{c} (r$rev)\n";
2446 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2447 pool => SVN::Pool->new, action => 'M' };
2450 sub add_file {
2451 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2452 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2453 delete $self->{empty}->{$dir};
2454 { path => $path, mode_a => 100644, mode_b => 100644,
2455 pool => SVN::Pool->new, action => 'A' };
2458 sub add_directory {
2459 my ($self, $path, $cp_path, $cp_rev) = @_;
2460 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2461 delete $self->{empty}->{$dir};
2462 $self->{empty}->{$path} = 1;
2463 { path => $path };
2466 sub change_dir_prop {
2467 my ($self, $db, $prop, $value) = @_;
2468 $self->{dir_prop}->{$db->{path}} ||= {};
2469 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2470 undef;
2473 sub absent_directory {
2474 my ($self, $path, $pb) = @_;
2475 $self->{absent_dir}->{$pb->{path}} ||= [];
2476 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2477 undef;
2480 sub absent_file {
2481 my ($self, $path, $pb) = @_;
2482 $self->{absent_file}->{$pb->{path}} ||= [];
2483 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2484 undef;
2487 sub change_file_prop {
2488 my ($self, $fb, $prop, $value) = @_;
2489 if ($prop eq 'svn:executable') {
2490 if ($fb->{mode_b} != 120000) {
2491 $fb->{mode_b} = defined $value ? 100755 : 100644;
2493 } elsif ($prop eq 'svn:special') {
2494 $fb->{mode_b} = defined $value ? 120000 : 100644;
2495 } else {
2496 $self->{file_prop}->{$fb->{path}} ||= {};
2497 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2499 undef;
2502 sub apply_textdelta {
2503 my ($self, $fb, $exp) = @_;
2504 my $fh = IO::File->new_tmpfile;
2505 $fh->autoflush(1);
2506 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2507 # (but $base does not,) so dup() it for reading in close_file
2508 open my $dup, '<&', $fh or croak $!;
2509 my $base = IO::File->new_tmpfile;
2510 $base->autoflush(1);
2511 if ($fb->{blob}) {
2512 defined (my $pid = fork) or croak $!;
2513 if (!$pid) {
2514 open STDOUT, '>&', $base or croak $!;
2515 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2516 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2518 waitpid $pid, 0;
2519 croak $? if $?;
2521 if (defined $exp) {
2522 seek $base, 0, 0 or croak $!;
2523 my $md5 = Digest::MD5->new;
2524 $md5->addfile($base);
2525 my $got = $md5->hexdigest;
2526 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2527 "expected: $exp\n",
2528 " got: $got\n" if ($got ne $exp);
2531 seek $base, 0, 0 or croak $!;
2532 $fb->{fh} = $dup;
2533 $fb->{base} = $base;
2534 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2537 sub close_file {
2538 my ($self, $fb, $exp) = @_;
2539 my $hash;
2540 my $path = $self->git_path($fb->{path});
2541 if (my $fh = $fb->{fh}) {
2542 if (defined $exp) {
2543 seek($fh, 0, 0) or croak $!;
2544 my $md5 = Digest::MD5->new;
2545 $md5->addfile($fh);
2546 my $got = $md5->hexdigest;
2547 if ($got ne $exp) {
2548 die "Checksum mismatch: $path\n",
2549 "expected: $exp\n got: $got\n";
2552 sysseek($fh, 0, 0) or croak $!;
2553 if ($fb->{mode_b} == 120000) {
2554 sysread($fh, my $buf, 5) == 5 or croak $!;
2555 $buf eq 'link ' or die "$path has mode 120000",
2556 "but is not a link\n";
2558 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2559 if (!$pid) {
2560 open STDIN, '<&', $fh or croak $!;
2561 exec qw/git-hash-object -w --stdin/ or croak $!;
2563 chomp($hash = do { local $/; <$out> });
2564 close $out or croak $!;
2565 close $fh or croak $!;
2566 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2567 close $fb->{base} or croak $!;
2568 } else {
2569 $hash = $fb->{blob} or die "no blob information\n";
2571 $fb->{pool}->clear;
2572 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2573 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2574 undef;
2577 sub abort_edit {
2578 my $self = shift;
2579 $self->{nr} = $self->{gii}->{nr};
2580 delete $self->{gii};
2581 $self->SUPER::abort_edit(@_);
2584 sub close_edit {
2585 my $self = shift;
2586 $self->{git_commit_ok} = 1;
2587 $self->{nr} = $self->{gii}->{nr};
2588 delete $self->{gii};
2589 $self->SUPER::close_edit(@_);
2592 package SVN::Git::Editor;
2593 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2594 use strict;
2595 use warnings;
2596 use Carp qw/croak/;
2597 use IO::File;
2598 use Digest::MD5;
2600 sub new {
2601 my ($class, $opts) = @_;
2602 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2603 die "$_ required!\n" unless (defined $opts->{$_});
2606 my $pool = SVN::Pool->new;
2607 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2608 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2609 $opts->{r}, $mods);
2611 # $opts->{ra} functions should not be used after this:
2612 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2613 $opts->{editor_cb}, $pool);
2614 my $self = SVN::Delta::Editor->new(@ce, $pool);
2615 bless $self, $class;
2616 foreach (qw/svn_path r tree_a tree_b/) {
2617 $self->{$_} = $opts->{$_};
2619 $self->{url} = $opts->{ra}->{url};
2620 $self->{mods} = $mods;
2621 $self->{types} = $types;
2622 $self->{pool} = $pool;
2623 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2624 $self->{rm} = { };
2625 $self->{path_prefix} = length $self->{svn_path} ?
2626 "$self->{svn_path}/" : '';
2627 return $self;
2630 sub generate_diff {
2631 my ($tree_a, $tree_b) = @_;
2632 my @diff_tree = qw(diff-tree -z -r);
2633 if ($_cp_similarity) {
2634 push @diff_tree, "-C$_cp_similarity";
2635 } else {
2636 push @diff_tree, '-C';
2638 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2639 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2640 push @diff_tree, $tree_a, $tree_b;
2641 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2642 local $/ = "\0";
2643 my $state = 'meta';
2644 my @mods;
2645 while (<$diff_fh>) {
2646 chomp $_; # this gets rid of the trailing "\0"
2647 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2648 $::sha1\s($::sha1)\s
2649 ([MTCRAD])\d*$/xo) {
2650 push @mods, { mode_a => $1, mode_b => $2,
2651 sha1_b => $3, chg => $4 };
2652 if ($4 =~ /^(?:C|R)$/) {
2653 $state = 'file_a';
2654 } else {
2655 $state = 'file_b';
2657 } elsif ($state eq 'file_a') {
2658 my $x = $mods[$#mods] or croak "Empty array\n";
2659 if ($x->{chg} !~ /^(?:C|R)$/) {
2660 croak "Error parsing $_, $x->{chg}\n";
2662 $x->{file_a} = $_;
2663 $state = 'file_b';
2664 } elsif ($state eq 'file_b') {
2665 my $x = $mods[$#mods] or croak "Empty array\n";
2666 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2667 croak "Error parsing $_, $x->{chg}\n";
2669 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2670 croak "Error parsing $_, $x->{chg}\n";
2672 $x->{file_b} = $_;
2673 $state = 'meta';
2674 } else {
2675 croak "Error parsing $_\n";
2678 command_close_pipe($diff_fh, $ctx);
2679 \@mods;
2682 sub check_diff_paths {
2683 my ($ra, $pfx, $rev, $mods) = @_;
2684 my %types;
2685 $pfx .= '/' if length $pfx;
2687 sub type_diff_paths {
2688 my ($ra, $types, $path, $rev) = @_;
2689 my @p = split m#/+#, $path;
2690 my $c = shift @p;
2691 unless (defined $types->{$c}) {
2692 $types->{$c} = $ra->check_path($c, $rev);
2694 while (@p) {
2695 $c .= '/' . shift @p;
2696 next if defined $types->{$c};
2697 $types->{$c} = $ra->check_path($c, $rev);
2701 foreach my $m (@$mods) {
2702 foreach my $f (qw/file_a file_b/) {
2703 next unless defined $m->{$f};
2704 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2705 if (length $pfx.$dir && ! defined $types{$dir}) {
2706 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2710 \%types;
2713 sub split_path {
2714 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2717 sub repo_path {
2718 my ($self, $path) = @_;
2719 $self->{path_prefix}.(defined $path ? $path : '');
2722 sub url_path {
2723 my ($self, $path) = @_;
2724 $self->{url} . '/' . $self->repo_path($path);
2727 sub rmdirs {
2728 my ($self) = @_;
2729 my $rm = $self->{rm};
2730 delete $rm->{''}; # we never delete the url we're tracking
2731 return unless %$rm;
2733 foreach (keys %$rm) {
2734 my @d = split m#/#, $_;
2735 my $c = shift @d;
2736 $rm->{$c} = 1;
2737 while (@d) {
2738 $c .= '/' . shift @d;
2739 $rm->{$c} = 1;
2742 delete $rm->{$self->{svn_path}};
2743 delete $rm->{''}; # we never delete the url we're tracking
2744 return unless %$rm;
2746 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2747 $self->{tree_b});
2748 local $/ = "\0";
2749 while (<$fh>) {
2750 chomp;
2751 my @dn = split m#/#, $_;
2752 while (pop @dn) {
2753 delete $rm->{join '/', @dn};
2755 unless (%$rm) {
2756 close $fh;
2757 return;
2760 command_close_pipe($fh, $ctx);
2762 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2763 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2764 $self->close_directory($bat->{$d}, $p);
2765 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2766 print "\tD+\t$d/\n" unless $::_q;
2767 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2768 delete $bat->{$d};
2772 sub open_or_add_dir {
2773 my ($self, $full_path, $baton) = @_;
2774 my $t = $self->{types}->{$full_path};
2775 if (!defined $t) {
2776 die "$full_path not known in r$self->{r} or we have a bug!\n";
2778 if ($t == $SVN::Node::none) {
2779 return $self->add_directory($full_path, $baton,
2780 undef, -1, $self->{pool});
2781 } elsif ($t == $SVN::Node::dir) {
2782 return $self->open_directory($full_path, $baton,
2783 $self->{r}, $self->{pool});
2785 print STDERR "$full_path already exists in repository at ",
2786 "r$self->{r} and it is not a directory (",
2787 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2788 exit 1;
2791 sub ensure_path {
2792 my ($self, $path) = @_;
2793 my $bat = $self->{bat};
2794 my $repo_path = $self->repo_path($path);
2795 return $bat->{''} unless (length $repo_path);
2796 my @p = split m#/+#, $repo_path;
2797 my $c = shift @p;
2798 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2799 while (@p) {
2800 my $c0 = $c;
2801 $c .= '/' . shift @p;
2802 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2804 return $bat->{$c};
2807 sub A {
2808 my ($self, $m) = @_;
2809 my ($dir, $file) = split_path($m->{file_b});
2810 my $pbat = $self->ensure_path($dir);
2811 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2812 undef, -1);
2813 print "\tA\t$m->{file_b}\n" unless $::_q;
2814 $self->chg_file($fbat, $m);
2815 $self->close_file($fbat,undef,$self->{pool});
2818 sub C {
2819 my ($self, $m) = @_;
2820 my ($dir, $file) = split_path($m->{file_b});
2821 my $pbat = $self->ensure_path($dir);
2822 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2823 $self->url_path($m->{file_a}), $self->{r});
2824 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2825 $self->chg_file($fbat, $m);
2826 $self->close_file($fbat,undef,$self->{pool});
2829 sub delete_entry {
2830 my ($self, $path, $pbat) = @_;
2831 my $rpath = $self->repo_path($path);
2832 my ($dir, $file) = split_path($rpath);
2833 $self->{rm}->{$dir} = 1;
2834 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2837 sub R {
2838 my ($self, $m) = @_;
2839 my ($dir, $file) = split_path($m->{file_b});
2840 my $pbat = $self->ensure_path($dir);
2841 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2842 $self->url_path($m->{file_a}), $self->{r});
2843 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2844 $self->chg_file($fbat, $m);
2845 $self->close_file($fbat,undef,$self->{pool});
2847 ($dir, $file) = split_path($m->{file_a});
2848 $pbat = $self->ensure_path($dir);
2849 $self->delete_entry($m->{file_a}, $pbat);
2852 sub M {
2853 my ($self, $m) = @_;
2854 my ($dir, $file) = split_path($m->{file_b});
2855 my $pbat = $self->ensure_path($dir);
2856 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2857 $pbat,$self->{r},$self->{pool});
2858 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2859 $self->chg_file($fbat, $m);
2860 $self->close_file($fbat,undef,$self->{pool});
2863 sub T { shift->M(@_) }
2865 sub change_file_prop {
2866 my ($self, $fbat, $pname, $pval) = @_;
2867 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2870 sub chg_file {
2871 my ($self, $fbat, $m) = @_;
2872 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2873 $self->change_file_prop($fbat,'svn:executable','*');
2874 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2875 $self->change_file_prop($fbat,'svn:executable',undef);
2877 my $fh = IO::File->new_tmpfile or croak $!;
2878 if ($m->{mode_b} =~ /^120/) {
2879 print $fh 'link ' or croak $!;
2880 $self->change_file_prop($fbat,'svn:special','*');
2881 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2882 $self->change_file_prop($fbat,'svn:special',undef);
2884 defined(my $pid = fork) or croak $!;
2885 if (!$pid) {
2886 open STDOUT, '>&', $fh or croak $!;
2887 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2889 waitpid $pid, 0;
2890 croak $? if $?;
2891 $fh->flush == 0 or croak $!;
2892 seek $fh, 0, 0 or croak $!;
2894 my $md5 = Digest::MD5->new;
2895 $md5->addfile($fh) or croak $!;
2896 seek $fh, 0, 0 or croak $!;
2898 my $exp = $md5->hexdigest;
2899 my $pool = SVN::Pool->new;
2900 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2901 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2902 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2903 $pool->clear;
2905 close $fh or croak $!;
2908 sub D {
2909 my ($self, $m) = @_;
2910 my ($dir, $file) = split_path($m->{file_b});
2911 my $pbat = $self->ensure_path($dir);
2912 print "\tD\t$m->{file_b}\n" unless $::_q;
2913 $self->delete_entry($m->{file_b}, $pbat);
2916 sub close_edit {
2917 my ($self) = @_;
2918 my ($p,$bat) = ($self->{pool}, $self->{bat});
2919 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2920 next if $_ eq '';
2921 $self->close_directory($bat->{$_}, $p);
2923 $self->close_directory($bat->{''}, $p);
2924 $self->SUPER::close_edit($p);
2925 $p->clear;
2928 sub abort_edit {
2929 my ($self) = @_;
2930 $self->SUPER::abort_edit($self->{pool});
2933 sub DESTROY {
2934 my $self = shift;
2935 $self->SUPER::DESTROY(@_);
2936 $self->{pool}->clear;
2939 # this drives the editor
2940 sub apply_diff {
2941 my ($self) = @_;
2942 my $mods = $self->{mods};
2943 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2944 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2945 my $f = $m->{chg};
2946 if (defined $o{$f}) {
2947 $self->$f($m);
2948 } else {
2949 fatal("Invalid change type: $f\n");
2952 $self->rmdirs if $_rmdir;
2953 if (@$mods == 0) {
2954 $self->abort_edit;
2955 } else {
2956 $self->close_edit;
2958 return scalar @$mods;
2961 package Git::SVN::Ra;
2962 use vars qw/@ISA $config_dir $_log_window_size/;
2963 use strict;
2964 use warnings;
2965 my ($can_do_switch, %ignored_err, $RA);
2967 BEGIN {
2968 # enforce temporary pool usage for some simple functions
2969 no strict 'refs';
2970 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
2971 my $SUPER = "SUPER::$f";
2972 *$f = sub {
2973 my $self = shift;
2974 my $pool = SVN::Pool->new;
2975 my @ret = $self->$SUPER(@_,$pool);
2976 $pool->clear;
2977 wantarray ? @ret : $ret[0];
2982 sub new {
2983 my ($class, $url) = @_;
2984 $url =~ s!/+$!!;
2985 return $RA if ($RA && $RA->{url} eq $url);
2987 SVN::_Core::svn_config_ensure($config_dir, undef);
2988 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2989 SVN::Client::get_simple_provider(),
2990 SVN::Client::get_ssl_server_trust_file_provider(),
2991 SVN::Client::get_simple_prompt_provider(
2992 \&Git::SVN::Prompt::simple, 2),
2993 SVN::Client::get_ssl_client_cert_file_provider(),
2994 SVN::Client::get_ssl_client_cert_prompt_provider(
2995 \&Git::SVN::Prompt::ssl_client_cert, 2),
2996 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2997 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2998 SVN::Client::get_username_provider(),
2999 SVN::Client::get_ssl_server_trust_prompt_provider(
3000 \&Git::SVN::Prompt::ssl_server_trust),
3001 SVN::Client::get_username_prompt_provider(
3002 \&Git::SVN::Prompt::username, 2),
3004 my $config = SVN::Core::config_get_config($config_dir);
3005 $RA = undef;
3006 my $self = SVN::Ra->new(url => $url, auth => $baton,
3007 config => $config,
3008 pool => SVN::Pool->new,
3009 auth_provider_callbacks => $callbacks);
3010 $self->{svn_path} = $url;
3011 $self->{repos_root} = $self->get_repos_root;
3012 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3013 $self->{cache} = { check_path => { r => 0, data => {} },
3014 get_dir => { r => 0, data => {} } };
3015 $RA = bless $self, $class;
3018 sub check_path {
3019 my ($self, $path, $r) = @_;
3020 my $cache = $self->{cache}->{check_path};
3021 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3022 return $cache->{data}->{$path};
3024 my $pool = SVN::Pool->new;
3025 my $t = $self->SUPER::check_path($path, $r, $pool);
3026 $pool->clear;
3027 if ($r != $cache->{r}) {
3028 %{$cache->{data}} = ();
3029 $cache->{r} = $r;
3031 $cache->{data}->{$path} = $t;
3034 sub get_dir {
3035 my ($self, $dir, $r) = @_;
3036 my $cache = $self->{cache}->{get_dir};
3037 if ($r == $cache->{r}) {
3038 if (my $x = $cache->{data}->{$dir}) {
3039 return wantarray ? @$x : $x->[0];
3042 my $pool = SVN::Pool->new;
3043 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3044 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3045 $pool->clear;
3046 if ($r != $cache->{r}) {
3047 %{$cache->{data}} = ();
3048 $cache->{r} = $r;
3050 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3051 wantarray ? (\%dirents, $r, $props) : \%dirents;
3054 sub DESTROY {
3055 # do not call the real DESTROY since we store ourselves in $RA
3058 sub get_log {
3059 my ($self, @args) = @_;
3060 my $pool = SVN::Pool->new;
3061 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3062 my $ret = $self->SUPER::get_log(@args, $pool);
3063 $pool->clear;
3064 $ret;
3067 sub get_commit_editor {
3068 my ($self, $log, $cb, $pool) = @_;
3069 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3070 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3073 sub gs_do_update {
3074 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3075 my $new = ($rev_a == $rev_b);
3076 my $path = $gs->{path};
3078 if ($new && -e $gs->{index}) {
3079 unlink $gs->{index} or die
3080 "Couldn't unlink index: $gs->{index}: $!\n";
3082 my $pool = SVN::Pool->new;
3083 $editor->set_path_strip($path);
3084 my (@pc) = split m#/#, $path;
3085 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3086 1, $editor, $pool);
3087 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3089 # Since we can't rely on svn_ra_reparent being available, we'll
3090 # just have to do some magic with set_path to make it so
3091 # we only want a partial path.
3092 my $sp = '';
3093 my $final = join('/', @pc);
3094 while (@pc) {
3095 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3096 $sp .= '/' if length $sp;
3097 $sp .= shift @pc;
3099 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3101 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3103 $reporter->finish_report($pool);
3104 $pool->clear;
3105 $editor->{git_commit_ok};
3108 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3109 # svn_ra_reparent didn't work before 1.4)
3110 sub gs_do_switch {
3111 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3112 my $path = $gs->{path};
3113 my $pool = SVN::Pool->new;
3115 my $full_url = $self->{url};
3116 my $old_url = $full_url;
3117 $full_url .= "/$path" if length $path;
3118 my ($ra, $reparented);
3119 if ($old_url ne $full_url) {
3120 if ($old_url !~ m#^svn(\+ssh)?://#) {
3121 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3122 $pool);
3123 $self->{url} = $full_url;
3124 $reparented = 1;
3125 } else {
3126 $ra = Git::SVN::Ra->new($full_url);
3129 $ra ||= $self;
3130 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3131 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3132 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3133 $reporter->finish_report($pool);
3135 if ($reparented) {
3136 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3137 $self->{url} = $old_url;
3140 $pool->clear;
3141 $editor->{git_commit_ok};
3144 sub longest_common_path {
3145 my ($gsv, $globs) = @_;
3146 my %common;
3147 my $common_max = scalar @$gsv;
3149 foreach my $gs (@$gsv) {
3150 my @tmp = split m#/#, $gs->{path};
3151 my $p = '';
3152 foreach (@tmp) {
3153 $p .= length($p) ? "/$_" : $_;
3154 $common{$p} ||= 0;
3155 $common{$p}++;
3158 $globs ||= [];
3159 $common_max += scalar @$globs;
3160 foreach my $glob (@$globs) {
3161 my @tmp = split m#/#, $glob->{path}->{left};
3162 my $p = '';
3163 foreach (@tmp) {
3164 $p .= length($p) ? "/$_" : $_;
3165 $common{$p} ||= 0;
3166 $common{$p}++;
3170 my $longest_path = '';
3171 foreach (sort {length $b <=> length $a} keys %common) {
3172 if ($common{$_} == $common_max) {
3173 $longest_path = $_;
3174 last;
3177 $longest_path;
3180 sub gs_fetch_loop_common {
3181 my ($self, $base, $head, $gsv, $globs) = @_;
3182 return if ($base > $head);
3183 my $inc = $_log_window_size;
3184 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3185 my $longest_path = longest_common_path($gsv, $globs);
3186 while (1) {
3187 my %revs;
3188 my $err;
3189 my $err_handler = $SVN::Error::handler;
3190 $SVN::Error::handler = sub {
3191 ($err) = @_;
3192 skip_unknown_revs($err);
3194 sub _cb {
3195 my ($paths, $r, $author, $date, $log) = @_;
3196 [ dup_changed_paths($paths),
3197 { author => $author, date => $date, log => $log } ];
3199 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3200 sub { $revs{$_[1]} = _cb(@_) });
3201 if ($err && $max >= $head) {
3202 print STDERR "Path '$longest_path' ",
3203 "was probably deleted:\n",
3204 $err->expanded_message,
3205 "\nWill attempt to follow ",
3206 "revisions r$min .. r$max ",
3207 "committed before the deletion\n";
3208 my $hi = $max;
3209 while (--$hi >= $min) {
3210 my $ok;
3211 $self->get_log([$longest_path], $min, $hi,
3212 0, 1, 1, sub {
3213 $ok ||= $_[1];
3214 $revs{$_[1]} = _cb(@_) });
3215 if ($ok) {
3216 print STDERR "r$min .. r$ok OK\n";
3217 last;
3221 $SVN::Error::handler = $err_handler;
3223 my %exists = map { $_->{path} => $_ } @$gsv;
3224 foreach my $r (sort {$a <=> $b} keys %revs) {
3225 my ($paths, $logged) = @{$revs{$r}};
3227 foreach my $gs ($self->match_globs(\%exists, $paths,
3228 $globs, $r)) {
3229 if ($gs->rev_db_max >= $r) {
3230 next;
3232 next unless $gs->match_paths($paths, $r);
3233 $gs->{logged_rev_props} = $logged;
3234 if (my $last_commit = $gs->last_commit) {
3235 $gs->assert_index_clean($last_commit);
3237 my $log_entry = $gs->do_fetch($paths, $r);
3238 if ($log_entry) {
3239 $gs->do_git_commit($log_entry);
3242 foreach my $g (@$globs) {
3243 my $k = "svn-remote.$g->{remote}." .
3244 "$g->{t}-maxRev";
3245 Git::SVN::tmp_config($k, $r);
3248 # pre-fill the .rev_db since it'll eventually get filled in
3249 # with '0' x40 if something new gets committed
3250 foreach my $gs (@$gsv) {
3251 next if defined $gs->rev_db_get($max);
3252 $gs->rev_db_set($max, 0 x40);
3254 foreach my $g (@$globs) {
3255 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3256 Git::SVN::tmp_config($k, $max);
3258 last if $max >= $head;
3259 $min = $max + 1;
3260 $max += $inc;
3261 $max = $head if ($max > $head);
3265 sub match_globs {
3266 my ($self, $exists, $paths, $globs, $r) = @_;
3268 sub get_dir_check {
3269 my ($self, $exists, $g, $r) = @_;
3270 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3271 return unless scalar @x == 3;
3272 my $dirents = $x[0];
3273 foreach my $de (keys %$dirents) {
3274 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3275 my $p = $g->{path}->full_path($de);
3276 next if $exists->{$p};
3277 next if (length $g->{path}->{right} &&
3278 ($self->check_path($p, $r) !=
3279 $SVN::Node::dir));
3280 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3281 $g->{ref}->full_path($de), 1);
3284 foreach my $g (@$globs) {
3285 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3286 if ($path->{action} =~ /^[AR]$/) {
3287 get_dir_check($self, $exists, $g, $r);
3290 foreach (keys %$paths) {
3291 if (/$g->{path}->{left_regex}/ &&
3292 !/$g->{path}->{regex}/) {
3293 next if $paths->{$_}->{action} !~ /^[AR]$/;
3294 get_dir_check($self, $exists, $g, $r);
3296 next unless /$g->{path}->{regex}/;
3297 my $p = $1;
3298 my $pathname = $g->{path}->full_path($p);
3299 next if $exists->{$pathname};
3300 next if ($self->check_path($pathname, $r) !=
3301 $SVN::Node::dir);
3302 $exists->{$pathname} = Git::SVN->init(
3303 $self->{url}, $pathname, undef,
3304 $g->{ref}->full_path($p), 1);
3306 my $c = '';
3307 foreach (split m#/#, $g->{path}->{left}) {
3308 $c .= "/$_";
3309 next unless ($paths->{$c} &&
3310 ($paths->{$c}->{action} =~ /^[AR]$/));
3311 get_dir_check($self, $exists, $g, $r);
3314 values %$exists;
3317 sub minimize_url {
3318 my ($self) = @_;
3319 return $self->{url} if ($self->{url} eq $self->{repos_root});
3320 my $url = $self->{repos_root};
3321 my @components = split(m!/!, $self->{svn_path});
3322 my $c = '';
3323 do {
3324 $url .= "/$c" if length $c;
3325 eval { (ref $self)->new($url)->get_latest_revnum };
3326 } while ($@ && ($c = shift @components));
3327 $url;
3330 sub can_do_switch {
3331 my $self = shift;
3332 unless (defined $can_do_switch) {
3333 my $pool = SVN::Pool->new;
3334 my $rep = eval {
3335 $self->do_switch(1, '', 0, $self->{url},
3336 SVN::Delta::Editor->new, $pool);
3338 if ($@) {
3339 $can_do_switch = 0;
3340 } else {
3341 $rep->abort_report($pool);
3342 $can_do_switch = 1;
3344 $pool->clear;
3346 $can_do_switch;
3349 sub skip_unknown_revs {
3350 my ($err) = @_;
3351 my $errno = $err->apr_err();
3352 # Maybe the branch we're tracking didn't
3353 # exist when the repo started, so it's
3354 # not an error if it doesn't, just continue
3356 # Wonderfully consistent library, eh?
3357 # 160013 - svn:// and file://
3358 # 175002 - http(s)://
3359 # 175007 - http(s):// (this repo required authorization, too...)
3360 # More codes may be discovered later...
3361 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3362 my $err_key = $err->expanded_message;
3363 # revision numbers change every time, filter them out
3364 $err_key =~ s/\d+/\0/g;
3365 $err_key = "$errno\0$err_key";
3366 unless ($ignored_err{$err_key}) {
3367 warn "W: Ignoring error from SVN, path probably ",
3368 "does not exist: ($errno): ",
3369 $err->expanded_message,"\n";
3370 $ignored_err{$err_key} = 1;
3372 return;
3374 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3377 # svn_log_changed_path_t objects passed to get_log are likely to be
3378 # overwritten even if only the refs are copied to an external variable,
3379 # so we should dup the structures in their entirety. Using an externally
3380 # passed pool (instead of our temporary and quickly cleared pool in
3381 # Git::SVN::Ra) does not help matters at all...
3382 sub dup_changed_paths {
3383 my ($paths) = @_;
3384 return undef unless $paths;
3385 my %ret;
3386 foreach my $p (keys %$paths) {
3387 my $i = $paths->{$p};
3388 my %s = map { $_ => $i->$_ }
3389 qw/copyfrom_path copyfrom_rev action/;
3390 $ret{$p} = \%s;
3392 \%ret;
3395 package Git::SVN::Log;
3396 use strict;
3397 use warnings;
3398 use POSIX qw/strftime/;
3399 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3400 %rusers $show_commit $incremental/;
3401 my $l_fmt;
3403 sub cmt_showable {
3404 my ($c) = @_;
3405 return 1 if defined $c->{r};
3407 # big commit message got truncated by the 16k pretty buffer in rev-list
3408 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3409 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3410 @{$c->{l}} = ();
3411 my @log = command(qw/cat-file commit/, $c->{c});
3413 # shift off the headers
3414 shift @log while ($log[0] ne '');
3415 shift @log;
3417 # TODO: make $c->{l} not have a trailing newline in the future
3418 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3420 (undef, $c->{r}, undef) = ::extract_metadata(
3421 (grep(/^git-svn-id: /, @log))[-1]);
3423 return defined $c->{r};
3426 sub log_use_color {
3427 return 1 if $color;
3428 my ($dc, $dcvar);
3429 $dcvar = 'color.diff';
3430 $dc = `git-config --get $dcvar`;
3431 if ($dc eq '') {
3432 # nothing at all; fallback to "diff.color"
3433 $dcvar = 'diff.color';
3434 $dc = `git-config --get $dcvar`;
3436 chomp($dc);
3437 if ($dc eq 'auto') {
3438 my $pc;
3439 $pc = `git-config --get color.pager`;
3440 if ($pc eq '') {
3441 # does not have it -- fallback to pager.color
3442 $pc = `git-config --bool --get pager.color`;
3444 else {
3445 $pc = `git-config --bool --get color.pager`;
3446 if ($?) {
3447 $pc = 'false';
3450 chomp($pc);
3451 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3452 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3454 return 0;
3456 return 0 if $dc eq 'never';
3457 return 1 if $dc eq 'always';
3458 chomp($dc = `git-config --bool --get $dcvar`);
3459 return ($dc eq 'true');
3462 sub git_svn_log_cmd {
3463 my ($r_min, $r_max, @args) = @_;
3464 my $head = 'HEAD';
3465 foreach my $x (@args) {
3466 last if $x eq '--';
3467 next unless ::verify_ref("$x^0");
3468 $head = $x;
3469 last;
3472 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3473 $gs ||= Git::SVN->_new;
3474 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3475 $gs->refname);
3476 push @cmd, '-r' unless $non_recursive;
3477 push @cmd, qw/--raw --name-status/ if $verbose;
3478 push @cmd, '--color' if log_use_color();
3479 return @cmd unless defined $r_max;
3480 if ($r_max == $r_min) {
3481 push @cmd, '--max-count=1';
3482 if (my $c = $gs->rev_db_get($r_max)) {
3483 push @cmd, $c;
3485 } else {
3486 my ($c_min, $c_max);
3487 $c_max = $gs->rev_db_get($r_max);
3488 $c_min = $gs->rev_db_get($r_min);
3489 if (defined $c_min && defined $c_max) {
3490 if ($r_max > $r_max) {
3491 push @cmd, "$c_min..$c_max";
3492 } else {
3493 push @cmd, "$c_max..$c_min";
3495 } elsif ($r_max > $r_min) {
3496 push @cmd, $c_max;
3497 } else {
3498 push @cmd, $c_min;
3501 return @cmd;
3504 # adapted from pager.c
3505 sub config_pager {
3506 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3507 if (!defined $pager) {
3508 $pager = 'less';
3509 } elsif (length $pager == 0 || $pager eq 'cat') {
3510 $pager = undef;
3514 sub run_pager {
3515 return unless -t *STDOUT;
3516 pipe my $rfd, my $wfd or return;
3517 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3518 if (!$pid) {
3519 open STDOUT, '>&', $wfd or
3520 ::fatal "Can't redirect to stdout: $!\n";
3521 return;
3523 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3524 $ENV{LESS} ||= 'FRSX';
3525 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3528 sub tz_to_s_offset {
3529 my ($tz) = @_;
3530 $tz =~ s/(\d\d)$//;
3531 return ($1 * 60) + ($tz * 3600);
3534 sub get_author_info {
3535 my ($dest, $author, $t, $tz) = @_;
3536 $author =~ s/(?:^\s*|\s*$)//g;
3537 $dest->{a_raw} = $author;
3538 my $au;
3539 if ($::_authors) {
3540 $au = $rusers{$author} || undef;
3542 if (!$au) {
3543 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3545 $dest->{t} = $t;
3546 $dest->{tz} = $tz;
3547 $dest->{a} = $au;
3548 # Date::Parse isn't in the standard Perl distro :(
3549 if ($tz =~ s/^\+//) {
3550 $t += tz_to_s_offset($tz);
3551 } elsif ($tz =~ s/^\-//) {
3552 $t -= tz_to_s_offset($tz);
3554 $dest->{t_utc} = $t;
3557 sub process_commit {
3558 my ($c, $r_min, $r_max, $defer) = @_;
3559 if (defined $r_min && defined $r_max) {
3560 if ($r_min == $c->{r} && $r_min == $r_max) {
3561 show_commit($c);
3562 return 0;
3564 return 1 if $r_min == $r_max;
3565 if ($r_min < $r_max) {
3566 # we need to reverse the print order
3567 return 0 if (defined $limit && --$limit < 0);
3568 push @$defer, $c;
3569 return 1;
3571 if ($r_min != $r_max) {
3572 return 1 if ($r_min < $c->{r});
3573 return 1 if ($r_max > $c->{r});
3576 return 0 if (defined $limit && --$limit < 0);
3577 show_commit($c);
3578 return 1;
3581 sub show_commit {
3582 my $c = shift;
3583 if ($oneline) {
3584 my $x = "\n";
3585 if (my $l = $c->{l}) {
3586 while ($l->[0] =~ /^\s*$/) { shift @$l }
3587 $x = $l->[0];
3589 $l_fmt ||= 'A' . length($c->{r});
3590 print 'r',pack($l_fmt, $c->{r}),' | ';
3591 print "$c->{c} | " if $show_commit;
3592 print $x;
3593 } else {
3594 show_commit_normal($c);
3598 sub show_commit_changed_paths {
3599 my ($c) = @_;
3600 return unless $c->{changed};
3601 print "Changed paths:\n", @{$c->{changed}};
3604 sub show_commit_normal {
3605 my ($c) = @_;
3606 print '-' x72, "\nr$c->{r} | ";
3607 print "$c->{c} | " if $show_commit;
3608 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3609 localtime($c->{t_utc})), ' | ';
3610 my $nr_line = 0;
3612 if (my $l = $c->{l}) {
3613 while ($l->[$#$l] eq "\n" && $#$l > 0
3614 && $l->[($#$l - 1)] eq "\n") {
3615 pop @$l;
3617 $nr_line = scalar @$l;
3618 if (!$nr_line) {
3619 print "1 line\n\n\n";
3620 } else {
3621 if ($nr_line == 1) {
3622 $nr_line = '1 line';
3623 } else {
3624 $nr_line .= ' lines';
3626 print $nr_line, "\n";
3627 show_commit_changed_paths($c);
3628 print "\n";
3629 print $_ foreach @$l;
3631 } else {
3632 print "1 line\n";
3633 show_commit_changed_paths($c);
3634 print "\n";
3637 foreach my $x (qw/raw stat diff/) {
3638 if ($c->{$x}) {
3639 print "\n";
3640 print $_ foreach @{$c->{$x}}
3645 sub cmd_show_log {
3646 my (@args) = @_;
3647 my ($r_min, $r_max);
3648 my $r_last = -1; # prevent dupes
3649 if (defined $TZ) {
3650 $ENV{TZ} = $TZ;
3651 } else {
3652 delete $ENV{TZ};
3654 if (defined $::_revision) {
3655 if ($::_revision =~ /^(\d+):(\d+)$/) {
3656 ($r_min, $r_max) = ($1, $2);
3657 } elsif ($::_revision =~ /^\d+$/) {
3658 $r_min = $r_max = $::_revision;
3659 } else {
3660 ::fatal "-r$::_revision is not supported, use ",
3661 "standard \'git log\' arguments instead\n";
3665 config_pager();
3666 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3667 my $log = command_output_pipe(@args);
3668 run_pager();
3669 my (@k, $c, $d, $stat);
3670 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3671 while (<$log>) {
3672 if (/^${esc_color}commit ($::sha1_short)/o) {
3673 my $cmt = $1;
3674 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3675 $r_last = $c->{r};
3676 process_commit($c, $r_min, $r_max, \@k) or
3677 goto out;
3679 $d = undef;
3680 $c = { c => $cmt };
3681 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3682 get_author_info($c, $1, $2, $3);
3683 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3684 # ignore
3685 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3686 push @{$c->{raw}}, $_;
3687 } elsif (/^${esc_color}[ACRMDT]\t/) {
3688 # we could add $SVN->{svn_path} here, but that requires
3689 # remote access at the moment (repo_path_split)...
3690 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3691 push @{$c->{changed}}, $_;
3692 } elsif (/^${esc_color}diff /o) {
3693 $d = 1;
3694 push @{$c->{diff}}, $_;
3695 } elsif ($d) {
3696 push @{$c->{diff}}, $_;
3697 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3698 $esc_color*[\+\-]*$esc_color$/x) {
3699 $stat = 1;
3700 push @{$c->{stat}}, $_;
3701 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3702 push @{$c->{stat}}, $_;
3703 $stat = undef;
3704 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3705 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3706 } elsif (s/^${esc_color} //o) {
3707 push @{$c->{l}}, $_;
3710 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3711 $r_last = $c->{r};
3712 process_commit($c, $r_min, $r_max, \@k);
3714 if (@k) {
3715 my $swap = $r_max;
3716 $r_max = $r_min;
3717 $r_min = $swap;
3718 process_commit($_, $r_min, $r_max) foreach reverse @k;
3720 out:
3721 close $log;
3722 print '-' x72,"\n" unless $incremental || $oneline;
3725 package Git::SVN::Migration;
3726 # these version numbers do NOT correspond to actual version numbers
3727 # of git nor git-svn. They are just relative.
3729 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3731 # v1 layout: .git/$id/info/url, refs/remotes/$id
3733 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3735 # v3 layout: .git/svn/$id, refs/remotes/$id
3736 # - info/url may remain for backwards compatibility
3737 # - this is what we migrate up to this layout automatically,
3738 # - this will be used by git svn init on single branches
3739 # v3.1 layout (auto migrated):
3740 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3741 # for backwards compatibility
3743 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3744 # - this is only created for newly multi-init-ed
3745 # repositories. Similar in spirit to the
3746 # --use-separate-remotes option in git-clone (now default)
3747 # - we do not automatically migrate to this (following
3748 # the example set by core git)
3749 use strict;
3750 use warnings;
3751 use Carp qw/croak/;
3752 use File::Path qw/mkpath/;
3753 use File::Basename qw/dirname basename/;
3754 use vars qw/$_minimize/;
3756 sub migrate_from_v0 {
3757 my $git_dir = $ENV{GIT_DIR};
3758 return undef unless -d $git_dir;
3759 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3760 my $migrated = 0;
3761 while (<$fh>) {
3762 chomp;
3763 my ($id, $orig_ref) = ($_, $_);
3764 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3765 next unless -f "$git_dir/$id/info/url";
3766 my $new_ref = "refs/remotes/$id";
3767 if (::verify_ref("$new_ref^0")) {
3768 print STDERR "W: $orig_ref is probably an old ",
3769 "branch used by an ancient version of ",
3770 "git-svn.\n",
3771 "However, $new_ref also exists.\n",
3772 "We will not be able ",
3773 "to use this branch until this ",
3774 "ambiguity is resolved.\n";
3775 next;
3777 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3778 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3779 command_noisy('update-ref', $new_ref, $orig_ref);
3780 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3781 $migrated++;
3783 command_close_pipe($fh, $ctx);
3784 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3785 $migrated;
3788 sub migrate_from_v1 {
3789 my $git_dir = $ENV{GIT_DIR};
3790 my $migrated = 0;
3791 return $migrated unless -d $git_dir;
3792 my $svn_dir = "$git_dir/svn";
3794 # just in case somebody used 'svn' as their $id at some point...
3795 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3797 print STDERR "Migrating from a git-svn v1 layout...\n";
3798 mkpath([$svn_dir]);
3799 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3800 "$svn_dir\n\t(required for this version ",
3801 "($::VERSION) of git-svn) does not. exist\n";
3802 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3803 while (<$fh>) {
3804 my $x = $_;
3805 next unless $x =~ s#^refs/remotes/##;
3806 chomp $x;
3807 next unless -f "$git_dir/$x/info/url";
3808 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3809 next unless $u;
3810 my $dn = dirname("$git_dir/svn/$x");
3811 mkpath([$dn]) unless -d $dn;
3812 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3813 mkpath(["$git_dir/svn/svn"]);
3814 print STDERR " - $git_dir/$x/info => ",
3815 "$git_dir/svn/$x/info\n";
3816 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3817 croak "$!: $x";
3818 # don't worry too much about these, they probably
3819 # don't exist with repos this old (save for index,
3820 # and we can easily regenerate that)
3821 foreach my $f (qw/unhandled.log index .rev_db/) {
3822 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3824 } else {
3825 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3826 rename "$git_dir/$x", "$git_dir/svn/$x" or
3827 croak "$!: $x";
3829 $migrated++;
3831 command_close_pipe($fh, $ctx);
3832 print STDERR "Done migrating from a git-svn v1 layout\n";
3833 $migrated;
3836 sub read_old_urls {
3837 my ($l_map, $pfx, $path) = @_;
3838 my @dir;
3839 foreach (<$path/*>) {
3840 if (-r "$_/info/url") {
3841 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3842 my $ref_id = $pfx . basename $_;
3843 my $url = ::file_to_s("$_/info/url");
3844 $l_map->{$ref_id} = $url;
3845 } elsif (-d $_) {
3846 push @dir, $_;
3849 foreach (@dir) {
3850 my $x = $_;
3851 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3852 read_old_urls($l_map, $x, $_);
3856 sub migrate_from_v2 {
3857 my @cfg = command(qw/config -l/);
3858 return if grep /^svn-remote\..+\.url=/, @cfg;
3859 my %l_map;
3860 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3861 my $migrated = 0;
3863 foreach my $ref_id (sort keys %l_map) {
3864 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3865 if ($@) {
3866 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3868 $migrated++;
3870 $migrated;
3873 sub minimize_connections {
3874 my $r = Git::SVN::read_all_remotes();
3875 my $new_urls = {};
3876 my $root_repos = {};
3877 foreach my $repo_id (keys %$r) {
3878 my $url = $r->{$repo_id}->{url} or next;
3879 my $fetch = $r->{$repo_id}->{fetch} or next;
3880 my $ra = Git::SVN::Ra->new($url);
3882 # skip existing cases where we already connect to the root
3883 if (($ra->{url} eq $ra->{repos_root}) ||
3884 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3885 $repo_id)) {
3886 $root_repos->{$ra->{url}} = $repo_id;
3887 next;
3890 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3891 my $root_path = $ra->{url};
3892 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3893 foreach my $path (keys %$fetch) {
3894 my $ref_id = $fetch->{$path};
3895 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3897 # make sure we can read when connecting to
3898 # a higher level of a repository
3899 my ($last_rev, undef) = $gs->last_rev_commit;
3900 if (!defined $last_rev) {
3901 $last_rev = eval {
3902 $root_ra->get_latest_revnum;
3904 next if $@;
3906 my $new = $root_path;
3907 $new .= length $path ? "/$path" : '';
3908 eval {
3909 $root_ra->get_log([$new], $last_rev, $last_rev,
3910 0, 0, 1, sub { });
3912 next if $@;
3913 $new_urls->{$ra->{repos_root}}->{$new} =
3914 { ref_id => $ref_id,
3915 old_repo_id => $repo_id,
3916 old_path => $path };
3920 my @emptied;
3921 foreach my $url (keys %$new_urls) {
3922 # see if we can re-use an existing [svn-remote "repo_id"]
3923 # instead of creating a(n ugly) new section:
3924 my $repo_id = $root_repos->{$url} ||
3925 Git::SVN::sanitize_remote_name($url);
3927 my $fetch = $new_urls->{$url};
3928 foreach my $path (keys %$fetch) {
3929 my $x = $fetch->{$path};
3930 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3931 my $pfx = "svn-remote.$x->{old_repo_id}";
3933 my $old_fetch = quotemeta("$x->{old_path}:".
3934 "refs/remotes/$x->{ref_id}");
3935 command_noisy(qw/config --unset/,
3936 "$pfx.fetch", '^'. $old_fetch . '$');
3937 delete $r->{$x->{old_repo_id}}->
3938 {fetch}->{$x->{old_path}};
3939 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3940 command_noisy(qw/config --unset/,
3941 "$pfx.url");
3942 push @emptied, $x->{old_repo_id}
3946 if (@emptied) {
3947 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3948 "$ENV{GIT_DIR}/config";
3949 print STDERR <<EOF;
3950 The following [svn-remote] sections in your config file ($file) are empty
3951 and can be safely removed:
3953 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3957 sub migration_check {
3958 migrate_from_v0();
3959 migrate_from_v1();
3960 migrate_from_v2();
3961 minimize_connections() if $_minimize;
3964 package Git::IndexInfo;
3965 use strict;
3966 use warnings;
3967 use Git qw/command_input_pipe command_close_pipe/;
3969 sub new {
3970 my ($class) = @_;
3971 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3972 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3975 sub remove {
3976 my ($self, $path) = @_;
3977 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3978 return ++$self->{nr};
3980 undef;
3983 sub update {
3984 my ($self, $mode, $hash, $path) = @_;
3985 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3986 return ++$self->{nr};
3988 undef;
3991 sub DESTROY {
3992 my ($self) = @_;
3993 command_close_pipe($self->{gui}, $self->{ctx});
3996 package Git::SVN::GlobSpec;
3997 use strict;
3998 use warnings;
4000 sub new {
4001 my ($class, $glob) = @_;
4002 my $re = $glob;
4003 $re =~ s!/+$!!g; # no need for trailing slashes
4004 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4005 my ($left, $right) = ($1, $2);
4006 if ($nr > 1) {
4007 die "Only one '*' wildcard expansion ",
4008 "is supported (got $nr): '$glob'\n";
4009 } elsif ($nr == 0) {
4010 die "One '*' is needed for glob: '$glob'\n";
4012 $re = quotemeta($left) . $re . quotemeta($right);
4013 if (length $left && !($left =~ s!/+$!!g)) {
4014 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4016 if (length $right && !($right =~ s!^/+!!g)) {
4017 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4019 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4020 bless { left => $left, right => $right, left_regex => $left_re,
4021 regex => qr/$re/, glob => $glob }, $class;
4024 sub full_path {
4025 my ($self, $path) = @_;
4026 return (length $self->{left} ? "$self->{left}/" : '') .
4027 $path . (length $self->{right} ? "/$self->{right}" : '');
4030 __END__
4032 Data structures:
4035 $remotes = { # returned by read_all_remotes()
4036 'svn' => {
4037 # svn-remote.svn.url=https://svn.musicpd.org
4038 url => 'https://svn.musicpd.org',
4039 # svn-remote.svn.fetch=mpd/trunk:trunk
4040 fetch => {
4041 'mpd/trunk' => 'trunk',
4043 # svn-remote.svn.tags=mpd/tags/*:tags/*
4044 tags => {
4045 path => {
4046 left => 'mpd/tags',
4047 right => '',
4048 regex => qr!mpd/tags/([^/]+)$!,
4049 glob => 'tags/*',
4051 ref => {
4052 left => 'tags',
4053 right => '',
4054 regex => qr!tags/([^/]+)$!,
4055 glob => 'tags/*',
4061 $log_entry hashref as returned by libsvn_log_entry()
4063 log => 'whitespace-formatted log entry
4064 ', # trailing newline is preserved
4065 revision => '8', # integer
4066 date => '2004-02-24T17:01:44.108345Z', # commit date
4067 author => 'committer name'
4071 # this is generated by generate_diff();
4072 @mods = array of diff-index line hashes, each element represents one line
4073 of diff-index output
4075 diff-index line ($m hash)
4077 mode_a => first column of diff-index output, no leading ':',
4078 mode_b => second column of diff-index output,
4079 sha1_b => sha1sum of the final blob,
4080 chg => change type [MCRADT],
4081 file_a => original file name of a file (iff chg is 'C' or 'R')
4082 file_b => new/current file name of a file (any chg)
4086 # retval of read_url_paths{,_all}();
4087 $l_map = {
4088 # repository root url
4089 'https://svn.musicpd.org' => {
4090 # repository path # GIT_SVN_ID
4091 'mpd/trunk' => 'trunk',
4092 'mpd/tags/0.11.5' => 'tags/0.11.5',
4096 Notes:
4097 I don't trust the each() function on unless I created %hash myself
4098 because the internal iterator may not have started at base.