Merge branch 'mk/svn'
[git/dscho.git] / git-svn.perl
blob98687f54d79fa2f7212a5cdad80332b4231d50df
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41 # import functions from Git into our packages, en masse
42 no strict 'refs';
43 foreach (qw/command command_oneline command_noisy command_output_pipe
44 command_input_pipe command_close_pipe/) {
45 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
46 Git::SVN::Migration Git::SVN::Log Git::SVN),
47 __PACKAGE__) {
48 *{"${package}::$_"} = \&{"Git::$_"};
53 my ($SVN);
55 $sha1 = qr/[a-f\d]{40}/;
56 $sha1_short = qr/[a-f\d]{4,40}/;
57 my ($_stdin, $_help, $_edit,
58 $_message, $_file,
59 $_template, $_shared,
60 $_version, $_fetch_all, $_no_rebase,
61 $_merge, $_strategy, $_dry_run, $_local,
62 $_prefix, $_no_checkout, $_verbose);
63 $Git::SVN::_follow_parent = 1;
64 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
65 'config-dir=s' => \$Git::SVN::Ra::config_dir,
66 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
67 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
68 'authors-file|A=s' => \$_authors,
69 'repack:i' => \$Git::SVN::_repack,
70 'noMetadata' => \$Git::SVN::_no_metadata,
71 'useSvmProps' => \$Git::SVN::_use_svm_props,
72 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
73 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
74 'no-checkout' => \$_no_checkout,
75 'quiet|q' => \$_q,
76 'repack-flags|repack-args|repack-opts=s' =>
77 \$Git::SVN::_repack_flags,
78 %remote_opts );
80 my ($_trunk, $_tags, $_branches);
81 my %icv;
82 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
83 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
84 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
85 'minimize-url|m' => \$Git::SVN::_minimize_url,
86 'no-metadata' => sub { $icv{noMetadata} = 1 },
87 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
88 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
89 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
90 %remote_opts );
91 my %cmt_opts = ( 'edit|e' => \$_edit,
92 'rmdir' => \$SVN::Git::Editor::_rmdir,
93 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
94 'l=i' => \$SVN::Git::Editor::_rename_limit,
95 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
98 my %cmd = (
99 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
100 { 'revision|r=s' => \$_revision,
101 'fetch-all|all' => \$_fetch_all,
102 %fc_opts } ],
103 clone => [ \&cmd_clone, "Initialize and fetch revisions",
104 { 'revision|r=s' => \$_revision,
105 %fc_opts, %init_opts } ],
106 init => [ \&cmd_init, "Initialize a repo for tracking" .
107 " (requires URL argument)",
108 \%init_opts ],
109 'multi-init' => [ \&cmd_multi_init,
110 "Deprecated alias for ".
111 "'$0 init -T<trunk> -b<branches> -t<tags>'",
112 \%init_opts ],
113 dcommit => [ \&cmd_dcommit,
114 'Commit several diffs to merge with upstream',
115 { 'merge|m|M' => \$_merge,
116 'strategy|s=s' => \$_strategy,
117 'verbose|v' => \$_verbose,
118 'dry-run|n' => \$_dry_run,
119 'fetch-all|all' => \$_fetch_all,
120 'no-rebase' => \$_no_rebase,
121 %cmt_opts, %fc_opts } ],
122 'set-tree' => [ \&cmd_set_tree,
123 "Set an SVN repository to a git tree-ish",
124 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
125 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
126 { 'revision|r=i' => \$_revision } ],
127 'multi-fetch' => [ \&cmd_multi_fetch,
128 "Deprecated alias for $0 fetch --all",
129 { 'revision|r=s' => \$_revision, %fc_opts } ],
130 'migrate' => [ sub { },
131 # no-op, we automatically run this anyways,
132 'Migrate configuration/metadata/layout from
133 previous versions of git-svn',
134 { 'minimize' => \$Git::SVN::Migration::_minimize,
135 %remote_opts } ],
136 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
137 { 'limit=i' => \$Git::SVN::Log::limit,
138 'revision|r=s' => \$_revision,
139 'verbose|v' => \$Git::SVN::Log::verbose,
140 'incremental' => \$Git::SVN::Log::incremental,
141 'oneline' => \$Git::SVN::Log::oneline,
142 'show-commit' => \$Git::SVN::Log::show_commit,
143 'non-recursive' => \$Git::SVN::Log::non_recursive,
144 'authors-file|A=s' => \$_authors,
145 'color' => \$Git::SVN::Log::color,
146 'pager=s' => \$Git::SVN::Log::pager,
147 } ],
148 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
149 { } ],
150 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
151 { 'merge|m|M' => \$_merge,
152 'verbose|v' => \$_verbose,
153 'strategy|s=s' => \$_strategy,
154 'local|l' => \$_local,
155 'fetch-all|all' => \$_fetch_all,
156 %fc_opts } ],
157 'commit-diff' => [ \&cmd_commit_diff,
158 'Commit a diff between two trees',
159 { 'message|m=s' => \$_message,
160 'file|F=s' => \$_file,
161 'revision|r=s' => \$_revision,
162 %cmt_opts } ],
165 my $cmd;
166 for (my $i = 0; $i < @ARGV; $i++) {
167 if (defined $cmd{$ARGV[$i]}) {
168 $cmd = $ARGV[$i];
169 splice @ARGV, $i, 1;
170 last;
174 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
176 read_repo_config(\%opts);
177 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
178 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
179 'minimize-connections' => \$Git::SVN::Migration::_minimize,
180 'id|i=s' => \$Git::SVN::default_ref_id,
181 'svn-remote|remote|R=s' => sub {
182 $Git::SVN::no_reuse_existing = 1;
183 $Git::SVN::default_repo_id = $_[1] });
184 exit 1 if (!$rv && $cmd && $cmd ne 'log');
186 usage(0) if $_help;
187 version() if $_version;
188 usage(1) unless defined $cmd;
189 load_authors() if $_authors;
191 # make sure we're always running
192 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
193 unless (-d $ENV{GIT_DIR}) {
194 if ($git_dir_user_set) {
195 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
196 "but it is not a directory\n";
198 my $git_dir = delete $ENV{GIT_DIR};
199 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
200 unless (length $cdup) {
201 die "Already at toplevel, but $git_dir ",
202 "not found '$cdup'\n";
204 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
205 unless (-d $git_dir) {
206 die "$git_dir still not found after going to ",
207 "'$cdup'\n";
209 $ENV{GIT_DIR} = $git_dir;
212 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
213 Git::SVN::Migration::migration_check();
215 Git::SVN::init_vars();
216 eval {
217 Git::SVN::verify_remotes_sanity();
218 $cmd{$cmd}->[0]->(@ARGV);
220 fatal $@ if $@;
221 post_fetch_checkout();
222 exit 0;
224 ####################### primary functions ######################
225 sub usage {
226 my $exit = shift || 0;
227 my $fd = $exit ? \*STDERR : \*STDOUT;
228 print $fd <<"";
229 git-svn - bidirectional operations between a single Subversion tree and git
230 Usage: $0 <command> [options] [arguments]\n
232 print $fd "Available commands:\n" unless $cmd;
234 foreach (sort keys %cmd) {
235 next if $cmd && $cmd ne $_;
236 next if /^multi-/; # don't show deprecated commands
237 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
238 foreach (keys %{$cmd{$_}->[2]}) {
239 # mixed-case options are for .git/config only
240 next if /[A-Z]/ && /^[a-z]+$/i;
241 # prints out arguments as they should be passed:
242 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
243 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
244 "--$_" : "-$_" }
245 split /\|/,$_)," $x\n";
248 print $fd <<"";
249 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
250 arbitrary identifier if you're tracking multiple SVN branches/repositories in
251 one git repository and want to keep them separate. See git-svn(1) for more
252 information.
254 exit $exit;
257 sub version {
258 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
259 exit 0;
262 sub do_git_init_db {
263 unless (-d $ENV{GIT_DIR}) {
264 my @init_db = ('init');
265 push @init_db, "--template=$_template" if defined $_template;
266 if (defined $_shared) {
267 if ($_shared =~ /[a-z]/) {
268 push @init_db, "--shared=$_shared";
269 } else {
270 push @init_db, "--shared";
273 command_noisy(@init_db);
275 my $set;
276 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
277 foreach my $i (keys %icv) {
278 die "'$set' and '$i' cannot both be set\n" if $set;
279 next unless defined $icv{$i};
280 command_noisy('config', "$pfx.$i", $icv{$i});
281 $set = $i;
285 sub init_subdir {
286 my $repo_path = shift or return;
287 mkpath([$repo_path]) unless -d $repo_path;
288 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
289 $ENV{GIT_DIR} = '.git';
292 sub cmd_clone {
293 my ($url, $path) = @_;
294 if (!defined $path &&
295 (defined $_trunk || defined $_branches || defined $_tags) &&
296 $url !~ m#^[a-z\+]+://#) {
297 $path = $url;
299 $path = basename($url) if !defined $path || !length $path;
300 cmd_init($url, $path);
301 Git::SVN::fetch_all($Git::SVN::default_repo_id);
304 sub cmd_init {
305 if (defined $_trunk || defined $_branches || defined $_tags) {
306 return cmd_multi_init(@_);
308 my $url = shift or die "SVN repository location required ",
309 "as a command-line argument\n";
310 init_subdir(@_);
311 do_git_init_db();
313 Git::SVN->init($url);
316 sub cmd_fetch {
317 if (grep /^\d+=./, @_) {
318 die "'<rev>=<commit>' fetch arguments are ",
319 "no longer supported.\n";
321 my ($remote) = @_;
322 if (@_ > 1) {
323 die "Usage: $0 fetch [--all] [svn-remote]\n";
325 $remote ||= $Git::SVN::default_repo_id;
326 if ($_fetch_all) {
327 cmd_multi_fetch();
328 } else {
329 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
333 sub cmd_set_tree {
334 my (@commits) = @_;
335 if ($_stdin || !@commits) {
336 print "Reading from stdin...\n";
337 @commits = ();
338 while (<STDIN>) {
339 if (/\b($sha1_short)\b/o) {
340 unshift @commits, $1;
344 my @revs;
345 foreach my $c (@commits) {
346 my @tmp = command('rev-parse',$c);
347 if (scalar @tmp == 1) {
348 push @revs, $tmp[0];
349 } elsif (scalar @tmp > 1) {
350 push @revs, reverse(command('rev-list',@tmp));
351 } else {
352 fatal "Failed to rev-parse $c\n";
355 my $gs = Git::SVN->new;
356 my ($r_last, $cmt_last) = $gs->last_rev_commit;
357 $gs->fetch;
358 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
359 fatal "There are new revisions that were fetched ",
360 "and need to be merged (or acknowledged) ",
361 "before committing.\nlast rev: $r_last\n",
362 " current: $gs->{last_rev}\n";
364 $gs->set_tree($_) foreach @revs;
365 print "Done committing ",scalar @revs," revisions to SVN\n";
368 sub cmd_dcommit {
369 my $head = shift;
370 $head ||= 'HEAD';
371 my @refs;
372 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
373 unless ($gs) {
374 die "Unable to determine upstream SVN information from ",
375 "$head history\n";
377 my $c = $refs[-1];
378 my $last_rev;
379 foreach my $d (@refs) {
380 if (!verify_ref("$d~1")) {
381 fatal "Commit $d\n",
382 "has no parent commit, and therefore ",
383 "nothing to diff against.\n",
384 "You should be working from a repository ",
385 "originally created by git-svn\n";
387 unless (defined $last_rev) {
388 (undef, $last_rev, undef) = cmt_metadata("$d~1");
389 unless (defined $last_rev) {
390 fatal "Unable to extract revision information ",
391 "from commit $d~1\n";
394 if ($_dry_run) {
395 print "diff-tree $d~1 $d\n";
396 } else {
397 my %ed_opts = ( r => $last_rev,
398 log => get_commit_entry($d)->{log},
399 ra => Git::SVN::Ra->new($gs->full_url),
400 tree_a => "$d~1",
401 tree_b => $d,
402 editor_cb => sub {
403 print "Committed r$_[0]\n";
404 $last_rev = $_[0]; },
405 svn_path => '');
406 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
407 print "No changes\n$d~1 == $d\n";
411 return if $_dry_run;
412 unless ($gs) {
413 warn "Could not determine fetch information for $url\n",
414 "Will not attempt to fetch and rebase commits.\n",
415 "This probably means you have useSvmProps and should\n",
416 "now resync your SVN::Mirror repository.\n";
417 return;
419 $_fetch_all ? $gs->fetch_all : $gs->fetch;
420 unless ($_no_rebase) {
421 # we always want to rebase against the current HEAD, not any
422 # head that was passed to us
423 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
424 my @finish;
425 if (@diff) {
426 @finish = rebase_cmd();
427 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
428 "using @finish:\n", "@diff";
429 } else {
430 print "No changes between current HEAD and ",
431 $gs->refname, "\nResetting to the latest ",
432 $gs->refname, "\n";
433 @finish = qw/reset --mixed/;
435 command_noisy(@finish, $gs->refname);
439 sub cmd_find_rev {
440 my $revision_or_hash = shift;
441 my $result;
442 if ($revision_or_hash =~ /^r\d+$/) {
443 my $head = shift;
444 $head ||= 'HEAD';
445 my @refs;
446 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
447 unless ($gs) {
448 die "Unable to determine upstream SVN information from ",
449 "$head history\n";
451 my $desired_revision = substr($revision_or_hash, 1);
452 $result = $gs->rev_db_get($desired_revision);
453 } else {
454 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
455 $result = $rev;
457 print "$result\n" if $result;
460 sub cmd_rebase {
461 command_noisy(qw/update-index --refresh/);
462 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
463 unless ($gs) {
464 die "Unable to determine upstream SVN information from ",
465 "working tree history\n";
467 if (command(qw/diff-index HEAD --/)) {
468 print STDERR "Cannot rebase with uncommited changes:\n";
469 command_noisy('status');
470 exit 1;
472 unless ($_local) {
473 $_fetch_all ? $gs->fetch_all : $gs->fetch;
475 command_noisy(rebase_cmd(), $gs->refname);
478 sub cmd_show_ignore {
479 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
480 $gs ||= Git::SVN->new;
481 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
482 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
485 sub cmd_multi_init {
486 my $url = shift;
487 unless (defined $_trunk || defined $_branches || defined $_tags) {
488 usage(1);
491 # there are currently some bugs that prevent multi-init/multi-fetch
492 # setups from working well without this.
493 $Git::SVN::_minimize_url = 1;
495 $_prefix = '' unless defined $_prefix;
496 if (defined $url) {
497 $url =~ s#/+$##;
498 init_subdir(@_);
500 do_git_init_db();
501 if (defined $_trunk) {
502 my $trunk_ref = $_prefix . 'trunk';
503 # try both old-style and new-style lookups:
504 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
505 unless ($gs_trunk) {
506 my ($trunk_url, $trunk_path) =
507 complete_svn_url($url, $_trunk);
508 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
509 undef, $trunk_ref);
512 return unless defined $_branches || defined $_tags;
513 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
514 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
515 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
518 sub cmd_multi_fetch {
519 my $remotes = Git::SVN::read_all_remotes();
520 foreach my $repo_id (sort keys %$remotes) {
521 if ($remotes->{$repo_id}->{url}) {
522 Git::SVN::fetch_all($repo_id, $remotes);
527 # this command is special because it requires no metadata
528 sub cmd_commit_diff {
529 my ($ta, $tb, $url) = @_;
530 my $usage = "Usage: $0 commit-diff -r<revision> ".
531 "<tree-ish> <tree-ish> [<URL>]\n";
532 fatal($usage) if (!defined $ta || !defined $tb);
533 my $svn_path;
534 if (!defined $url) {
535 my $gs = eval { Git::SVN->new };
536 if (!$gs) {
537 fatal("Needed URL or usable git-svn --id in ",
538 "the command-line\n", $usage);
540 $url = $gs->{url};
541 $svn_path = $gs->{path};
543 unless (defined $_revision) {
544 fatal("-r|--revision is a required argument\n", $usage);
546 if (defined $_message && defined $_file) {
547 fatal("Both --message/-m and --file/-F specified ",
548 "for the commit message.\n",
549 "I have no idea what you mean\n");
551 if (defined $_file) {
552 $_message = file_to_s($_file);
553 } else {
554 $_message ||= get_commit_entry($tb)->{log};
556 my $ra ||= Git::SVN::Ra->new($url);
557 $svn_path ||= $ra->{svn_path};
558 my $r = $_revision;
559 if ($r eq 'HEAD') {
560 $r = $ra->get_latest_revnum;
561 } elsif ($r !~ /^\d+$/) {
562 die "revision argument: $r not understood by git-svn\n";
564 my %ed_opts = ( r => $r,
565 log => $_message,
566 ra => $ra,
567 tree_a => $ta,
568 tree_b => $tb,
569 editor_cb => sub { print "Committed r$_[0]\n" },
570 svn_path => $svn_path );
571 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
572 print "No changes\n$ta == $tb\n";
576 ########################### utility functions #########################
578 sub rebase_cmd {
579 my @cmd = qw/rebase/;
580 push @cmd, '-v' if $_verbose;
581 push @cmd, qw/--merge/ if $_merge;
582 push @cmd, "--strategy=$_strategy" if $_strategy;
583 @cmd;
586 sub post_fetch_checkout {
587 return if $_no_checkout;
588 my $gs = $Git::SVN::_head or return;
589 return if verify_ref('refs/heads/master^0');
591 my $valid_head = verify_ref('HEAD^0');
592 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
593 return if ($valid_head || !verify_ref('HEAD^0'));
595 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
596 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
597 return if -f $index;
599 chomp(my $bare = `git config --bool --get core.bare`);
600 return if $bare eq 'true';
601 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
602 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
603 print STDERR "Checked out HEAD:\n ",
604 $gs->full_url, " r", $gs->last_rev, "\n";
607 sub complete_svn_url {
608 my ($url, $path) = @_;
609 $path =~ s#/+$##;
610 if ($path !~ m#^[a-z\+]+://#) {
611 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
612 fatal("E: '$path' is not a complete URL ",
613 "and a separate URL is not specified\n");
615 return ($url, $path);
617 return ($path, '');
620 sub complete_url_ls_init {
621 my ($ra, $repo_path, $switch, $pfx) = @_;
622 unless ($repo_path) {
623 print STDERR "W: $switch not specified\n";
624 return;
626 $repo_path =~ s#/+$##;
627 if ($repo_path =~ m#^[a-z\+]+://#) {
628 $ra = Git::SVN::Ra->new($repo_path);
629 $repo_path = '';
630 } else {
631 $repo_path =~ s#^/+##;
632 unless ($ra) {
633 fatal("E: '$repo_path' is not a complete URL ",
634 "and a separate URL is not specified\n");
637 my $url = $ra->{url};
638 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
639 my $k = "svn-remote.$gs->{repo_id}.url";
640 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
641 if ($orig_url && ($orig_url ne $gs->{url})) {
642 die "$k already set: $orig_url\n",
643 "wanted to set to: $gs->{url}\n";
645 command_oneline('config', $k, $gs->{url}) unless $orig_url;
646 my $remote_path = "$ra->{svn_path}/$repo_path/*";
647 $remote_path =~ s#/+#/#g;
648 $remote_path =~ s#^/##g;
649 my ($n) = ($switch =~ /^--(\w+)/);
650 if (length $pfx && $pfx !~ m#/$#) {
651 die "--prefix='$pfx' must have a trailing slash '/'\n";
653 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
654 "$remote_path:refs/remotes/$pfx*");
657 sub verify_ref {
658 my ($ref) = @_;
659 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
660 { STDERR => 0 }); };
663 sub get_tree_from_treeish {
664 my ($treeish) = @_;
665 # $treeish can be a symbolic ref, too:
666 my $type = command_oneline(qw/cat-file -t/, $treeish);
667 my $expected;
668 while ($type eq 'tag') {
669 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
671 if ($type eq 'commit') {
672 $expected = (grep /^tree /, command(qw/cat-file commit/,
673 $treeish))[0];
674 ($expected) = ($expected =~ /^tree ($sha1)$/o);
675 die "Unable to get tree from $treeish\n" unless $expected;
676 } elsif ($type eq 'tree') {
677 $expected = $treeish;
678 } else {
679 die "$treeish is a $type, expected tree, tag or commit\n";
681 return $expected;
684 sub get_commit_entry {
685 my ($treeish) = shift;
686 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
687 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
688 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
689 open my $log_fh, '>', $commit_editmsg or croak $!;
691 my $type = command_oneline(qw/cat-file -t/, $treeish);
692 if ($type eq 'commit' || $type eq 'tag') {
693 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
694 $type, $treeish);
695 my $in_msg = 0;
696 while (<$msg_fh>) {
697 if (!$in_msg) {
698 $in_msg = 1 if (/^\s*$/);
699 } elsif (/^git-svn-id: /) {
700 # skip this for now, we regenerate the
701 # correct one on re-fetch anyways
702 # TODO: set *:merge properties or like...
703 } else {
704 print $log_fh $_ or croak $!;
707 command_close_pipe($msg_fh, $ctx);
709 close $log_fh or croak $!;
711 if ($_edit || ($type eq 'tree')) {
712 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
713 # TODO: strip out spaces, comments, like git-commit.sh
714 system($editor, $commit_editmsg);
716 rename $commit_editmsg, $commit_msg or croak $!;
717 open $log_fh, '<', $commit_msg or croak $!;
718 { local $/; chomp($log_entry{log} = <$log_fh>); }
719 close $log_fh or croak $!;
720 unlink $commit_msg;
721 \%log_entry;
724 sub s_to_file {
725 my ($str, $file, $mode) = @_;
726 open my $fd,'>',$file or croak $!;
727 print $fd $str,"\n" or croak $!;
728 close $fd or croak $!;
729 chmod ($mode &~ umask, $file) if (defined $mode);
732 sub file_to_s {
733 my $file = shift;
734 open my $fd,'<',$file or croak "$!: file: $file\n";
735 local $/;
736 my $ret = <$fd>;
737 close $fd or croak $!;
738 $ret =~ s/\s*$//s;
739 return $ret;
742 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
743 sub load_authors {
744 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
745 my $log = $cmd eq 'log';
746 while (<$authors>) {
747 chomp;
748 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
749 my ($user, $name, $email) = ($1, $2, $3);
750 if ($log) {
751 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
752 } else {
753 $users{$user} = [$name, $email];
756 close $authors or croak $!;
759 # convert GetOpt::Long specs for use by git-config
760 sub read_repo_config {
761 return unless -d $ENV{GIT_DIR};
762 my $opts = shift;
763 my @config_only;
764 foreach my $o (keys %$opts) {
765 # if we have mixedCase and a long option-only, then
766 # it's a config-only variable that we don't need for
767 # the command-line.
768 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
769 my $v = $opts->{$o};
770 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
771 $key =~ s/-//g;
772 my $arg = 'git-config';
773 $arg .= ' --int' if ($o =~ /[:=]i$/);
774 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
775 if (ref $v eq 'ARRAY') {
776 chomp(my @tmp = `$arg --get-all svn.$key`);
777 @$v = @tmp if @tmp;
778 } else {
779 chomp(my $tmp = `$arg --get svn.$key`);
780 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
781 $$v = $tmp;
785 delete @$opts{@config_only} if @config_only;
788 sub extract_metadata {
789 my $id = shift or return (undef, undef, undef);
790 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
791 \s([a-f\d\-]+)$/x);
792 if (!defined $rev || !$uuid || !$url) {
793 # some of the original repositories I made had
794 # identifiers like this:
795 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
797 return ($url, $rev, $uuid);
800 sub cmt_metadata {
801 return extract_metadata((grep(/^git-svn-id: /,
802 command(qw/cat-file commit/, shift)))[-1]);
805 sub working_head_info {
806 my ($head, $refs) = @_;
807 my ($fh, $ctx) = command_output_pipe('log', $head);
808 my $hash;
809 my %max;
810 while (<$fh>) {
811 if ( m{^commit ($::sha1)$} ) {
812 unshift @$refs, $hash if $hash and $refs;
813 $hash = $1;
814 next;
816 next unless s{^\s*(git-svn-id:)}{$1};
817 my ($url, $rev, $uuid) = extract_metadata($_);
818 if (defined $url && defined $rev) {
819 next if $max{$url} and $max{$url} < $rev;
820 if (my $gs = Git::SVN->find_by_url($url)) {
821 my $c = $gs->rev_db_get($rev);
822 if ($c && $c eq $hash) {
823 close $fh; # break the pipe
824 return ($url, $rev, $uuid, $gs);
825 } else {
826 $max{$url} ||= $gs->rev_db_max;
831 command_close_pipe($fh, $ctx);
832 (undef, undef, undef, undef);
835 package Git::SVN;
836 use strict;
837 use warnings;
838 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
839 $_repack $_repack_flags $_use_svm_props $_head
840 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
841 use Carp qw/croak/;
842 use File::Path qw/mkpath/;
843 use File::Copy qw/copy/;
844 use IPC::Open3;
846 my $_repack_nr;
847 # properties that we do not log:
848 my %SKIP_PROP;
849 BEGIN {
850 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
851 svn:special svn:executable
852 svn:entry:committed-rev
853 svn:entry:last-author
854 svn:entry:uuid
855 svn:entry:committed-date/;
857 # some options are read globally, but can be overridden locally
858 # per [svn-remote "..."] section. Command-line options will *NOT*
859 # override options set in an [svn-remote "..."] section
860 no strict 'refs';
861 for my $option (qw/follow_parent no_metadata use_svm_props
862 use_svnsync_props/) {
863 my $key = $option;
864 $key =~ tr/_//d;
865 my $prop = "-$option";
866 *$option = sub {
867 my ($self) = @_;
868 return $self->{$prop} if exists $self->{$prop};
869 my $k = "svn-remote.$self->{repo_id}.$key";
870 eval { command_oneline(qw/config --get/, $k) };
871 if ($@) {
872 $self->{$prop} = ${"Git::SVN::_$option"};
873 } else {
874 my $v = command_oneline(qw/config --bool/,$k);
875 $self->{$prop} = $v eq 'false' ? 0 : 1;
877 return $self->{$prop};
882 my %LOCKFILES;
883 END { unlink keys %LOCKFILES if %LOCKFILES }
885 sub resolve_local_globs {
886 my ($url, $fetch, $glob_spec) = @_;
887 return unless defined $glob_spec;
888 my $ref = $glob_spec->{ref};
889 my $path = $glob_spec->{path};
890 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
891 next unless m#^refs/remotes/$ref->{regex}$#;
892 my $p = $1;
893 my $pathname = $path->full_path($p);
894 my $refname = $ref->full_path($p);
895 if (my $existing = $fetch->{$pathname}) {
896 if ($existing ne $refname) {
897 die "Refspec conflict:\n",
898 "existing: refs/remotes/$existing\n",
899 " globbed: refs/remotes/$refname\n";
901 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
902 $u =~ s!^\Q$url\E(/|$)!! or die
903 "refs/remotes/$refname: '$url' not found in '$u'\n";
904 if ($pathname ne $u) {
905 warn "W: Refspec glob conflict ",
906 "(ref: refs/remotes/$refname):\n",
907 "expected path: $pathname\n",
908 " real path: $u\n",
909 "Continuing ahead with $u\n";
910 next;
912 } else {
913 $fetch->{$pathname} = $refname;
918 sub parse_revision_argument {
919 my ($base, $head) = @_;
920 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
921 return ($base, $head);
923 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
924 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
925 return ($head, $head) if ($::_revision eq 'HEAD');
926 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
927 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
928 die "revision argument: $::_revision not understood by git-svn\n";
931 sub fetch_all {
932 my ($repo_id, $remotes) = @_;
933 if (ref $repo_id) {
934 my $gs = $repo_id;
935 $repo_id = undef;
936 $repo_id = $gs->{repo_id};
938 $remotes ||= read_all_remotes();
939 my $remote = $remotes->{$repo_id} or
940 die "[svn-remote \"$repo_id\"] unknown\n";
941 my $fetch = $remote->{fetch};
942 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
943 my (@gs, @globs);
944 my $ra = Git::SVN::Ra->new($url);
945 my $uuid = $ra->get_uuid;
946 my $head = $ra->get_latest_revnum;
947 my $base = defined $fetch ? $head : 0;
949 # read the max revs for wildcard expansion (branches/*, tags/*)
950 foreach my $t (qw/branches tags/) {
951 defined $remote->{$t} or next;
952 push @globs, $remote->{$t};
953 my $max_rev = eval { tmp_config(qw/--int --get/,
954 "svn-remote.$repo_id.${t}-maxRev") };
955 if (defined $max_rev && ($max_rev < $base)) {
956 $base = $max_rev;
957 } elsif (!defined $max_rev) {
958 $base = 0;
962 if ($fetch) {
963 foreach my $p (sort keys %$fetch) {
964 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
965 my $lr = $gs->rev_db_max;
966 if (defined $lr) {
967 $base = $lr if ($lr < $base);
969 push @gs, $gs;
973 ($base, $head) = parse_revision_argument($base, $head);
974 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
977 sub read_all_remotes {
978 my $r = {};
979 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
980 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
981 $r->{$1}->{fetch}->{$2} = $3;
982 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
983 $r->{$1}->{url} = $2;
984 } elsif (m!^(.+)\.(branches|tags)=
985 (.*):refs/remotes/(.+)\s*$/!x) {
986 my ($p, $g) = ($3, $4);
987 my $rs = $r->{$1}->{$2} = {
988 t => $2,
989 remote => $1,
990 path => Git::SVN::GlobSpec->new($p),
991 ref => Git::SVN::GlobSpec->new($g) };
992 if (length($rs->{ref}->{right}) != 0) {
993 die "The '*' glob character must be the last ",
994 "character of '$g'\n";
1001 sub init_vars {
1002 if (defined $_repack) {
1003 $_repack = 1000 if ($_repack <= 0);
1004 $_repack_nr = $_repack;
1005 $_repack_flags ||= '-d';
1009 sub verify_remotes_sanity {
1010 return unless -d $ENV{GIT_DIR};
1011 my %seen;
1012 foreach (command(qw/config -l/)) {
1013 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1014 if ($seen{$1}) {
1015 die "Remote ref refs/remote/$1 is tracked by",
1016 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1017 "Please resolve this ambiguity in ",
1018 "your git configuration file before ",
1019 "continuing\n";
1021 $seen{$1} = $_;
1026 # we allow more chars than remotes2config.sh...
1027 sub sanitize_remote_name {
1028 my ($name) = @_;
1029 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1030 $name;
1033 sub find_existing_remote {
1034 my ($url, $remotes) = @_;
1035 return undef if $no_reuse_existing;
1036 my $existing;
1037 foreach my $repo_id (keys %$remotes) {
1038 my $u = $remotes->{$repo_id}->{url} or next;
1039 next if $u ne $url;
1040 $existing = $repo_id;
1041 last;
1043 $existing;
1046 sub init_remote_config {
1047 my ($self, $url, $no_write) = @_;
1048 $url =~ s!/+$!!; # strip trailing slash
1049 my $r = read_all_remotes();
1050 my $existing = find_existing_remote($url, $r);
1051 if ($existing) {
1052 unless ($no_write) {
1053 print STDERR "Using existing ",
1054 "[svn-remote \"$existing\"]\n";
1056 $self->{repo_id} = $existing;
1057 } elsif ($_minimize_url) {
1058 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1059 $existing = find_existing_remote($min_url, $r);
1060 if ($existing) {
1061 unless ($no_write) {
1062 print STDERR "Using existing ",
1063 "[svn-remote \"$existing\"]\n";
1065 $self->{repo_id} = $existing;
1067 if ($min_url ne $url) {
1068 unless ($no_write) {
1069 print STDERR "Using higher level of URL: ",
1070 "$url => $min_url\n";
1072 my $old_path = $self->{path};
1073 $self->{path} = $url;
1074 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1075 if (length $old_path) {
1076 $self->{path} .= "/$old_path";
1078 $url = $min_url;
1081 my $orig_url;
1082 if (!$existing) {
1083 # verify that we aren't overwriting anything:
1084 $orig_url = eval {
1085 command_oneline('config', '--get',
1086 "svn-remote.$self->{repo_id}.url")
1088 if ($orig_url && ($orig_url ne $url)) {
1089 die "svn-remote.$self->{repo_id}.url already set: ",
1090 "$orig_url\nwanted to set to: $url\n";
1093 my ($xrepo_id, $xpath) = find_ref($self->refname);
1094 if (defined $xpath) {
1095 die "svn-remote.$xrepo_id.fetch already set to track ",
1096 "$xpath:refs/remotes/", $self->refname, "\n";
1098 unless ($no_write) {
1099 command_noisy('config',
1100 "svn-remote.$self->{repo_id}.url", $url);
1101 command_noisy('config', '--add',
1102 "svn-remote.$self->{repo_id}.fetch",
1103 "$self->{path}:".$self->refname);
1105 $self->{url} = $url;
1108 sub find_by_url { # repos_root and, path are optional
1109 my ($class, $full_url, $repos_root, $path) = @_;
1111 return undef unless defined $full_url;
1112 remove_username($full_url);
1113 remove_username($repos_root) if defined $repos_root;
1114 my $remotes = read_all_remotes();
1115 if (defined $full_url && defined $repos_root && !defined $path) {
1116 $path = $full_url;
1117 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1119 foreach my $repo_id (keys %$remotes) {
1120 my $u = $remotes->{$repo_id}->{url} or next;
1121 remove_username($u);
1122 next if defined $repos_root && $repos_root ne $u;
1124 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1125 foreach (qw/branches tags/) {
1126 resolve_local_globs($u, $fetch,
1127 $remotes->{$repo_id}->{$_});
1129 my $p = $path;
1130 unless (defined $p) {
1131 $p = $full_url;
1132 $p =~ s#^\Q$u\E(?:/|$)## or next;
1134 foreach my $f (keys %$fetch) {
1135 next if $f ne $p;
1136 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1139 undef;
1142 sub init {
1143 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1144 my $self = _new($class, $repo_id, $ref_id, $path);
1145 if (defined $url) {
1146 $self->init_remote_config($url, $no_write);
1148 $self;
1151 sub find_ref {
1152 my ($ref_id) = @_;
1153 foreach (command(qw/config -l/)) {
1154 next unless m!^svn-remote\.(.+)\.fetch=
1155 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1156 my ($repo_id, $path, $ref) = ($1, $2, $3);
1157 if ($ref eq $ref_id) {
1158 $path = '' if ($path =~ m#^\./?#);
1159 return ($repo_id, $path);
1162 (undef, undef, undef);
1165 sub new {
1166 my ($class, $ref_id, $repo_id, $path) = @_;
1167 if (defined $ref_id && !defined $repo_id && !defined $path) {
1168 ($repo_id, $path) = find_ref($ref_id);
1169 if (!defined $repo_id) {
1170 die "Could not find a \"svn-remote.*.fetch\" key ",
1171 "in the repository configuration matching: ",
1172 "refs/remotes/$ref_id\n";
1175 my $self = _new($class, $repo_id, $ref_id, $path);
1176 if (!defined $self->{path} || !length $self->{path}) {
1177 my $fetch = command_oneline('config', '--get',
1178 "svn-remote.$repo_id.fetch",
1179 ":refs/remotes/$ref_id\$") or
1180 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1181 "\":refs/remotes/$ref_id\$\" in config\n";
1182 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1184 $self->{url} = command_oneline('config', '--get',
1185 "svn-remote.$repo_id.url") or
1186 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1187 $self->rebuild;
1188 $self;
1191 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1193 sub svm_uuid {
1194 my ($self) = @_;
1195 return $self->{svm}->{uuid} if $self->svm;
1196 $self->ra;
1197 unless ($self->{svm}) {
1198 die "SVM UUID not cached, and reading remotely failed\n";
1200 $self->{svm}->{uuid};
1203 sub svm {
1204 my ($self) = @_;
1205 return $self->{svm} if $self->{svm};
1206 my $svm;
1207 # see if we have it in our config, first:
1208 eval {
1209 my $section = "svn-remote.$self->{repo_id}";
1210 $svm = {
1211 source => tmp_config('--get', "$section.svm-source"),
1212 uuid => tmp_config('--get', "$section.svm-uuid"),
1213 replace => tmp_config('--get', "$section.svm-replace"),
1216 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1217 $self->{svm} = $svm;
1219 $self->{svm};
1222 sub _set_svm_vars {
1223 my ($self, $ra) = @_;
1224 return $ra if $self->svm;
1226 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1227 "(svm:source, svm:uuid) ",
1228 "from the following URLs:\n" );
1229 sub read_svm_props {
1230 my ($self, $ra, $path, $r) = @_;
1231 my $props = ($ra->get_dir($path, $r))[2];
1232 my $src = $props->{'svm:source'};
1233 my $uuid = $props->{'svm:uuid'};
1234 return undef if (!$src || !$uuid);
1236 chomp($src, $uuid);
1238 $uuid =~ m{^[0-9a-f\-]{30,}$}
1239 or die "doesn't look right - svm:uuid is '$uuid'\n";
1241 # the '!' is used to mark the repos_root!/relative/path
1242 $src =~ s{/?!/?}{/};
1243 $src =~ s{/+$}{}; # no trailing slashes please
1244 # username is of no interest
1245 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1247 my $replace = $ra->{url};
1248 $replace .= "/$path" if length $path;
1250 my $section = "svn-remote.$self->{repo_id}";
1251 tmp_config("$section.svm-source", $src);
1252 tmp_config("$section.svm-replace", $replace);
1253 tmp_config("$section.svm-uuid", $uuid);
1254 $self->{svm} = {
1255 source => $src,
1256 uuid => $uuid,
1257 replace => $replace
1261 my $r = $ra->get_latest_revnum;
1262 my $path = $self->{path};
1263 my %tried;
1264 while (length $path) {
1265 unless ($tried{"$self->{url}/$path"}) {
1266 return $ra if $self->read_svm_props($ra, $path, $r);
1267 $tried{"$self->{url}/$path"} = 1;
1269 $path =~ s#/?[^/]+$##;
1271 die "Path: '$path' should be ''\n" if $path ne '';
1272 return $ra if $self->read_svm_props($ra, $path, $r);
1273 $tried{"$self->{url}/$path"} = 1;
1275 if ($ra->{repos_root} eq $self->{url}) {
1276 die @err, (map { " $_\n" } keys %tried), "\n";
1279 # nope, make sure we're connected to the repository root:
1280 my $ok;
1281 my @tried_b;
1282 $path = $ra->{svn_path};
1283 $ra = Git::SVN::Ra->new($ra->{repos_root});
1284 while (length $path) {
1285 unless ($tried{"$ra->{url}/$path"}) {
1286 $ok = $self->read_svm_props($ra, $path, $r);
1287 last if $ok;
1288 $tried{"$ra->{url}/$path"} = 1;
1290 $path =~ s#/?[^/]+$##;
1292 die "Path: '$path' should be ''\n" if $path ne '';
1293 $ok ||= $self->read_svm_props($ra, $path, $r);
1294 $tried{"$ra->{url}/$path"} = 1;
1295 if (!$ok) {
1296 die @err, (map { " $_\n" } keys %tried), "\n";
1298 Git::SVN::Ra->new($self->{url});
1301 sub svnsync {
1302 my ($self) = @_;
1303 return $self->{svnsync} if $self->{svnsync};
1305 if ($self->no_metadata) {
1306 die "Can't have both 'noMetadata' and ",
1307 "'useSvnsyncProps' options set!\n";
1309 if ($self->rewrite_root) {
1310 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1311 "options set!\n";
1314 my $svnsync;
1315 # see if we have it in our config, first:
1316 eval {
1317 my $section = "svn-remote.$self->{repo_id}";
1318 $svnsync = {
1319 url => tmp_config('--get', "$section.svnsync-url"),
1320 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1323 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1324 return $self->{svnsync} = $svnsync;
1327 my $err = "useSvnsyncProps set, but failed to read " .
1328 "svnsync property: svn:sync-from-";
1329 my $rp = $self->ra->rev_proplist(0);
1331 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1332 $url =~ m{^[a-z\+]+://} or
1333 die "doesn't look right - svn:sync-from-url is '$url'\n";
1335 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1336 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1337 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1339 my $section = "svn-remote.$self->{repo_id}";
1340 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1341 tmp_config('--add', "$section.svnsync-url", $url);
1342 return $self->{svnsync} = { url => $url, uuid => $uuid };
1345 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1346 # remote lookup (useful for 'git svn log').
1347 sub ra_uuid {
1348 my ($self) = @_;
1349 unless ($self->{ra_uuid}) {
1350 my $key = "svn-remote.$self->{repo_id}.uuid";
1351 my $uuid = eval { tmp_config('--get', $key) };
1352 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1353 $self->{ra_uuid} = $uuid;
1354 } else {
1355 die "ra_uuid called without URL\n" unless $self->{url};
1356 $self->{ra_uuid} = $self->ra->get_uuid;
1357 tmp_config('--add', $key, $self->{ra_uuid});
1360 $self->{ra_uuid};
1363 sub ra {
1364 my ($self) = shift;
1365 my $ra = Git::SVN::Ra->new($self->{url});
1366 if ($self->use_svm_props && !$self->{svm}) {
1367 if ($self->no_metadata) {
1368 die "Can't have both 'noMetadata' and ",
1369 "'useSvmProps' options set!\n";
1370 } elsif ($self->use_svnsync_props) {
1371 die "Can't have both 'useSvnsyncProps' and ",
1372 "'useSvmProps' options set!\n";
1374 $ra = $self->_set_svm_vars($ra);
1375 $self->{-want_revprops} = 1;
1377 $ra;
1380 sub rel_path {
1381 my ($self) = @_;
1382 my $repos_root = $self->ra->{repos_root};
1383 return $self->{path} if ($self->{url} eq $repos_root);
1384 my $url = $self->{url} .
1385 (length $self->{path} ? "/$self->{path}" : $self->{path});
1386 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1387 $url;
1390 sub traverse_ignore {
1391 my ($self, $fh, $path, $r) = @_;
1392 $path =~ s#^/+##g;
1393 my $ra = $self->ra;
1394 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1395 my $p = $path;
1396 $p =~ s#^\Q$self->{path}\E(/|$)##;
1397 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1398 if (my $s = $props->{'svn:ignore'}) {
1399 $s =~ s/[\r\n]+/\n/g;
1400 chomp $s;
1401 if (length $p == 0) {
1402 $s =~ s#\n#\n/$p#g;
1403 print $fh "/$s\n";
1404 } else {
1405 $s =~ s#\n#\n/$p/#g;
1406 print $fh "/$p/$s\n";
1409 foreach (sort keys %$dirent) {
1410 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1411 $self->traverse_ignore($fh, "$path/$_", $r);
1415 sub last_rev { ($_[0]->last_rev_commit)[0] }
1416 sub last_commit { ($_[0]->last_rev_commit)[1] }
1418 # returns the newest SVN revision number and newest commit SHA1
1419 sub last_rev_commit {
1420 my ($self) = @_;
1421 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1422 return ($self->{last_rev}, $self->{last_commit});
1424 my $c = ::verify_ref($self->refname.'^0');
1425 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1426 my $rev = (::cmt_metadata($c))[1];
1427 if (defined $rev) {
1428 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1429 return ($rev, $c);
1432 my $db_path = $self->db_path;
1433 unless (-e $db_path) {
1434 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1435 return (undef, undef);
1437 my $offset = -41; # from tail
1438 my $rl;
1439 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1440 sysseek($fh, $offset, 2); # don't care for errors
1441 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1442 chomp $rl;
1443 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1444 $offset -= 41;
1445 sysseek($fh, $offset, 2); # don't care for errors
1446 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1447 chomp $rl;
1449 if ($c && $c ne $rl) {
1450 die "$db_path and ", $self->refname,
1451 " inconsistent!:\n$c != $rl\n";
1453 my $rev = sysseek($fh, 0, 1) or croak $!;
1454 $rev = ($rev - 41) / 41;
1455 close $fh or croak $!;
1456 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1457 return ($rev, $c);
1460 sub get_fetch_range {
1461 my ($self, $min, $max) = @_;
1462 $max ||= $self->ra->get_latest_revnum;
1463 $min ||= $self->rev_db_max;
1464 (++$min, $max);
1467 sub tmp_config {
1468 my (@args) = @_;
1469 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1470 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1471 if (! -f $config && -f $old_def_config) {
1472 rename $old_def_config, $config or
1473 die "Failed rename $old_def_config => $config: $!\n";
1475 my $old_config = $ENV{GIT_CONFIG};
1476 $ENV{GIT_CONFIG} = $config;
1477 $@ = undef;
1478 my @ret = eval {
1479 unless (-f $config) {
1480 mkfile($config);
1481 open my $fh, '>', $config or
1482 die "Can't open $config: $!\n";
1483 print $fh "; This file is used internally by ",
1484 "git-svn\n" or die
1485 "Couldn't write to $config: $!\n";
1486 print $fh "; You should not have to edit it\n" or
1487 die "Couldn't write to $config: $!\n";
1488 close $fh or die "Couldn't close $config: $!\n";
1490 command('config', @args);
1492 my $err = $@;
1493 if (defined $old_config) {
1494 $ENV{GIT_CONFIG} = $old_config;
1495 } else {
1496 delete $ENV{GIT_CONFIG};
1498 die $err if $err;
1499 wantarray ? @ret : $ret[0];
1502 sub tmp_index_do {
1503 my ($self, $sub) = @_;
1504 my $old_index = $ENV{GIT_INDEX_FILE};
1505 $ENV{GIT_INDEX_FILE} = $self->{index};
1506 $@ = undef;
1507 my @ret = eval {
1508 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1509 mkpath([$dir]) unless -d $dir;
1510 &$sub;
1512 my $err = $@;
1513 if (defined $old_index) {
1514 $ENV{GIT_INDEX_FILE} = $old_index;
1515 } else {
1516 delete $ENV{GIT_INDEX_FILE};
1518 die $err if $err;
1519 wantarray ? @ret : $ret[0];
1522 sub assert_index_clean {
1523 my ($self, $treeish) = @_;
1525 $self->tmp_index_do(sub {
1526 command_noisy('read-tree', $treeish) unless -e $self->{index};
1527 my $x = command_oneline('write-tree');
1528 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1529 /^tree ($::sha1)/mo);
1530 return if $y eq $x;
1532 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1533 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1534 command_noisy('read-tree', $treeish);
1535 $x = command_oneline('write-tree');
1536 if ($y ne $x) {
1537 ::fatal "trees ($treeish) $y != $x\n",
1538 "Something is seriously wrong...\n";
1543 sub get_commit_parents {
1544 my ($self, $log_entry) = @_;
1545 my (%seen, @ret, @tmp);
1546 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1547 if (my $ip = $self->{inject_parents}) {
1548 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1549 push @tmp, $commit;
1552 if (my $cur = ::verify_ref($self->refname.'^0')) {
1553 push @tmp, $cur;
1555 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1556 while (my $p = shift @tmp) {
1557 next if $seen{$p};
1558 $seen{$p} = 1;
1559 push @ret, $p;
1560 # MAXPARENT is defined to 16 in commit-tree.c:
1561 last if @ret >= 16;
1563 if (@tmp) {
1564 die "r$log_entry->{revision}: No room for parents:\n\t",
1565 join("\n\t", @tmp), "\n";
1567 @ret;
1570 sub rewrite_root {
1571 my ($self) = @_;
1572 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1573 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1574 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1575 if ($rwr) {
1576 $rwr =~ s#/+$##;
1577 if ($rwr !~ m#^[a-z\+]+://#) {
1578 die "$rwr is not a valid URL (key: $k)\n";
1581 $self->{-rewrite_root} = $rwr;
1584 sub metadata_url {
1585 my ($self) = @_;
1586 ($self->rewrite_root || $self->{url}) .
1587 (length $self->{path} ? '/' . $self->{path} : '');
1590 sub full_url {
1591 my ($self) = @_;
1592 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1595 sub do_git_commit {
1596 my ($self, $log_entry) = @_;
1597 my $lr = $self->last_rev;
1598 if (defined $lr && $lr >= $log_entry->{revision}) {
1599 die "Last fetched revision of ", $self->refname,
1600 " was r$lr, but we are about to fetch: ",
1601 "r$log_entry->{revision}!\n";
1603 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1604 croak "$log_entry->{revision} = $c already exists! ",
1605 "Why are we refetching it?\n";
1607 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1608 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1609 $log_entry->{email};
1610 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1612 my $tree = $log_entry->{tree};
1613 if (!defined $tree) {
1614 $tree = $self->tmp_index_do(sub {
1615 command_oneline('write-tree') });
1617 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1619 my @exec = ('git-commit-tree', $tree);
1620 foreach ($self->get_commit_parents($log_entry)) {
1621 push @exec, '-p', $_;
1623 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1624 or croak $!;
1625 print $msg_fh $log_entry->{log} or croak $!;
1626 unless ($self->no_metadata) {
1627 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1628 or croak $!;
1630 $msg_fh->flush == 0 or croak $!;
1631 close $msg_fh or croak $!;
1632 chomp(my $commit = do { local $/; <$out_fh> });
1633 close $out_fh or croak $!;
1634 waitpid $pid, 0;
1635 croak $? if $?;
1636 if ($commit !~ /^$::sha1$/o) {
1637 die "Failed to commit, invalid sha1: $commit\n";
1640 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1642 $self->{last_rev} = $log_entry->{revision};
1643 $self->{last_commit} = $commit;
1644 print "r$log_entry->{revision}";
1645 if (defined $log_entry->{svm_revision}) {
1646 print " (\@$log_entry->{svm_revision})";
1647 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1648 0, $self->svm_uuid);
1650 print " = $commit ($self->{ref_id})\n";
1651 if (defined $_repack && (--$_repack_nr == 0)) {
1652 $_repack_nr = $_repack;
1653 # repack doesn't use any arguments with spaces in them, does it?
1654 print "Running git repack $_repack_flags ...\n";
1655 command_noisy('repack', split(/\s+/, $_repack_flags));
1656 print "Done repacking\n";
1658 return $commit;
1661 sub match_paths {
1662 my ($self, $paths, $r) = @_;
1663 return 1 if $self->{path} eq '';
1664 if (my $path = $paths->{"/$self->{path}"}) {
1665 return ($path->{action} eq 'D') ? 0 : 1;
1667 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1668 if (grep /$self->{path_regex}/, keys %$paths) {
1669 return 1;
1671 my $c = '';
1672 foreach (split m#/#, $self->{path}) {
1673 $c .= "/$_";
1674 next unless ($paths->{$c} &&
1675 ($paths->{$c}->{action} =~ /^[AR]$/));
1676 if ($self->ra->check_path($self->{path}, $r) ==
1677 $SVN::Node::dir) {
1678 return 1;
1681 return 0;
1684 sub find_parent_branch {
1685 my ($self, $paths, $rev) = @_;
1686 return undef unless $self->follow_parent;
1687 unless (defined $paths) {
1688 my $err_handler = $SVN::Error::handler;
1689 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1690 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1691 $paths =
1692 Git::SVN::Ra::dup_changed_paths($_[0]) });
1693 $SVN::Error::handler = $err_handler;
1695 return undef unless defined $paths;
1697 # look for a parent from another branch:
1698 my @b_path_components = split m#/#, $self->rel_path;
1699 my @a_path_components;
1700 my $i;
1701 while (@b_path_components) {
1702 $i = $paths->{'/'.join('/', @b_path_components)};
1703 last if $i && defined $i->{copyfrom_path};
1704 unshift(@a_path_components, pop(@b_path_components));
1706 return undef unless defined $i && defined $i->{copyfrom_path};
1707 my $branch_from = $i->{copyfrom_path};
1708 if (@a_path_components) {
1709 print STDERR "branch_from: $branch_from => ";
1710 $branch_from .= '/'.join('/', @a_path_components);
1711 print STDERR $branch_from, "\n";
1713 my $r = $i->{copyfrom_rev};
1714 my $repos_root = $self->ra->{repos_root};
1715 my $url = $self->ra->{url};
1716 my $new_url = $repos_root . $branch_from;
1717 print STDERR "Found possible branch point: ",
1718 "$new_url => ", $self->full_url, ", $r\n";
1719 $branch_from =~ s#^/##;
1720 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1721 unless ($gs) {
1722 my $ref_id = $self->{ref_id};
1723 $ref_id =~ s/\@\d+$//;
1724 $ref_id .= "\@$r";
1725 # just grow a tail if we're not unique enough :x
1726 $ref_id .= '-' while find_ref($ref_id);
1727 print STDERR "Initializing parent: $ref_id\n";
1728 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1730 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1731 if (!defined $r0 || !defined $parent) {
1732 my ($base, $head) = parse_revision_argument(0, $r);
1733 if ($base <= $r) {
1734 $gs->fetch($base, $r);
1736 ($r0, $parent) = $gs->last_rev_commit;
1738 if (defined $r0 && defined $parent) {
1739 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1740 my $ed;
1741 if ($self->ra->can_do_switch) {
1742 $self->assert_index_clean($parent);
1743 print STDERR "Following parent with do_switch\n";
1744 # do_switch works with svn/trunk >= r22312, but that
1745 # is not included with SVN 1.4.3 (the latest version
1746 # at the moment), so we can't rely on it
1747 $self->{last_commit} = $parent;
1748 $ed = SVN::Git::Fetcher->new($self);
1749 $gs->ra->gs_do_switch($r0, $rev, $gs,
1750 $self->full_url, $ed)
1751 or die "SVN connection failed somewhere...\n";
1752 } else {
1753 print STDERR "Following parent with do_update\n";
1754 $ed = SVN::Git::Fetcher->new($self);
1755 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1756 or die "SVN connection failed somewhere...\n";
1758 print STDERR "Successfully followed parent\n";
1759 return $self->make_log_entry($rev, [$parent], $ed);
1761 return undef;
1764 sub do_fetch {
1765 my ($self, $paths, $rev) = @_;
1766 my $ed;
1767 my ($last_rev, @parents);
1768 if (my $lc = $self->last_commit) {
1769 # we can have a branch that was deleted, then re-added
1770 # under the same name but copied from another path, in
1771 # which case we'll have multiple parents (we don't
1772 # want to break the original ref, nor lose copypath info):
1773 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1774 push @{$log_entry->{parents}}, $lc;
1775 return $log_entry;
1777 $ed = SVN::Git::Fetcher->new($self);
1778 $last_rev = $self->{last_rev};
1779 $ed->{c} = $lc;
1780 @parents = ($lc);
1781 } else {
1782 $last_rev = $rev;
1783 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1784 return $log_entry;
1786 $ed = SVN::Git::Fetcher->new($self);
1788 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1789 die "SVN connection failed somewhere...\n";
1791 $self->make_log_entry($rev, \@parents, $ed);
1794 sub get_untracked {
1795 my ($self, $ed) = @_;
1796 my @out;
1797 my $h = $ed->{empty};
1798 foreach (sort keys %$h) {
1799 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1800 push @out, " $act: " . uri_encode($_);
1801 warn "W: $act: $_\n";
1803 foreach my $t (qw/dir_prop file_prop/) {
1804 $h = $ed->{$t} or next;
1805 foreach my $path (sort keys %$h) {
1806 my $ppath = $path eq '' ? '.' : $path;
1807 foreach my $prop (sort keys %{$h->{$path}}) {
1808 next if $SKIP_PROP{$prop};
1809 my $v = $h->{$path}->{$prop};
1810 my $t_ppath_prop = "$t: " .
1811 uri_encode($ppath) . ' ' .
1812 uri_encode($prop);
1813 if (defined $v) {
1814 push @out, " +$t_ppath_prop " .
1815 uri_encode($v);
1816 } else {
1817 push @out, " -$t_ppath_prop";
1822 foreach my $t (qw/absent_file absent_directory/) {
1823 $h = $ed->{$t} or next;
1824 foreach my $parent (sort keys %$h) {
1825 foreach my $path (sort @{$h->{$parent}}) {
1826 push @out, " $t: " .
1827 uri_encode("$parent/$path");
1828 warn "W: $t: $parent/$path ",
1829 "Insufficient permissions?\n";
1833 \@out;
1836 sub parse_svn_date {
1837 my $date = shift || return '+0000 1970-01-01 00:00:00';
1838 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1839 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1840 croak "Unable to parse date: $date\n";
1841 "+0000 $Y-$m-$d $H:$M:$S";
1844 sub check_author {
1845 my ($author) = @_;
1846 if (!defined $author || length $author == 0) {
1847 $author = '(no author)';
1849 if (defined $::_authors && ! defined $::users{$author}) {
1850 die "Author: $author not defined in $::_authors file\n";
1852 $author;
1855 sub make_log_entry {
1856 my ($self, $rev, $parents, $ed) = @_;
1857 my $untracked = $self->get_untracked($ed);
1859 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1860 print $un "r$rev\n" or croak $!;
1861 print $un $_, "\n" foreach @$untracked;
1862 my %log_entry = ( parents => $parents || [], revision => $rev,
1863 log => '');
1865 my $headrev;
1866 my $logged = delete $self->{logged_rev_props};
1867 if (!$logged || $self->{-want_revprops}) {
1868 my $rp = $self->ra->rev_proplist($rev);
1869 foreach (sort keys %$rp) {
1870 my $v = $rp->{$_};
1871 if (/^svn:(author|date|log)$/) {
1872 $log_entry{$1} = $v;
1873 } elsif ($_ eq 'svm:headrev') {
1874 $headrev = $v;
1875 } else {
1876 print $un " rev_prop: ", uri_encode($_), ' ',
1877 uri_encode($v), "\n";
1880 } else {
1881 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1883 close $un or croak $!;
1885 $log_entry{date} = parse_svn_date($log_entry{date});
1886 $log_entry{log} .= "\n";
1887 my $author = $log_entry{author} = check_author($log_entry{author});
1888 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1889 : ($author, undef);
1890 if (defined $headrev && $self->use_svm_props) {
1891 if ($self->rewrite_root) {
1892 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1893 "options set!\n";
1895 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1896 # we don't want "SVM: initializing mirror for junk" ...
1897 return undef if $r == 0;
1898 my $svm = $self->svm;
1899 if ($uuid ne $svm->{uuid}) {
1900 die "UUID mismatch on SVM path:\n",
1901 "expected: $svm->{uuid}\n",
1902 " got: $uuid\n";
1904 my $full_url = $self->full_url;
1905 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1906 die "Failed to replace '$svm->{replace}' with ",
1907 "'$svm->{source}' in $full_url\n";
1908 # throw away username for storing in records
1909 remove_username($full_url);
1910 $log_entry{metadata} = "$full_url\@$r $uuid";
1911 $log_entry{svm_revision} = $r;
1912 $email ||= "$author\@$uuid"
1913 } elsif ($self->use_svnsync_props) {
1914 my $full_url = $self->svnsync->{url};
1915 $full_url .= "/$self->{path}" if length $self->{path};
1916 remove_username($full_url);
1917 my $uuid = $self->svnsync->{uuid};
1918 $log_entry{metadata} = "$full_url\@$rev $uuid";
1919 $email ||= "$author\@$uuid"
1920 } else {
1921 my $url = $self->metadata_url;
1922 remove_username($url);
1923 $log_entry{metadata} = "$url\@$rev " .
1924 $self->ra->get_uuid;
1925 $email ||= "$author\@" . $self->ra->get_uuid;
1927 $log_entry{name} = $name;
1928 $log_entry{email} = $email;
1929 \%log_entry;
1932 sub fetch {
1933 my ($self, $min_rev, $max_rev, @parents) = @_;
1934 my ($last_rev, $last_commit) = $self->last_rev_commit;
1935 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1936 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1939 sub set_tree_cb {
1940 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1941 $self->{inject_parents} = { $rev => $tree };
1942 $self->fetch(undef, undef);
1945 sub set_tree {
1946 my ($self, $tree) = (shift, shift);
1947 my $log_entry = ::get_commit_entry($tree);
1948 unless ($self->{last_rev}) {
1949 fatal("Must have an existing revision to commit\n");
1951 my %ed_opts = ( r => $self->{last_rev},
1952 log => $log_entry->{log},
1953 ra => $self->ra,
1954 tree_a => $self->{last_commit},
1955 tree_b => $tree,
1956 editor_cb => sub {
1957 $self->set_tree_cb($log_entry, $tree, @_) },
1958 svn_path => $self->{path} );
1959 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1960 print "No changes\nr$self->{last_rev} = $tree\n";
1964 sub rebuild {
1965 my ($self) = @_;
1966 my $db_path = $self->db_path;
1967 return if (-e $db_path && ! -z $db_path);
1968 return unless ::verify_ref($self->refname.'^0');
1969 if (-f $self->{db_root}) {
1970 rename $self->{db_root}, $db_path or die
1971 "rename $self->{db_root} => $db_path failed: $!\n";
1972 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1973 symlink $base, $self->{db_root} or die
1974 "symlink $base => $self->{db_root} failed: $!\n";
1975 return;
1977 print "Rebuilding $db_path ...\n";
1978 my ($log, $ctx) = command_output_pipe("log", $self->refname);
1979 my $latest;
1980 my $full_url = $self->full_url;
1981 remove_username($full_url);
1982 my $svn_uuid;
1983 my $c;
1984 while (<$log>) {
1985 if ( m{^commit ($::sha1)$} ) {
1986 $c = $1;
1987 next;
1989 next unless s{^\s*(git-svn-id:)}{$1};
1990 my ($url, $rev, $uuid) = ::extract_metadata($_);
1991 remove_username($url);
1993 # ignore merges (from set-tree)
1994 next if (!defined $rev || !$uuid);
1996 # if we merged or otherwise started elsewhere, this is
1997 # how we break out of it
1998 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1999 ($full_url && $url && ($url ne $full_url))) {
2000 next;
2002 $latest ||= $rev;
2003 $svn_uuid ||= $uuid;
2005 $self->rev_db_set($rev, $c);
2006 print "r$rev = $c\n";
2008 command_close_pipe($log, $ctx);
2009 print "Done rebuilding $db_path\n";
2012 # rev_db:
2013 # Tie::File seems to be prone to offset errors if revisions get sparse,
2014 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2015 # one of my favorite modules is out :< Next up would be one of the DBM
2016 # modules, but I'm not sure which is most portable... So I'll just
2017 # go with something that's plain-text, but still capable of
2018 # being randomly accessed. So here's my ultra-simple fixed-width
2019 # database. All records are 40 characters + "\n", so it's easy to seek
2020 # to a revision: (41 * rev) is the byte offset.
2021 # A record of 40 0s denotes an empty revision.
2022 # And yes, it's still pretty fast (faster than Tie::File).
2023 # These files are disposable unless noMetadata or useSvmProps is set
2025 sub _rev_db_set {
2026 my ($fh, $rev, $commit) = @_;
2027 my $offset = $rev * 41;
2028 # assume that append is the common case:
2029 seek $fh, 0, 2 or croak $!;
2030 my $pos = tell $fh;
2031 if ($pos < $offset) {
2032 for (1 .. (($offset - $pos) / 41)) {
2033 print $fh (('0' x 40),"\n") or croak $!;
2036 seek $fh, $offset, 0 or croak $!;
2037 print $fh $commit,"\n" or croak $!;
2040 sub mkfile {
2041 my ($path) = @_;
2042 unless (-e $path) {
2043 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2044 mkpath([$dir]) unless -d $dir;
2045 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2046 close $fh or die "Couldn't close (create) $path: $!\n";
2050 sub rev_db_set {
2051 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2052 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2053 my $db = $self->db_path($uuid);
2054 my $db_lock = "$db.lock";
2055 my $sig;
2056 if ($update_ref) {
2057 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2058 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2060 mkfile($db);
2062 $LOCKFILES{$db_lock} = 1;
2063 my $sync;
2064 # both of these options make our .rev_db file very, very important
2065 # and we can't afford to lose it because rebuild() won't work
2066 if ($self->use_svm_props || $self->no_metadata) {
2067 $sync = 1;
2068 copy($db, $db_lock) or die "rev_db_set(@_): ",
2069 "Failed to copy: ",
2070 "$db => $db_lock ($!)\n";
2071 } else {
2072 rename $db, $db_lock or die "rev_db_set(@_): ",
2073 "Failed to rename: ",
2074 "$db => $db_lock ($!)\n";
2076 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2077 _rev_db_set($fh, $rev, $commit);
2078 if ($sync) {
2079 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2080 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2082 close $fh or croak $!;
2083 if ($update_ref) {
2084 $_head = $self;
2085 command_noisy('update-ref', '-m', "r$rev",
2086 $self->refname, $commit);
2088 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2089 "$db_lock => $db ($!)\n";
2090 delete $LOCKFILES{$db_lock};
2091 if ($update_ref) {
2092 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2093 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2094 kill $sig, $$ if defined $sig;
2098 sub rev_db_max {
2099 my ($self) = @_;
2100 $self->rebuild;
2101 my $db_path = $self->db_path;
2102 my @stat = stat $db_path or return 0;
2103 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2104 my $max = $stat[7] / 41;
2105 (($max > 0) ? $max - 1 : 0);
2108 sub rev_db_get {
2109 my ($self, $rev, $uuid) = @_;
2110 my $ret;
2111 my $offset = $rev * 41;
2112 my $db_path = $self->db_path($uuid);
2113 return undef unless -e $db_path;
2114 open my $fh, '<', $db_path or croak $!;
2115 if (sysseek($fh, $offset, 0) == $offset) {
2116 my $read = sysread($fh, $ret, 40);
2117 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2119 close $fh or croak $!;
2120 $ret;
2123 sub find_rev_before {
2124 my ($self, $rev, $eq_ok) = @_;
2125 --$rev unless $eq_ok;
2126 while ($rev > 0) {
2127 if (my $c = $self->rev_db_get($rev)) {
2128 return ($rev, $c);
2130 --$rev;
2132 return (undef, undef);
2135 sub _new {
2136 my ($class, $repo_id, $ref_id, $path) = @_;
2137 unless (defined $repo_id && length $repo_id) {
2138 $repo_id = $Git::SVN::default_repo_id;
2140 unless (defined $ref_id && length $ref_id) {
2141 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2143 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2144 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2145 $_[3] = $path = '' unless (defined $path);
2146 mkpath(["$ENV{GIT_DIR}/svn"]);
2147 bless {
2148 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2149 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2150 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2153 sub db_path {
2154 my ($self, $uuid) = @_;
2155 $uuid ||= $self->ra_uuid;
2156 "$self->{db_root}.$uuid";
2159 sub uri_encode {
2160 my ($f) = @_;
2161 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2165 sub remove_username {
2166 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2169 package Git::SVN::Prompt;
2170 use strict;
2171 use warnings;
2172 require SVN::Core;
2173 use vars qw/$_no_auth_cache $_username/;
2175 sub simple {
2176 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2177 $may_save = undef if $_no_auth_cache;
2178 $default_username = $_username if defined $_username;
2179 if (defined $default_username && length $default_username) {
2180 if (defined $realm && length $realm) {
2181 print STDERR "Authentication realm: $realm\n";
2182 STDERR->flush;
2184 $cred->username($default_username);
2185 } else {
2186 username($cred, $realm, $may_save, $pool);
2188 $cred->password(_read_password("Password for '" .
2189 $cred->username . "': ", $realm));
2190 $cred->may_save($may_save);
2191 $SVN::_Core::SVN_NO_ERROR;
2194 sub ssl_server_trust {
2195 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2196 $may_save = undef if $_no_auth_cache;
2197 print STDERR "Error validating server certificate for '$realm':\n";
2198 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2199 print STDERR " - The certificate is not issued by a trusted ",
2200 "authority. Use the\n",
2201 " fingerprint to validate the certificate manually!\n";
2203 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2204 print STDERR " - The certificate hostname does not match.\n";
2206 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2207 print STDERR " - The certificate is not yet valid.\n";
2209 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2210 print STDERR " - The certificate has expired.\n";
2212 if ($failures & $SVN::Auth::SSL::OTHER) {
2213 print STDERR " - The certificate has an unknown error.\n";
2215 printf STDERR
2216 "Certificate information:\n".
2217 " - Hostname: %s\n".
2218 " - Valid: from %s until %s\n".
2219 " - Issuer: %s\n".
2220 " - Fingerprint: %s\n",
2221 map $cert_info->$_, qw(hostname valid_from valid_until
2222 issuer_dname fingerprint);
2223 my $choice;
2224 prompt:
2225 print STDERR $may_save ?
2226 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2227 "(R)eject or accept (t)emporarily? ";
2228 STDERR->flush;
2229 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2230 if ($choice =~ /^t$/i) {
2231 $cred->may_save(undef);
2232 } elsif ($choice =~ /^r$/i) {
2233 return -1;
2234 } elsif ($may_save && $choice =~ /^p$/i) {
2235 $cred->may_save($may_save);
2236 } else {
2237 goto prompt;
2239 $cred->accepted_failures($failures);
2240 $SVN::_Core::SVN_NO_ERROR;
2243 sub ssl_client_cert {
2244 my ($cred, $realm, $may_save, $pool) = @_;
2245 $may_save = undef if $_no_auth_cache;
2246 print STDERR "Client certificate filename: ";
2247 STDERR->flush;
2248 chomp(my $filename = <STDIN>);
2249 $cred->cert_file($filename);
2250 $cred->may_save($may_save);
2251 $SVN::_Core::SVN_NO_ERROR;
2254 sub ssl_client_cert_pw {
2255 my ($cred, $realm, $may_save, $pool) = @_;
2256 $may_save = undef if $_no_auth_cache;
2257 $cred->password(_read_password("Password: ", $realm));
2258 $cred->may_save($may_save);
2259 $SVN::_Core::SVN_NO_ERROR;
2262 sub username {
2263 my ($cred, $realm, $may_save, $pool) = @_;
2264 $may_save = undef if $_no_auth_cache;
2265 if (defined $realm && length $realm) {
2266 print STDERR "Authentication realm: $realm\n";
2268 my $username;
2269 if (defined $_username) {
2270 $username = $_username;
2271 } else {
2272 print STDERR "Username: ";
2273 STDERR->flush;
2274 chomp($username = <STDIN>);
2276 $cred->username($username);
2277 $cred->may_save($may_save);
2278 $SVN::_Core::SVN_NO_ERROR;
2281 sub _read_password {
2282 my ($prompt, $realm) = @_;
2283 print STDERR $prompt;
2284 STDERR->flush;
2285 require Term::ReadKey;
2286 Term::ReadKey::ReadMode('noecho');
2287 my $password = '';
2288 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2289 last if $key =~ /[\012\015]/; # \n\r
2290 $password .= $key;
2292 Term::ReadKey::ReadMode('restore');
2293 print STDERR "\n";
2294 STDERR->flush;
2295 $password;
2298 package main;
2301 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2302 $SVN::Node::dir.$SVN::Node::unknown.
2303 $SVN::Node::none.$SVN::Node::file.
2304 $SVN::Node::dir.$SVN::Node::unknown.
2305 $SVN::Auth::SSL::CNMISMATCH.
2306 $SVN::Auth::SSL::NOTYETVALID.
2307 $SVN::Auth::SSL::EXPIRED.
2308 $SVN::Auth::SSL::UNKNOWNCA.
2309 $SVN::Auth::SSL::OTHER;
2312 package SVN::Git::Fetcher;
2313 use vars qw/@ISA/;
2314 use strict;
2315 use warnings;
2316 use Carp qw/croak/;
2317 use IO::File qw//;
2318 use Digest::MD5;
2320 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2321 sub new {
2322 my ($class, $git_svn) = @_;
2323 my $self = SVN::Delta::Editor->new;
2324 bless $self, $class;
2325 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2326 $self->{empty} = {};
2327 $self->{dir_prop} = {};
2328 $self->{file_prop} = {};
2329 $self->{absent_dir} = {};
2330 $self->{absent_file} = {};
2331 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2332 $self;
2335 sub set_path_strip {
2336 my ($self, $path) = @_;
2337 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2340 sub open_root {
2341 { path => '' };
2344 sub open_directory {
2345 my ($self, $path, $pb, $rev) = @_;
2346 { path => $path };
2349 sub git_path {
2350 my ($self, $path) = @_;
2351 if ($self->{path_strip}) {
2352 $path =~ s!$self->{path_strip}!! or
2353 die "Failed to strip path '$path' ($self->{path_strip})\n";
2355 $path;
2358 sub delete_entry {
2359 my ($self, $path, $rev, $pb) = @_;
2361 my $gpath = $self->git_path($path);
2362 return undef if ($gpath eq '');
2364 # remove entire directories.
2365 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2366 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2367 -r --name-only -z/,
2368 $self->{c}, '--', $gpath);
2369 local $/ = "\0";
2370 while (<$ls>) {
2371 chomp;
2372 $self->{gii}->remove($_);
2373 print "\tD\t$_\n" unless $::_q;
2375 print "\tD\t$gpath/\n" unless $::_q;
2376 command_close_pipe($ls, $ctx);
2377 $self->{empty}->{$path} = 0
2378 } else {
2379 $self->{gii}->remove($gpath);
2380 print "\tD\t$gpath\n" unless $::_q;
2382 undef;
2385 sub open_file {
2386 my ($self, $path, $pb, $rev) = @_;
2387 my $gpath = $self->git_path($path);
2388 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2389 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2390 unless (defined $mode && defined $blob) {
2391 die "$path was not found in commit $self->{c} (r$rev)\n";
2393 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2394 pool => SVN::Pool->new, action => 'M' };
2397 sub add_file {
2398 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2399 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2400 delete $self->{empty}->{$dir};
2401 { path => $path, mode_a => 100644, mode_b => 100644,
2402 pool => SVN::Pool->new, action => 'A' };
2405 sub add_directory {
2406 my ($self, $path, $cp_path, $cp_rev) = @_;
2407 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2408 delete $self->{empty}->{$dir};
2409 $self->{empty}->{$path} = 1;
2410 { path => $path };
2413 sub change_dir_prop {
2414 my ($self, $db, $prop, $value) = @_;
2415 $self->{dir_prop}->{$db->{path}} ||= {};
2416 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2417 undef;
2420 sub absent_directory {
2421 my ($self, $path, $pb) = @_;
2422 $self->{absent_dir}->{$pb->{path}} ||= [];
2423 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2424 undef;
2427 sub absent_file {
2428 my ($self, $path, $pb) = @_;
2429 $self->{absent_file}->{$pb->{path}} ||= [];
2430 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2431 undef;
2434 sub change_file_prop {
2435 my ($self, $fb, $prop, $value) = @_;
2436 if ($prop eq 'svn:executable') {
2437 if ($fb->{mode_b} != 120000) {
2438 $fb->{mode_b} = defined $value ? 100755 : 100644;
2440 } elsif ($prop eq 'svn:special') {
2441 $fb->{mode_b} = defined $value ? 120000 : 100644;
2442 } else {
2443 $self->{file_prop}->{$fb->{path}} ||= {};
2444 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2446 undef;
2449 sub apply_textdelta {
2450 my ($self, $fb, $exp) = @_;
2451 my $fh = IO::File->new_tmpfile;
2452 $fh->autoflush(1);
2453 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2454 # (but $base does not,) so dup() it for reading in close_file
2455 open my $dup, '<&', $fh or croak $!;
2456 my $base = IO::File->new_tmpfile;
2457 $base->autoflush(1);
2458 if ($fb->{blob}) {
2459 defined (my $pid = fork) or croak $!;
2460 if (!$pid) {
2461 open STDOUT, '>&', $base or croak $!;
2462 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2463 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2465 waitpid $pid, 0;
2466 croak $? if $?;
2468 if (defined $exp) {
2469 seek $base, 0, 0 or croak $!;
2470 my $md5 = Digest::MD5->new;
2471 $md5->addfile($base);
2472 my $got = $md5->hexdigest;
2473 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2474 "expected: $exp\n",
2475 " got: $got\n" if ($got ne $exp);
2478 seek $base, 0, 0 or croak $!;
2479 $fb->{fh} = $dup;
2480 $fb->{base} = $base;
2481 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2484 sub close_file {
2485 my ($self, $fb, $exp) = @_;
2486 my $hash;
2487 my $path = $self->git_path($fb->{path});
2488 if (my $fh = $fb->{fh}) {
2489 if (defined $exp) {
2490 seek($fh, 0, 0) or croak $!;
2491 my $md5 = Digest::MD5->new;
2492 $md5->addfile($fh);
2493 my $got = $md5->hexdigest;
2494 if ($got ne $exp) {
2495 die "Checksum mismatch: $path\n",
2496 "expected: $exp\n got: $got\n";
2499 sysseek($fh, 0, 0) or croak $!;
2500 if ($fb->{mode_b} == 120000) {
2501 sysread($fh, my $buf, 5) == 5 or croak $!;
2502 $buf eq 'link ' or die "$path has mode 120000",
2503 "but is not a link\n";
2505 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2506 if (!$pid) {
2507 open STDIN, '<&', $fh or croak $!;
2508 exec qw/git-hash-object -w --stdin/ or croak $!;
2510 chomp($hash = do { local $/; <$out> });
2511 close $out or croak $!;
2512 close $fh or croak $!;
2513 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2514 close $fb->{base} or croak $!;
2515 } else {
2516 $hash = $fb->{blob} or die "no blob information\n";
2518 $fb->{pool}->clear;
2519 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2520 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2521 undef;
2524 sub abort_edit {
2525 my $self = shift;
2526 $self->{nr} = $self->{gii}->{nr};
2527 delete $self->{gii};
2528 $self->SUPER::abort_edit(@_);
2531 sub close_edit {
2532 my $self = shift;
2533 $self->{git_commit_ok} = 1;
2534 $self->{nr} = $self->{gii}->{nr};
2535 delete $self->{gii};
2536 $self->SUPER::close_edit(@_);
2539 package SVN::Git::Editor;
2540 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2541 use strict;
2542 use warnings;
2543 use Carp qw/croak/;
2544 use IO::File;
2545 use Digest::MD5;
2547 sub new {
2548 my ($class, $opts) = @_;
2549 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2550 die "$_ required!\n" unless (defined $opts->{$_});
2553 my $pool = SVN::Pool->new;
2554 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2555 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2556 $opts->{r}, $mods);
2558 # $opts->{ra} functions should not be used after this:
2559 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2560 $opts->{editor_cb}, $pool);
2561 my $self = SVN::Delta::Editor->new(@ce, $pool);
2562 bless $self, $class;
2563 foreach (qw/svn_path r tree_a tree_b/) {
2564 $self->{$_} = $opts->{$_};
2566 $self->{url} = $opts->{ra}->{url};
2567 $self->{mods} = $mods;
2568 $self->{types} = $types;
2569 $self->{pool} = $pool;
2570 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2571 $self->{rm} = { };
2572 $self->{path_prefix} = length $self->{svn_path} ?
2573 "$self->{svn_path}/" : '';
2574 return $self;
2577 sub generate_diff {
2578 my ($tree_a, $tree_b) = @_;
2579 my @diff_tree = qw(diff-tree -z -r);
2580 if ($_cp_similarity) {
2581 push @diff_tree, "-C$_cp_similarity";
2582 } else {
2583 push @diff_tree, '-C';
2585 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2586 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2587 push @diff_tree, $tree_a, $tree_b;
2588 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2589 local $/ = "\0";
2590 my $state = 'meta';
2591 my @mods;
2592 while (<$diff_fh>) {
2593 chomp $_; # this gets rid of the trailing "\0"
2594 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2595 $::sha1\s($::sha1)\s
2596 ([MTCRAD])\d*$/xo) {
2597 push @mods, { mode_a => $1, mode_b => $2,
2598 sha1_b => $3, chg => $4 };
2599 if ($4 =~ /^(?:C|R)$/) {
2600 $state = 'file_a';
2601 } else {
2602 $state = 'file_b';
2604 } elsif ($state eq 'file_a') {
2605 my $x = $mods[$#mods] or croak "Empty array\n";
2606 if ($x->{chg} !~ /^(?:C|R)$/) {
2607 croak "Error parsing $_, $x->{chg}\n";
2609 $x->{file_a} = $_;
2610 $state = 'file_b';
2611 } elsif ($state eq 'file_b') {
2612 my $x = $mods[$#mods] or croak "Empty array\n";
2613 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2614 croak "Error parsing $_, $x->{chg}\n";
2616 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2617 croak "Error parsing $_, $x->{chg}\n";
2619 $x->{file_b} = $_;
2620 $state = 'meta';
2621 } else {
2622 croak "Error parsing $_\n";
2625 command_close_pipe($diff_fh, $ctx);
2626 \@mods;
2629 sub check_diff_paths {
2630 my ($ra, $pfx, $rev, $mods) = @_;
2631 my %types;
2632 $pfx .= '/' if length $pfx;
2634 sub type_diff_paths {
2635 my ($ra, $types, $path, $rev) = @_;
2636 my @p = split m#/+#, $path;
2637 my $c = shift @p;
2638 unless (defined $types->{$c}) {
2639 $types->{$c} = $ra->check_path($c, $rev);
2641 while (@p) {
2642 $c .= '/' . shift @p;
2643 next if defined $types->{$c};
2644 $types->{$c} = $ra->check_path($c, $rev);
2648 foreach my $m (@$mods) {
2649 foreach my $f (qw/file_a file_b/) {
2650 next unless defined $m->{$f};
2651 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2652 if (length $pfx.$dir && ! defined $types{$dir}) {
2653 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2657 \%types;
2660 sub split_path {
2661 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2664 sub repo_path {
2665 my ($self, $path) = @_;
2666 $self->{path_prefix}.(defined $path ? $path : '');
2669 sub url_path {
2670 my ($self, $path) = @_;
2671 $self->{url} . '/' . $self->repo_path($path);
2674 sub rmdirs {
2675 my ($self) = @_;
2676 my $rm = $self->{rm};
2677 delete $rm->{''}; # we never delete the url we're tracking
2678 return unless %$rm;
2680 foreach (keys %$rm) {
2681 my @d = split m#/#, $_;
2682 my $c = shift @d;
2683 $rm->{$c} = 1;
2684 while (@d) {
2685 $c .= '/' . shift @d;
2686 $rm->{$c} = 1;
2689 delete $rm->{$self->{svn_path}};
2690 delete $rm->{''}; # we never delete the url we're tracking
2691 return unless %$rm;
2693 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2694 $self->{tree_b});
2695 local $/ = "\0";
2696 while (<$fh>) {
2697 chomp;
2698 my @dn = split m#/#, $_;
2699 while (pop @dn) {
2700 delete $rm->{join '/', @dn};
2702 unless (%$rm) {
2703 close $fh;
2704 return;
2707 command_close_pipe($fh, $ctx);
2709 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2710 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2711 $self->close_directory($bat->{$d}, $p);
2712 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2713 print "\tD+\t$d/\n" unless $::_q;
2714 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2715 delete $bat->{$d};
2719 sub open_or_add_dir {
2720 my ($self, $full_path, $baton) = @_;
2721 my $t = $self->{types}->{$full_path};
2722 if (!defined $t) {
2723 die "$full_path not known in r$self->{r} or we have a bug!\n";
2725 if ($t == $SVN::Node::none) {
2726 return $self->add_directory($full_path, $baton,
2727 undef, -1, $self->{pool});
2728 } elsif ($t == $SVN::Node::dir) {
2729 return $self->open_directory($full_path, $baton,
2730 $self->{r}, $self->{pool});
2732 print STDERR "$full_path already exists in repository at ",
2733 "r$self->{r} and it is not a directory (",
2734 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2735 exit 1;
2738 sub ensure_path {
2739 my ($self, $path) = @_;
2740 my $bat = $self->{bat};
2741 my $repo_path = $self->repo_path($path);
2742 return $bat->{''} unless (length $repo_path);
2743 my @p = split m#/+#, $repo_path;
2744 my $c = shift @p;
2745 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2746 while (@p) {
2747 my $c0 = $c;
2748 $c .= '/' . shift @p;
2749 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2751 return $bat->{$c};
2754 sub A {
2755 my ($self, $m) = @_;
2756 my ($dir, $file) = split_path($m->{file_b});
2757 my $pbat = $self->ensure_path($dir);
2758 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2759 undef, -1);
2760 print "\tA\t$m->{file_b}\n" unless $::_q;
2761 $self->chg_file($fbat, $m);
2762 $self->close_file($fbat,undef,$self->{pool});
2765 sub C {
2766 my ($self, $m) = @_;
2767 my ($dir, $file) = split_path($m->{file_b});
2768 my $pbat = $self->ensure_path($dir);
2769 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2770 $self->url_path($m->{file_a}), $self->{r});
2771 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2772 $self->chg_file($fbat, $m);
2773 $self->close_file($fbat,undef,$self->{pool});
2776 sub delete_entry {
2777 my ($self, $path, $pbat) = @_;
2778 my $rpath = $self->repo_path($path);
2779 my ($dir, $file) = split_path($rpath);
2780 $self->{rm}->{$dir} = 1;
2781 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2784 sub R {
2785 my ($self, $m) = @_;
2786 my ($dir, $file) = split_path($m->{file_b});
2787 my $pbat = $self->ensure_path($dir);
2788 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2789 $self->url_path($m->{file_a}), $self->{r});
2790 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2791 $self->chg_file($fbat, $m);
2792 $self->close_file($fbat,undef,$self->{pool});
2794 ($dir, $file) = split_path($m->{file_a});
2795 $pbat = $self->ensure_path($dir);
2796 $self->delete_entry($m->{file_a}, $pbat);
2799 sub M {
2800 my ($self, $m) = @_;
2801 my ($dir, $file) = split_path($m->{file_b});
2802 my $pbat = $self->ensure_path($dir);
2803 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2804 $pbat,$self->{r},$self->{pool});
2805 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2806 $self->chg_file($fbat, $m);
2807 $self->close_file($fbat,undef,$self->{pool});
2810 sub T { shift->M(@_) }
2812 sub change_file_prop {
2813 my ($self, $fbat, $pname, $pval) = @_;
2814 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2817 sub chg_file {
2818 my ($self, $fbat, $m) = @_;
2819 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2820 $self->change_file_prop($fbat,'svn:executable','*');
2821 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2822 $self->change_file_prop($fbat,'svn:executable',undef);
2824 my $fh = IO::File->new_tmpfile or croak $!;
2825 if ($m->{mode_b} =~ /^120/) {
2826 print $fh 'link ' or croak $!;
2827 $self->change_file_prop($fbat,'svn:special','*');
2828 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2829 $self->change_file_prop($fbat,'svn:special',undef);
2831 defined(my $pid = fork) or croak $!;
2832 if (!$pid) {
2833 open STDOUT, '>&', $fh or croak $!;
2834 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2836 waitpid $pid, 0;
2837 croak $? if $?;
2838 $fh->flush == 0 or croak $!;
2839 seek $fh, 0, 0 or croak $!;
2841 my $md5 = Digest::MD5->new;
2842 $md5->addfile($fh) or croak $!;
2843 seek $fh, 0, 0 or croak $!;
2845 my $exp = $md5->hexdigest;
2846 my $pool = SVN::Pool->new;
2847 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2848 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2849 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2850 $pool->clear;
2852 close $fh or croak $!;
2855 sub D {
2856 my ($self, $m) = @_;
2857 my ($dir, $file) = split_path($m->{file_b});
2858 my $pbat = $self->ensure_path($dir);
2859 print "\tD\t$m->{file_b}\n" unless $::_q;
2860 $self->delete_entry($m->{file_b}, $pbat);
2863 sub close_edit {
2864 my ($self) = @_;
2865 my ($p,$bat) = ($self->{pool}, $self->{bat});
2866 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2867 next if $_ eq '';
2868 $self->close_directory($bat->{$_}, $p);
2870 $self->close_directory($bat->{''}, $p);
2871 $self->SUPER::close_edit($p);
2872 $p->clear;
2875 sub abort_edit {
2876 my ($self) = @_;
2877 $self->SUPER::abort_edit($self->{pool});
2880 sub DESTROY {
2881 my $self = shift;
2882 $self->SUPER::DESTROY(@_);
2883 $self->{pool}->clear;
2886 # this drives the editor
2887 sub apply_diff {
2888 my ($self) = @_;
2889 my $mods = $self->{mods};
2890 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2891 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2892 my $f = $m->{chg};
2893 if (defined $o{$f}) {
2894 $self->$f($m);
2895 } else {
2896 fatal("Invalid change type: $f\n");
2899 $self->rmdirs if $_rmdir;
2900 if (@$mods == 0) {
2901 $self->abort_edit;
2902 } else {
2903 $self->close_edit;
2905 return scalar @$mods;
2908 package Git::SVN::Ra;
2909 use vars qw/@ISA $config_dir $_log_window_size/;
2910 use strict;
2911 use warnings;
2912 my ($can_do_switch, %ignored_err, $RA);
2914 BEGIN {
2915 # enforce temporary pool usage for some simple functions
2916 no strict 'refs';
2917 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
2918 my $SUPER = "SUPER::$f";
2919 *$f = sub {
2920 my $self = shift;
2921 my $pool = SVN::Pool->new;
2922 my @ret = $self->$SUPER(@_,$pool);
2923 $pool->clear;
2924 wantarray ? @ret : $ret[0];
2929 sub new {
2930 my ($class, $url) = @_;
2931 $url =~ s!/+$!!;
2932 return $RA if ($RA && $RA->{url} eq $url);
2934 SVN::_Core::svn_config_ensure($config_dir, undef);
2935 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2936 SVN::Client::get_simple_provider(),
2937 SVN::Client::get_ssl_server_trust_file_provider(),
2938 SVN::Client::get_simple_prompt_provider(
2939 \&Git::SVN::Prompt::simple, 2),
2940 SVN::Client::get_ssl_client_cert_file_provider(),
2941 SVN::Client::get_ssl_client_cert_prompt_provider(
2942 \&Git::SVN::Prompt::ssl_client_cert, 2),
2943 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2944 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2945 SVN::Client::get_username_provider(),
2946 SVN::Client::get_ssl_server_trust_prompt_provider(
2947 \&Git::SVN::Prompt::ssl_server_trust),
2948 SVN::Client::get_username_prompt_provider(
2949 \&Git::SVN::Prompt::username, 2),
2951 my $config = SVN::Core::config_get_config($config_dir);
2952 my $self = SVN::Ra->new(url => $url, auth => $baton,
2953 config => $config,
2954 pool => SVN::Pool->new,
2955 auth_provider_callbacks => $callbacks);
2956 $self->{svn_path} = $url;
2957 $self->{repos_root} = $self->get_repos_root;
2958 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2959 $self->{cache} = { check_path => { r => 0, data => {} },
2960 get_dir => { r => 0, data => {} } };
2961 $RA = bless $self, $class;
2964 sub check_path {
2965 my ($self, $path, $r) = @_;
2966 my $cache = $self->{cache}->{check_path};
2967 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
2968 return $cache->{data}->{$path};
2970 my $pool = SVN::Pool->new;
2971 my $t = $self->SUPER::check_path($path, $r, $pool);
2972 $pool->clear;
2973 if ($r != $cache->{r}) {
2974 %{$cache->{data}} = ();
2975 $cache->{r} = $r;
2977 $cache->{data}->{$path} = $t;
2980 sub get_dir {
2981 my ($self, $dir, $r) = @_;
2982 my $cache = $self->{cache}->{get_dir};
2983 if ($r == $cache->{r}) {
2984 if (my $x = $cache->{data}->{$dir}) {
2985 return wantarray ? @$x : $x->[0];
2988 my $pool = SVN::Pool->new;
2989 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
2990 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
2991 $pool->clear;
2992 if ($r != $cache->{r}) {
2993 %{$cache->{data}} = ();
2994 $cache->{r} = $r;
2996 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
2997 wantarray ? (\%dirents, $r, $props) : \%dirents;
3000 sub DESTROY {
3001 # do not call the real DESTROY since we store ourselves in $RA
3004 sub get_log {
3005 my ($self, @args) = @_;
3006 my $pool = SVN::Pool->new;
3007 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3008 my $ret = $self->SUPER::get_log(@args, $pool);
3009 $pool->clear;
3010 $ret;
3013 sub get_commit_editor {
3014 my ($self, $log, $cb, $pool) = @_;
3015 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3016 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3019 sub gs_do_update {
3020 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3021 my $new = ($rev_a == $rev_b);
3022 my $path = $gs->{path};
3024 if ($new && -e $gs->{index}) {
3025 unlink $gs->{index} or die
3026 "Couldn't unlink index: $gs->{index}: $!\n";
3028 my $pool = SVN::Pool->new;
3029 $editor->set_path_strip($path);
3030 my (@pc) = split m#/#, $path;
3031 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3032 1, $editor, $pool);
3033 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3035 # Since we can't rely on svn_ra_reparent being available, we'll
3036 # just have to do some magic with set_path to make it so
3037 # we only want a partial path.
3038 my $sp = '';
3039 my $final = join('/', @pc);
3040 while (@pc) {
3041 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3042 $sp .= '/' if length $sp;
3043 $sp .= shift @pc;
3045 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3047 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3049 $reporter->finish_report($pool);
3050 $pool->clear;
3051 $editor->{git_commit_ok};
3054 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3055 # svn_ra_reparent didn't work before 1.4)
3056 sub gs_do_switch {
3057 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3058 my $path = $gs->{path};
3059 my $pool = SVN::Pool->new;
3061 my $full_url = $self->{url};
3062 my $old_url = $full_url;
3063 $full_url .= "/$path" if length $path;
3064 my ($ra, $reparented);
3065 if ($old_url ne $full_url) {
3066 if ($old_url !~ m#^svn(\+ssh)?://#) {
3067 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3068 $pool);
3069 $self->{url} = $full_url;
3070 $reparented = 1;
3071 } else {
3072 $ra = Git::SVN::Ra->new($full_url);
3075 $ra ||= $self;
3076 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3077 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3078 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3079 $reporter->finish_report($pool);
3081 if ($reparented) {
3082 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3083 $self->{url} = $old_url;
3086 $pool->clear;
3087 $editor->{git_commit_ok};
3090 sub longest_common_path {
3091 my ($gsv, $globs) = @_;
3092 my %common;
3093 my $common_max = scalar @$gsv;
3095 foreach my $gs (@$gsv) {
3096 my @tmp = split m#/#, $gs->{path};
3097 my $p = '';
3098 foreach (@tmp) {
3099 $p .= length($p) ? "/$_" : $_;
3100 $common{$p} ||= 0;
3101 $common{$p}++;
3104 $globs ||= [];
3105 $common_max += scalar @$globs;
3106 foreach my $glob (@$globs) {
3107 my @tmp = split m#/#, $glob->{path}->{left};
3108 my $p = '';
3109 foreach (@tmp) {
3110 $p .= length($p) ? "/$_" : $_;
3111 $common{$p} ||= 0;
3112 $common{$p}++;
3116 my $longest_path = '';
3117 foreach (sort {length $b <=> length $a} keys %common) {
3118 if ($common{$_} == $common_max) {
3119 $longest_path = $_;
3120 last;
3123 $longest_path;
3126 sub gs_fetch_loop_common {
3127 my ($self, $base, $head, $gsv, $globs) = @_;
3128 return if ($base > $head);
3129 my $inc = $_log_window_size;
3130 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3131 my $longest_path = longest_common_path($gsv, $globs);
3132 while (1) {
3133 my %revs;
3134 my $err;
3135 my $err_handler = $SVN::Error::handler;
3136 $SVN::Error::handler = sub {
3137 ($err) = @_;
3138 skip_unknown_revs($err);
3140 sub _cb {
3141 my ($paths, $r, $author, $date, $log) = @_;
3142 [ dup_changed_paths($paths),
3143 { author => $author, date => $date, log => $log } ];
3145 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3146 sub { $revs{$_[1]} = _cb(@_) });
3147 if ($err && $max >= $head) {
3148 print STDERR "Path '$longest_path' ",
3149 "was probably deleted:\n",
3150 $err->expanded_message,
3151 "\nWill attempt to follow ",
3152 "revisions r$min .. r$max ",
3153 "committed before the deletion\n";
3154 my $hi = $max;
3155 while (--$hi >= $min) {
3156 my $ok;
3157 $self->get_log([$longest_path], $min, $hi,
3158 0, 1, 1, sub {
3159 $ok ||= $_[1];
3160 $revs{$_[1]} = _cb(@_) });
3161 if ($ok) {
3162 print STDERR "r$min .. r$ok OK\n";
3163 last;
3167 $SVN::Error::handler = $err_handler;
3169 my %exists = map { $_->{path} => $_ } @$gsv;
3170 foreach my $r (sort {$a <=> $b} keys %revs) {
3171 my ($paths, $logged) = @{$revs{$r}};
3173 foreach my $gs ($self->match_globs(\%exists, $paths,
3174 $globs, $r)) {
3175 if ($gs->rev_db_max >= $r) {
3176 next;
3178 next unless $gs->match_paths($paths, $r);
3179 $gs->{logged_rev_props} = $logged;
3180 if (my $last_commit = $gs->last_commit) {
3181 $gs->assert_index_clean($last_commit);
3183 my $log_entry = $gs->do_fetch($paths, $r);
3184 if ($log_entry) {
3185 $gs->do_git_commit($log_entry);
3188 foreach my $g (@$globs) {
3189 my $k = "svn-remote.$g->{remote}." .
3190 "$g->{t}-maxRev";
3191 Git::SVN::tmp_config($k, $r);
3194 # pre-fill the .rev_db since it'll eventually get filled in
3195 # with '0' x40 if something new gets committed
3196 foreach my $gs (@$gsv) {
3197 next if defined $gs->rev_db_get($max);
3198 $gs->rev_db_set($max, 0 x40);
3200 foreach my $g (@$globs) {
3201 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3202 Git::SVN::tmp_config($k, $max);
3204 last if $max >= $head;
3205 $min = $max + 1;
3206 $max += $inc;
3207 $max = $head if ($max > $head);
3211 sub match_globs {
3212 my ($self, $exists, $paths, $globs, $r) = @_;
3214 sub get_dir_check {
3215 my ($self, $exists, $g, $r) = @_;
3216 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3217 return unless scalar @x == 3;
3218 my $dirents = $x[0];
3219 foreach my $de (keys %$dirents) {
3220 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3221 my $p = $g->{path}->full_path($de);
3222 next if $exists->{$p};
3223 next if (length $g->{path}->{right} &&
3224 ($self->check_path($p, $r) !=
3225 $SVN::Node::dir));
3226 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3227 $g->{ref}->full_path($de), 1);
3230 foreach my $g (@$globs) {
3231 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3232 if ($path->{action} =~ /^[AR]$/) {
3233 get_dir_check($self, $exists, $g, $r);
3236 foreach (keys %$paths) {
3237 if (/$g->{path}->{left_regex}/ &&
3238 !/$g->{path}->{regex}/) {
3239 next if $paths->{$_}->{action} !~ /^[AR]$/;
3240 get_dir_check($self, $exists, $g, $r);
3242 next unless /$g->{path}->{regex}/;
3243 my $p = $1;
3244 my $pathname = $g->{path}->full_path($p);
3245 next if $exists->{$pathname};
3246 next if ($self->check_path($pathname, $r) !=
3247 $SVN::Node::dir);
3248 $exists->{$pathname} = Git::SVN->init(
3249 $self->{url}, $pathname, undef,
3250 $g->{ref}->full_path($p), 1);
3252 my $c = '';
3253 foreach (split m#/#, $g->{path}->{left}) {
3254 $c .= "/$_";
3255 next unless ($paths->{$c} &&
3256 ($paths->{$c}->{action} =~ /^[AR]$/));
3257 get_dir_check($self, $exists, $g, $r);
3260 values %$exists;
3263 sub minimize_url {
3264 my ($self) = @_;
3265 return $self->{url} if ($self->{url} eq $self->{repos_root});
3266 my $url = $self->{repos_root};
3267 my @components = split(m!/!, $self->{svn_path});
3268 my $c = '';
3269 do {
3270 $url .= "/$c" if length $c;
3271 eval { (ref $self)->new($url)->get_latest_revnum };
3272 } while ($@ && ($c = shift @components));
3273 $url;
3276 sub can_do_switch {
3277 my $self = shift;
3278 unless (defined $can_do_switch) {
3279 my $pool = SVN::Pool->new;
3280 my $rep = eval {
3281 $self->do_switch(1, '', 0, $self->{url},
3282 SVN::Delta::Editor->new, $pool);
3284 if ($@) {
3285 $can_do_switch = 0;
3286 } else {
3287 $rep->abort_report($pool);
3288 $can_do_switch = 1;
3290 $pool->clear;
3292 $can_do_switch;
3295 sub skip_unknown_revs {
3296 my ($err) = @_;
3297 my $errno = $err->apr_err();
3298 # Maybe the branch we're tracking didn't
3299 # exist when the repo started, so it's
3300 # not an error if it doesn't, just continue
3302 # Wonderfully consistent library, eh?
3303 # 160013 - svn:// and file://
3304 # 175002 - http(s)://
3305 # 175007 - http(s):// (this repo required authorization, too...)
3306 # More codes may be discovered later...
3307 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3308 my $err_key = $err->expanded_message;
3309 # revision numbers change every time, filter them out
3310 $err_key =~ s/\d+/\0/g;
3311 $err_key = "$errno\0$err_key";
3312 unless ($ignored_err{$err_key}) {
3313 warn "W: Ignoring error from SVN, path probably ",
3314 "does not exist: ($errno): ",
3315 $err->expanded_message,"\n";
3316 $ignored_err{$err_key} = 1;
3318 return;
3320 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3323 # svn_log_changed_path_t objects passed to get_log are likely to be
3324 # overwritten even if only the refs are copied to an external variable,
3325 # so we should dup the structures in their entirety. Using an externally
3326 # passed pool (instead of our temporary and quickly cleared pool in
3327 # Git::SVN::Ra) does not help matters at all...
3328 sub dup_changed_paths {
3329 my ($paths) = @_;
3330 return undef unless $paths;
3331 my %ret;
3332 foreach my $p (keys %$paths) {
3333 my $i = $paths->{$p};
3334 my %s = map { $_ => $i->$_ }
3335 qw/copyfrom_path copyfrom_rev action/;
3336 $ret{$p} = \%s;
3338 \%ret;
3341 package Git::SVN::Log;
3342 use strict;
3343 use warnings;
3344 use POSIX qw/strftime/;
3345 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3346 %rusers $show_commit $incremental/;
3347 my $l_fmt;
3349 sub cmt_showable {
3350 my ($c) = @_;
3351 return 1 if defined $c->{r};
3353 # big commit message got truncated by the 16k pretty buffer in rev-list
3354 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3355 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3356 @{$c->{l}} = ();
3357 my @log = command(qw/cat-file commit/, $c->{c});
3359 # shift off the headers
3360 shift @log while ($log[0] ne '');
3361 shift @log;
3363 # TODO: make $c->{l} not have a trailing newline in the future
3364 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3366 (undef, $c->{r}, undef) = ::extract_metadata(
3367 (grep(/^git-svn-id: /, @log))[-1]);
3369 return defined $c->{r};
3372 sub log_use_color {
3373 return 1 if $color;
3374 my ($dc, $dcvar);
3375 $dcvar = 'color.diff';
3376 $dc = `git-config --get $dcvar`;
3377 if ($dc eq '') {
3378 # nothing at all; fallback to "diff.color"
3379 $dcvar = 'diff.color';
3380 $dc = `git-config --get $dcvar`;
3382 chomp($dc);
3383 if ($dc eq 'auto') {
3384 my $pc;
3385 $pc = `git-config --get color.pager`;
3386 if ($pc eq '') {
3387 # does not have it -- fallback to pager.color
3388 $pc = `git-config --bool --get pager.color`;
3390 else {
3391 $pc = `git-config --bool --get color.pager`;
3392 if ($?) {
3393 $pc = 'false';
3396 chomp($pc);
3397 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3398 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3400 return 0;
3402 return 0 if $dc eq 'never';
3403 return 1 if $dc eq 'always';
3404 chomp($dc = `git-config --bool --get $dcvar`);
3405 return ($dc eq 'true');
3408 sub git_svn_log_cmd {
3409 my ($r_min, $r_max, @args) = @_;
3410 my $head = 'HEAD';
3411 foreach my $x (@args) {
3412 last if $x eq '--';
3413 next unless ::verify_ref("$x^0");
3414 $head = $x;
3415 last;
3418 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3419 $gs ||= Git::SVN->_new;
3420 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3421 $gs->refname);
3422 push @cmd, '-r' unless $non_recursive;
3423 push @cmd, qw/--raw --name-status/ if $verbose;
3424 push @cmd, '--color' if log_use_color();
3425 return @cmd unless defined $r_max;
3426 if ($r_max == $r_min) {
3427 push @cmd, '--max-count=1';
3428 if (my $c = $gs->rev_db_get($r_max)) {
3429 push @cmd, $c;
3431 } else {
3432 my ($c_min, $c_max);
3433 $c_max = $gs->rev_db_get($r_max);
3434 $c_min = $gs->rev_db_get($r_min);
3435 if (defined $c_min && defined $c_max) {
3436 if ($r_max > $r_max) {
3437 push @cmd, "$c_min..$c_max";
3438 } else {
3439 push @cmd, "$c_max..$c_min";
3441 } elsif ($r_max > $r_min) {
3442 push @cmd, $c_max;
3443 } else {
3444 push @cmd, $c_min;
3447 return @cmd;
3450 # adapted from pager.c
3451 sub config_pager {
3452 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3453 if (!defined $pager) {
3454 $pager = 'less';
3455 } elsif (length $pager == 0 || $pager eq 'cat') {
3456 $pager = undef;
3460 sub run_pager {
3461 return unless -t *STDOUT;
3462 pipe my $rfd, my $wfd or return;
3463 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3464 if (!$pid) {
3465 open STDOUT, '>&', $wfd or
3466 ::fatal "Can't redirect to stdout: $!\n";
3467 return;
3469 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3470 $ENV{LESS} ||= 'FRSX';
3471 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3474 sub tz_to_s_offset {
3475 my ($tz) = @_;
3476 $tz =~ s/(\d\d)$//;
3477 return ($1 * 60) + ($tz * 3600);
3480 sub get_author_info {
3481 my ($dest, $author, $t, $tz) = @_;
3482 $author =~ s/(?:^\s*|\s*$)//g;
3483 $dest->{a_raw} = $author;
3484 my $au;
3485 if ($::_authors) {
3486 $au = $rusers{$author} || undef;
3488 if (!$au) {
3489 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3491 $dest->{t} = $t;
3492 $dest->{tz} = $tz;
3493 $dest->{a} = $au;
3494 # Date::Parse isn't in the standard Perl distro :(
3495 if ($tz =~ s/^\+//) {
3496 $t += tz_to_s_offset($tz);
3497 } elsif ($tz =~ s/^\-//) {
3498 $t -= tz_to_s_offset($tz);
3500 $dest->{t_utc} = $t;
3503 sub process_commit {
3504 my ($c, $r_min, $r_max, $defer) = @_;
3505 if (defined $r_min && defined $r_max) {
3506 if ($r_min == $c->{r} && $r_min == $r_max) {
3507 show_commit($c);
3508 return 0;
3510 return 1 if $r_min == $r_max;
3511 if ($r_min < $r_max) {
3512 # we need to reverse the print order
3513 return 0 if (defined $limit && --$limit < 0);
3514 push @$defer, $c;
3515 return 1;
3517 if ($r_min != $r_max) {
3518 return 1 if ($r_min < $c->{r});
3519 return 1 if ($r_max > $c->{r});
3522 return 0 if (defined $limit && --$limit < 0);
3523 show_commit($c);
3524 return 1;
3527 sub show_commit {
3528 my $c = shift;
3529 if ($oneline) {
3530 my $x = "\n";
3531 if (my $l = $c->{l}) {
3532 while ($l->[0] =~ /^\s*$/) { shift @$l }
3533 $x = $l->[0];
3535 $l_fmt ||= 'A' . length($c->{r});
3536 print 'r',pack($l_fmt, $c->{r}),' | ';
3537 print "$c->{c} | " if $show_commit;
3538 print $x;
3539 } else {
3540 show_commit_normal($c);
3544 sub show_commit_changed_paths {
3545 my ($c) = @_;
3546 return unless $c->{changed};
3547 print "Changed paths:\n", @{$c->{changed}};
3550 sub show_commit_normal {
3551 my ($c) = @_;
3552 print '-' x72, "\nr$c->{r} | ";
3553 print "$c->{c} | " if $show_commit;
3554 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3555 localtime($c->{t_utc})), ' | ';
3556 my $nr_line = 0;
3558 if (my $l = $c->{l}) {
3559 while ($l->[$#$l] eq "\n" && $#$l > 0
3560 && $l->[($#$l - 1)] eq "\n") {
3561 pop @$l;
3563 $nr_line = scalar @$l;
3564 if (!$nr_line) {
3565 print "1 line\n\n\n";
3566 } else {
3567 if ($nr_line == 1) {
3568 $nr_line = '1 line';
3569 } else {
3570 $nr_line .= ' lines';
3572 print $nr_line, "\n";
3573 show_commit_changed_paths($c);
3574 print "\n";
3575 print $_ foreach @$l;
3577 } else {
3578 print "1 line\n";
3579 show_commit_changed_paths($c);
3580 print "\n";
3583 foreach my $x (qw/raw stat diff/) {
3584 if ($c->{$x}) {
3585 print "\n";
3586 print $_ foreach @{$c->{$x}}
3591 sub cmd_show_log {
3592 my (@args) = @_;
3593 my ($r_min, $r_max);
3594 my $r_last = -1; # prevent dupes
3595 if (defined $TZ) {
3596 $ENV{TZ} = $TZ;
3597 } else {
3598 delete $ENV{TZ};
3600 if (defined $::_revision) {
3601 if ($::_revision =~ /^(\d+):(\d+)$/) {
3602 ($r_min, $r_max) = ($1, $2);
3603 } elsif ($::_revision =~ /^\d+$/) {
3604 $r_min = $r_max = $::_revision;
3605 } else {
3606 ::fatal "-r$::_revision is not supported, use ",
3607 "standard \'git log\' arguments instead\n";
3611 config_pager();
3612 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3613 my $log = command_output_pipe(@args);
3614 run_pager();
3615 my (@k, $c, $d, $stat);
3616 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3617 while (<$log>) {
3618 if (/^${esc_color}commit ($::sha1_short)/o) {
3619 my $cmt = $1;
3620 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3621 $r_last = $c->{r};
3622 process_commit($c, $r_min, $r_max, \@k) or
3623 goto out;
3625 $d = undef;
3626 $c = { c => $cmt };
3627 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3628 get_author_info($c, $1, $2, $3);
3629 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3630 # ignore
3631 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3632 push @{$c->{raw}}, $_;
3633 } elsif (/^${esc_color}[ACRMDT]\t/) {
3634 # we could add $SVN->{svn_path} here, but that requires
3635 # remote access at the moment (repo_path_split)...
3636 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3637 push @{$c->{changed}}, $_;
3638 } elsif (/^${esc_color}diff /o) {
3639 $d = 1;
3640 push @{$c->{diff}}, $_;
3641 } elsif ($d) {
3642 push @{$c->{diff}}, $_;
3643 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3644 $esc_color*[\+\-]*$esc_color$/x) {
3645 $stat = 1;
3646 push @{$c->{stat}}, $_;
3647 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3648 push @{$c->{stat}}, $_;
3649 $stat = undef;
3650 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3651 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3652 } elsif (s/^${esc_color} //o) {
3653 push @{$c->{l}}, $_;
3656 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3657 $r_last = $c->{r};
3658 process_commit($c, $r_min, $r_max, \@k);
3660 if (@k) {
3661 my $swap = $r_max;
3662 $r_max = $r_min;
3663 $r_min = $swap;
3664 process_commit($_, $r_min, $r_max) foreach reverse @k;
3666 out:
3667 close $log;
3668 print '-' x72,"\n" unless $incremental || $oneline;
3671 package Git::SVN::Migration;
3672 # these version numbers do NOT correspond to actual version numbers
3673 # of git nor git-svn. They are just relative.
3675 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3677 # v1 layout: .git/$id/info/url, refs/remotes/$id
3679 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3681 # v3 layout: .git/svn/$id, refs/remotes/$id
3682 # - info/url may remain for backwards compatibility
3683 # - this is what we migrate up to this layout automatically,
3684 # - this will be used by git svn init on single branches
3685 # v3.1 layout (auto migrated):
3686 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3687 # for backwards compatibility
3689 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3690 # - this is only created for newly multi-init-ed
3691 # repositories. Similar in spirit to the
3692 # --use-separate-remotes option in git-clone (now default)
3693 # - we do not automatically migrate to this (following
3694 # the example set by core git)
3695 use strict;
3696 use warnings;
3697 use Carp qw/croak/;
3698 use File::Path qw/mkpath/;
3699 use File::Basename qw/dirname basename/;
3700 use vars qw/$_minimize/;
3702 sub migrate_from_v0 {
3703 my $git_dir = $ENV{GIT_DIR};
3704 return undef unless -d $git_dir;
3705 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3706 my $migrated = 0;
3707 while (<$fh>) {
3708 chomp;
3709 my ($id, $orig_ref) = ($_, $_);
3710 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3711 next unless -f "$git_dir/$id/info/url";
3712 my $new_ref = "refs/remotes/$id";
3713 if (::verify_ref("$new_ref^0")) {
3714 print STDERR "W: $orig_ref is probably an old ",
3715 "branch used by an ancient version of ",
3716 "git-svn.\n",
3717 "However, $new_ref also exists.\n",
3718 "We will not be able ",
3719 "to use this branch until this ",
3720 "ambiguity is resolved.\n";
3721 next;
3723 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3724 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3725 command_noisy('update-ref', $new_ref, $orig_ref);
3726 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3727 $migrated++;
3729 command_close_pipe($fh, $ctx);
3730 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3731 $migrated;
3734 sub migrate_from_v1 {
3735 my $git_dir = $ENV{GIT_DIR};
3736 my $migrated = 0;
3737 return $migrated unless -d $git_dir;
3738 my $svn_dir = "$git_dir/svn";
3740 # just in case somebody used 'svn' as their $id at some point...
3741 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3743 print STDERR "Migrating from a git-svn v1 layout...\n";
3744 mkpath([$svn_dir]);
3745 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3746 "$svn_dir\n\t(required for this version ",
3747 "($::VERSION) of git-svn) does not. exist\n";
3748 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3749 while (<$fh>) {
3750 my $x = $_;
3751 next unless $x =~ s#^refs/remotes/##;
3752 chomp $x;
3753 next unless -f "$git_dir/$x/info/url";
3754 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3755 next unless $u;
3756 my $dn = dirname("$git_dir/svn/$x");
3757 mkpath([$dn]) unless -d $dn;
3758 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3759 mkpath(["$git_dir/svn/svn"]);
3760 print STDERR " - $git_dir/$x/info => ",
3761 "$git_dir/svn/$x/info\n";
3762 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3763 croak "$!: $x";
3764 # don't worry too much about these, they probably
3765 # don't exist with repos this old (save for index,
3766 # and we can easily regenerate that)
3767 foreach my $f (qw/unhandled.log index .rev_db/) {
3768 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3770 } else {
3771 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3772 rename "$git_dir/$x", "$git_dir/svn/$x" or
3773 croak "$!: $x";
3775 $migrated++;
3777 command_close_pipe($fh, $ctx);
3778 print STDERR "Done migrating from a git-svn v1 layout\n";
3779 $migrated;
3782 sub read_old_urls {
3783 my ($l_map, $pfx, $path) = @_;
3784 my @dir;
3785 foreach (<$path/*>) {
3786 if (-r "$_/info/url") {
3787 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3788 my $ref_id = $pfx . basename $_;
3789 my $url = ::file_to_s("$_/info/url");
3790 $l_map->{$ref_id} = $url;
3791 } elsif (-d $_) {
3792 push @dir, $_;
3795 foreach (@dir) {
3796 my $x = $_;
3797 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3798 read_old_urls($l_map, $x, $_);
3802 sub migrate_from_v2 {
3803 my @cfg = command(qw/config -l/);
3804 return if grep /^svn-remote\..+\.url=/, @cfg;
3805 my %l_map;
3806 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3807 my $migrated = 0;
3809 foreach my $ref_id (sort keys %l_map) {
3810 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3811 if ($@) {
3812 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3814 $migrated++;
3816 $migrated;
3819 sub minimize_connections {
3820 my $r = Git::SVN::read_all_remotes();
3821 my $new_urls = {};
3822 my $root_repos = {};
3823 foreach my $repo_id (keys %$r) {
3824 my $url = $r->{$repo_id}->{url} or next;
3825 my $fetch = $r->{$repo_id}->{fetch} or next;
3826 my $ra = Git::SVN::Ra->new($url);
3828 # skip existing cases where we already connect to the root
3829 if (($ra->{url} eq $ra->{repos_root}) ||
3830 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3831 $repo_id)) {
3832 $root_repos->{$ra->{url}} = $repo_id;
3833 next;
3836 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3837 my $root_path = $ra->{url};
3838 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3839 foreach my $path (keys %$fetch) {
3840 my $ref_id = $fetch->{$path};
3841 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3843 # make sure we can read when connecting to
3844 # a higher level of a repository
3845 my ($last_rev, undef) = $gs->last_rev_commit;
3846 if (!defined $last_rev) {
3847 $last_rev = eval {
3848 $root_ra->get_latest_revnum;
3850 next if $@;
3852 my $new = $root_path;
3853 $new .= length $path ? "/$path" : '';
3854 eval {
3855 $root_ra->get_log([$new], $last_rev, $last_rev,
3856 0, 0, 1, sub { });
3858 next if $@;
3859 $new_urls->{$ra->{repos_root}}->{$new} =
3860 { ref_id => $ref_id,
3861 old_repo_id => $repo_id,
3862 old_path => $path };
3866 my @emptied;
3867 foreach my $url (keys %$new_urls) {
3868 # see if we can re-use an existing [svn-remote "repo_id"]
3869 # instead of creating a(n ugly) new section:
3870 my $repo_id = $root_repos->{$url} ||
3871 Git::SVN::sanitize_remote_name($url);
3873 my $fetch = $new_urls->{$url};
3874 foreach my $path (keys %$fetch) {
3875 my $x = $fetch->{$path};
3876 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3877 my $pfx = "svn-remote.$x->{old_repo_id}";
3879 my $old_fetch = quotemeta("$x->{old_path}:".
3880 "refs/remotes/$x->{ref_id}");
3881 command_noisy(qw/config --unset/,
3882 "$pfx.fetch", '^'. $old_fetch . '$');
3883 delete $r->{$x->{old_repo_id}}->
3884 {fetch}->{$x->{old_path}};
3885 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3886 command_noisy(qw/config --unset/,
3887 "$pfx.url");
3888 push @emptied, $x->{old_repo_id}
3892 if (@emptied) {
3893 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3894 "$ENV{GIT_DIR}/config";
3895 print STDERR <<EOF;
3896 The following [svn-remote] sections in your config file ($file) are empty
3897 and can be safely removed:
3899 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3903 sub migration_check {
3904 migrate_from_v0();
3905 migrate_from_v1();
3906 migrate_from_v2();
3907 minimize_connections() if $_minimize;
3910 package Git::IndexInfo;
3911 use strict;
3912 use warnings;
3913 use Git qw/command_input_pipe command_close_pipe/;
3915 sub new {
3916 my ($class) = @_;
3917 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3918 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3921 sub remove {
3922 my ($self, $path) = @_;
3923 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3924 return ++$self->{nr};
3926 undef;
3929 sub update {
3930 my ($self, $mode, $hash, $path) = @_;
3931 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3932 return ++$self->{nr};
3934 undef;
3937 sub DESTROY {
3938 my ($self) = @_;
3939 command_close_pipe($self->{gui}, $self->{ctx});
3942 package Git::SVN::GlobSpec;
3943 use strict;
3944 use warnings;
3946 sub new {
3947 my ($class, $glob) = @_;
3948 my $re = $glob;
3949 $re =~ s!/+$!!g; # no need for trailing slashes
3950 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3951 my ($left, $right) = ($1, $2);
3952 if ($nr > 1) {
3953 die "Only one '*' wildcard expansion ",
3954 "is supported (got $nr): '$glob'\n";
3955 } elsif ($nr == 0) {
3956 die "One '*' is needed for glob: '$glob'\n";
3958 $re = quotemeta($left) . $re . quotemeta($right);
3959 if (length $left && !($left =~ s!/+$!!g)) {
3960 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3962 if (length $right && !($right =~ s!^/+!!g)) {
3963 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3965 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3966 bless { left => $left, right => $right, left_regex => $left_re,
3967 regex => qr/$re/, glob => $glob }, $class;
3970 sub full_path {
3971 my ($self, $path) = @_;
3972 return (length $self->{left} ? "$self->{left}/" : '') .
3973 $path . (length $self->{right} ? "/$self->{right}" : '');
3976 __END__
3978 Data structures:
3981 $remotes = { # returned by read_all_remotes()
3982 'svn' => {
3983 # svn-remote.svn.url=https://svn.musicpd.org
3984 url => 'https://svn.musicpd.org',
3985 # svn-remote.svn.fetch=mpd/trunk:trunk
3986 fetch => {
3987 'mpd/trunk' => 'trunk',
3989 # svn-remote.svn.tags=mpd/tags/*:tags/*
3990 tags => {
3991 path => {
3992 left => 'mpd/tags',
3993 right => '',
3994 regex => qr!mpd/tags/([^/]+)$!,
3995 glob => 'tags/*',
3997 ref => {
3998 left => 'tags',
3999 right => '',
4000 regex => qr!tags/([^/]+)$!,
4001 glob => 'tags/*',
4007 $log_entry hashref as returned by libsvn_log_entry()
4009 log => 'whitespace-formatted log entry
4010 ', # trailing newline is preserved
4011 revision => '8', # integer
4012 date => '2004-02-24T17:01:44.108345Z', # commit date
4013 author => 'committer name'
4017 # this is generated by generate_diff();
4018 @mods = array of diff-index line hashes, each element represents one line
4019 of diff-index output
4021 diff-index line ($m hash)
4023 mode_a => first column of diff-index output, no leading ':',
4024 mode_b => second column of diff-index output,
4025 sha1_b => sha1sum of the final blob,
4026 chg => change type [MCRADT],
4027 file_a => original file name of a file (iff chg is 'C' or 'R')
4028 file_b => new/current file name of a file (any chg)
4032 # retval of read_url_paths{,_all}();
4033 $l_map = {
4034 # repository root url
4035 'https://svn.musicpd.org' => {
4036 # repository path # GIT_SVN_ID
4037 'mpd/trunk' => 'trunk',
4038 'mpd/tags/0.11.5' => 'tags/0.11.5',
4042 Notes:
4043 I don't trust the each() function on unless I created %hash myself
4044 because the internal iterator may not have started at base.