Merge branch 'maint'
[git/mingw.git] / git-svn.perl
blob7b5f8ab3be6639e682dc6b0d5a53412f1078ba54
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 my $s;
42 foreach (qw/command command_oneline command_noisy command_output_pipe
43 command_input_pipe command_close_pipe/) {
44 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
45 "*Git::SVN::Migration::$_ = ".
46 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
48 eval $s;
51 my ($SVN);
53 $sha1 = qr/[a-f\d]{40}/;
54 $sha1_short = qr/[a-f\d]{4,40}/;
55 my ($_stdin, $_help, $_edit,
56 $_message, $_file,
57 $_template, $_shared,
58 $_version, $_fetch_all,
59 $_merge, $_strategy, $_dry_run, $_local,
60 $_prefix, $_no_checkout, $_verbose);
61 $Git::SVN::_follow_parent = 1;
62 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63 'config-dir=s' => \$Git::SVN::Ra::config_dir,
64 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
65 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
66 'authors-file|A=s' => \$_authors,
67 'repack:i' => \$Git::SVN::_repack,
68 'noMetadata' => \$Git::SVN::_no_metadata,
69 'useSvmProps' => \$Git::SVN::_use_svm_props,
70 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
71 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
72 'no-checkout' => \$_no_checkout,
73 'quiet|q' => \$_q,
74 'repack-flags|repack-args|repack-opts=s' =>
75 \$Git::SVN::_repack_flags,
76 %remote_opts );
78 my ($_trunk, $_tags, $_branches);
79 my %icv;
80 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
83 'no-metadata' => sub { $icv{noMetadata} = 1 },
84 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
85 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
86 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
87 %remote_opts );
88 my %cmt_opts = ( 'edit|e' => \$_edit,
89 'rmdir' => \$SVN::Git::Editor::_rmdir,
90 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
91 'l=i' => \$SVN::Git::Editor::_rename_limit,
92 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
95 my %cmd = (
96 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
97 { 'revision|r=s' => \$_revision,
98 'fetch-all|all' => \$_fetch_all,
99 %fc_opts } ],
100 clone => [ \&cmd_clone, "Initialize and fetch revisions",
101 { 'revision|r=s' => \$_revision,
102 %fc_opts, %init_opts } ],
103 init => [ \&cmd_init, "Initialize a repo for tracking" .
104 " (requires URL argument)",
105 \%init_opts ],
106 'multi-init' => [ \&cmd_multi_init,
107 "Deprecated alias for ".
108 "'$0 init -T<trunk> -b<branches> -t<tags>'",
109 \%init_opts ],
110 dcommit => [ \&cmd_dcommit,
111 'Commit several diffs to merge with upstream',
112 { 'merge|m|M' => \$_merge,
113 'strategy|s=s' => \$_strategy,
114 'verbose|v' => \$_verbose,
115 'dry-run|n' => \$_dry_run,
116 'fetch-all|all' => \$_fetch_all,
117 %cmt_opts, %fc_opts } ],
118 'set-tree' => [ \&cmd_set_tree,
119 "Set an SVN repository to a git tree-ish",
120 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
121 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
122 { 'revision|r=i' => \$_revision } ],
123 'multi-fetch' => [ \&cmd_multi_fetch,
124 "Deprecated alias for $0 fetch --all",
125 { 'revision|r=s' => \$_revision, %fc_opts } ],
126 'migrate' => [ sub { },
127 # no-op, we automatically run this anyways,
128 'Migrate configuration/metadata/layout from
129 previous versions of git-svn',
130 { 'minimize' => \$Git::SVN::Migration::_minimize,
131 %remote_opts } ],
132 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
133 { 'limit=i' => \$Git::SVN::Log::limit,
134 'revision|r=s' => \$_revision,
135 'verbose|v' => \$Git::SVN::Log::verbose,
136 'incremental' => \$Git::SVN::Log::incremental,
137 'oneline' => \$Git::SVN::Log::oneline,
138 'show-commit' => \$Git::SVN::Log::show_commit,
139 'non-recursive' => \$Git::SVN::Log::non_recursive,
140 'authors-file|A=s' => \$_authors,
141 'color' => \$Git::SVN::Log::color,
142 'pager=s' => \$Git::SVN::Log::pager,
143 } ],
144 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
145 { 'merge|m|M' => \$_merge,
146 'verbose|v' => \$_verbose,
147 'strategy|s=s' => \$_strategy,
148 'local|l' => \$_local,
149 'fetch-all|all' => \$_fetch_all,
150 %fc_opts } ],
151 'commit-diff' => [ \&cmd_commit_diff,
152 'Commit a diff between two trees',
153 { 'message|m=s' => \$_message,
154 'file|F=s' => \$_file,
155 'revision|r=s' => \$_revision,
156 %cmt_opts } ],
159 my $cmd;
160 for (my $i = 0; $i < @ARGV; $i++) {
161 if (defined $cmd{$ARGV[$i]}) {
162 $cmd = $ARGV[$i];
163 splice @ARGV, $i, 1;
164 last;
168 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
170 read_repo_config(\%opts);
171 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
172 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
173 'minimize-connections' => \$Git::SVN::Migration::_minimize,
174 'id|i=s' => \$Git::SVN::default_ref_id,
175 'svn-remote|remote|R=s' => sub {
176 $Git::SVN::no_reuse_existing = 1;
177 $Git::SVN::default_repo_id = $_[1] });
178 exit 1 if (!$rv && $cmd && $cmd ne 'log');
180 usage(0) if $_help;
181 version() if $_version;
182 usage(1) unless defined $cmd;
183 load_authors() if $_authors;
185 # make sure we're always running
186 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
187 unless (-d $ENV{GIT_DIR}) {
188 if ($git_dir_user_set) {
189 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
190 "but it is not a directory\n";
192 my $git_dir = delete $ENV{GIT_DIR};
193 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
194 unless (length $cdup) {
195 die "Already at toplevel, but $git_dir ",
196 "not found '$cdup'\n";
198 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
199 unless (-d $git_dir) {
200 die "$git_dir still not found after going to ",
201 "'$cdup'\n";
203 $ENV{GIT_DIR} = $git_dir;
206 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
207 Git::SVN::Migration::migration_check();
209 Git::SVN::init_vars();
210 eval {
211 Git::SVN::verify_remotes_sanity();
212 $cmd{$cmd}->[0]->(@ARGV);
214 fatal $@ if $@;
215 post_fetch_checkout();
216 exit 0;
218 ####################### primary functions ######################
219 sub usage {
220 my $exit = shift || 0;
221 my $fd = $exit ? \*STDERR : \*STDOUT;
222 print $fd <<"";
223 git-svn - bidirectional operations between a single Subversion tree and git
224 Usage: $0 <command> [options] [arguments]\n
226 print $fd "Available commands:\n" unless $cmd;
228 foreach (sort keys %cmd) {
229 next if $cmd && $cmd ne $_;
230 next if /^multi-/; # don't show deprecated commands
231 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
232 foreach (keys %{$cmd{$_}->[2]}) {
233 # mixed-case options are for .git/config only
234 next if /[A-Z]/ && /^[a-z]+$/i;
235 # prints out arguments as they should be passed:
236 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
237 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
238 "--$_" : "-$_" }
239 split /\|/,$_)," $x\n";
242 print $fd <<"";
243 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
244 arbitrary identifier if you're tracking multiple SVN branches/repositories in
245 one git repository and want to keep them separate. See git-svn(1) for more
246 information.
248 exit $exit;
251 sub version {
252 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
253 exit 0;
256 sub do_git_init_db {
257 unless (-d $ENV{GIT_DIR}) {
258 my @init_db = ('init');
259 push @init_db, "--template=$_template" if defined $_template;
260 if (defined $_shared) {
261 if ($_shared =~ /[a-z]/) {
262 push @init_db, "--shared=$_shared";
263 } else {
264 push @init_db, "--shared";
267 command_noisy(@init_db);
269 my $set;
270 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
271 foreach my $i (keys %icv) {
272 die "'$set' and '$i' cannot both be set\n" if $set;
273 next unless defined $icv{$i};
274 command_noisy('config', "$pfx.$i", $icv{$i});
275 $set = $i;
279 sub init_subdir {
280 my $repo_path = shift or return;
281 mkpath([$repo_path]) unless -d $repo_path;
282 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
283 $ENV{GIT_DIR} = '.git';
286 sub cmd_clone {
287 my ($url, $path) = @_;
288 if (!defined $path &&
289 (defined $_trunk || defined $_branches || defined $_tags) &&
290 $url !~ m#^[a-z\+]+://#) {
291 $path = $url;
293 $path = basename($url) if !defined $path || !length $path;
294 cmd_init($url, $path);
295 Git::SVN::fetch_all($Git::SVN::default_repo_id);
298 sub cmd_init {
299 if (defined $_trunk || defined $_branches || defined $_tags) {
300 return cmd_multi_init(@_);
302 my $url = shift or die "SVN repository location required ",
303 "as a command-line argument\n";
304 init_subdir(@_);
305 do_git_init_db();
307 Git::SVN->init($url);
310 sub cmd_fetch {
311 if (grep /^\d+=./, @_) {
312 die "'<rev>=<commit>' fetch arguments are ",
313 "no longer supported.\n";
315 my ($remote) = @_;
316 if (@_ > 1) {
317 die "Usage: $0 fetch [--all] [svn-remote]\n";
319 $remote ||= $Git::SVN::default_repo_id;
320 if ($_fetch_all) {
321 cmd_multi_fetch();
322 } else {
323 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
327 sub cmd_set_tree {
328 my (@commits) = @_;
329 if ($_stdin || !@commits) {
330 print "Reading from stdin...\n";
331 @commits = ();
332 while (<STDIN>) {
333 if (/\b($sha1_short)\b/o) {
334 unshift @commits, $1;
338 my @revs;
339 foreach my $c (@commits) {
340 my @tmp = command('rev-parse',$c);
341 if (scalar @tmp == 1) {
342 push @revs, $tmp[0];
343 } elsif (scalar @tmp > 1) {
344 push @revs, reverse(command('rev-list',@tmp));
345 } else {
346 fatal "Failed to rev-parse $c\n";
349 my $gs = Git::SVN->new;
350 my ($r_last, $cmt_last) = $gs->last_rev_commit;
351 $gs->fetch;
352 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
353 fatal "There are new revisions that were fetched ",
354 "and need to be merged (or acknowledged) ",
355 "before committing.\nlast rev: $r_last\n",
356 " current: $gs->{last_rev}\n";
358 $gs->set_tree($_) foreach @revs;
359 print "Done committing ",scalar @revs," revisions to SVN\n";
362 sub cmd_dcommit {
363 my $head = shift;
364 $head ||= 'HEAD';
365 my @refs;
366 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
367 unless ($gs) {
368 die "Unable to determine upstream SVN information from ",
369 "$head history\n";
371 my $c = $refs[-1];
372 my $last_rev;
373 foreach my $d (@refs) {
374 if (!verify_ref("$d~1")) {
375 fatal "Commit $d\n",
376 "has no parent commit, and therefore ",
377 "nothing to diff against.\n",
378 "You should be working from a repository ",
379 "originally created by git-svn\n";
381 unless (defined $last_rev) {
382 (undef, $last_rev, undef) = cmt_metadata("$d~1");
383 unless (defined $last_rev) {
384 fatal "Unable to extract revision information ",
385 "from commit $d~1\n";
388 if ($_dry_run) {
389 print "diff-tree $d~1 $d\n";
390 } else {
391 my %ed_opts = ( r => $last_rev,
392 log => get_commit_entry($d)->{log},
393 ra => Git::SVN::Ra->new($url),
394 tree_a => "$d~1",
395 tree_b => $d,
396 editor_cb => sub {
397 print "Committed r$_[0]\n";
398 $last_rev = $_[0]; },
399 svn_path => '');
400 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
401 print "No changes\n$d~1 == $d\n";
405 return if $_dry_run;
406 unless ($gs) {
407 warn "Could not determine fetch information for $url\n",
408 "Will not attempt to fetch and rebase commits.\n",
409 "This probably means you have useSvmProps and should\n",
410 "now resync your SVN::Mirror repository.\n";
411 return;
413 $_fetch_all ? $gs->fetch_all : $gs->fetch;
414 # we always want to rebase against the current HEAD, not any
415 # head that was passed to us
416 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
417 my @finish;
418 if (@diff) {
419 @finish = rebase_cmd();
420 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
421 "using @finish:\n", "@diff";
422 } else {
423 print "No changes between current HEAD and ",
424 $gs->refname, "\nResetting to the latest ",
425 $gs->refname, "\n";
426 @finish = qw/reset --mixed/;
428 command_noisy(@finish, $gs->refname);
431 sub cmd_rebase {
432 command_noisy(qw/update-index --refresh/);
433 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
434 unless ($gs) {
435 die "Unable to determine upstream SVN information from ",
436 "working tree history\n";
438 if (command(qw/diff-index HEAD --/)) {
439 print STDERR "Cannot rebase with uncommited changes:\n";
440 command_noisy('status');
441 exit 1;
443 unless ($_local) {
444 $_fetch_all ? $gs->fetch_all : $gs->fetch;
446 command_noisy(rebase_cmd(), $gs->refname);
449 sub cmd_show_ignore {
450 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
451 $gs ||= Git::SVN->new;
452 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
453 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
456 sub cmd_multi_init {
457 my $url = shift;
458 unless (defined $_trunk || defined $_branches || defined $_tags) {
459 usage(1);
461 $_prefix = '' unless defined $_prefix;
462 if (defined $url) {
463 $url =~ s#/+$##;
464 init_subdir(@_);
466 do_git_init_db();
467 if (defined $_trunk) {
468 my $trunk_ref = $_prefix . 'trunk';
469 # try both old-style and new-style lookups:
470 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
471 unless ($gs_trunk) {
472 my ($trunk_url, $trunk_path) =
473 complete_svn_url($url, $_trunk);
474 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
475 undef, $trunk_ref);
478 return unless defined $_branches || defined $_tags;
479 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
480 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
481 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
484 sub cmd_multi_fetch {
485 my $remotes = Git::SVN::read_all_remotes();
486 foreach my $repo_id (sort keys %$remotes) {
487 if ($remotes->{$repo_id}->{url}) {
488 Git::SVN::fetch_all($repo_id, $remotes);
493 # this command is special because it requires no metadata
494 sub cmd_commit_diff {
495 my ($ta, $tb, $url) = @_;
496 my $usage = "Usage: $0 commit-diff -r<revision> ".
497 "<tree-ish> <tree-ish> [<URL>]\n";
498 fatal($usage) if (!defined $ta || !defined $tb);
499 my $svn_path;
500 if (!defined $url) {
501 my $gs = eval { Git::SVN->new };
502 if (!$gs) {
503 fatal("Needed URL or usable git-svn --id in ",
504 "the command-line\n", $usage);
506 $url = $gs->{url};
507 $svn_path = $gs->{path};
509 unless (defined $_revision) {
510 fatal("-r|--revision is a required argument\n", $usage);
512 if (defined $_message && defined $_file) {
513 fatal("Both --message/-m and --file/-F specified ",
514 "for the commit message.\n",
515 "I have no idea what you mean\n");
517 if (defined $_file) {
518 $_message = file_to_s($_file);
519 } else {
520 $_message ||= get_commit_entry($tb)->{log};
522 my $ra ||= Git::SVN::Ra->new($url);
523 $svn_path ||= $ra->{svn_path};
524 my $r = $_revision;
525 if ($r eq 'HEAD') {
526 $r = $ra->get_latest_revnum;
527 } elsif ($r !~ /^\d+$/) {
528 die "revision argument: $r not understood by git-svn\n";
530 my %ed_opts = ( r => $r,
531 log => $_message,
532 ra => $ra,
533 tree_a => $ta,
534 tree_b => $tb,
535 editor_cb => sub { print "Committed r$_[0]\n" },
536 svn_path => $svn_path );
537 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
538 print "No changes\n$ta == $tb\n";
542 ########################### utility functions #########################
544 sub rebase_cmd {
545 my @cmd = qw/rebase/;
546 push @cmd, '-v' if $_verbose;
547 push @cmd, qw/--merge/ if $_merge;
548 push @cmd, "--strategy=$_strategy" if $_strategy;
549 @cmd;
552 sub post_fetch_checkout {
553 return if $_no_checkout;
554 my $gs = $Git::SVN::_head or return;
555 return if verify_ref('refs/heads/master^0');
557 my $valid_head = verify_ref('HEAD^0');
558 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
559 return if ($valid_head || !verify_ref('HEAD^0'));
561 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
562 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
563 return if -f $index;
565 chomp(my $bare = `git config --bool --get core.bare`);
566 return if $bare eq 'true';
567 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
568 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
569 print STDERR "Checked out HEAD:\n ",
570 $gs->full_url, " r", $gs->last_rev, "\n";
573 sub complete_svn_url {
574 my ($url, $path) = @_;
575 $path =~ s#/+$##;
576 if ($path !~ m#^[a-z\+]+://#) {
577 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
578 fatal("E: '$path' is not a complete URL ",
579 "and a separate URL is not specified\n");
581 return ($url, $path);
583 return ($path, '');
586 sub complete_url_ls_init {
587 my ($ra, $repo_path, $switch, $pfx) = @_;
588 unless ($repo_path) {
589 print STDERR "W: $switch not specified\n";
590 return;
592 $repo_path =~ s#/+$##;
593 if ($repo_path =~ m#^[a-z\+]+://#) {
594 $ra = Git::SVN::Ra->new($repo_path);
595 $repo_path = '';
596 } else {
597 $repo_path =~ s#^/+##;
598 unless ($ra) {
599 fatal("E: '$repo_path' is not a complete URL ",
600 "and a separate URL is not specified\n");
603 my $url = $ra->{url};
604 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
605 my $k = "svn-remote.$gs->{repo_id}.url";
606 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
607 if ($orig_url && ($orig_url ne $gs->{url})) {
608 die "$k already set: $orig_url\n",
609 "wanted to set to: $gs->{url}\n";
611 command_oneline('config', $k, $gs->{url}) unless $orig_url;
612 my $remote_path = "$ra->{svn_path}/$repo_path/*";
613 $remote_path =~ s#/+#/#g;
614 $remote_path =~ s#^/##g;
615 my ($n) = ($switch =~ /^--(\w+)/);
616 if (length $pfx && $pfx !~ m#/$#) {
617 die "--prefix='$pfx' must have a trailing slash '/'\n";
619 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
620 "$remote_path:refs/remotes/$pfx*");
623 sub verify_ref {
624 my ($ref) = @_;
625 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
626 { STDERR => 0 }); };
629 sub get_tree_from_treeish {
630 my ($treeish) = @_;
631 # $treeish can be a symbolic ref, too:
632 my $type = command_oneline(qw/cat-file -t/, $treeish);
633 my $expected;
634 while ($type eq 'tag') {
635 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
637 if ($type eq 'commit') {
638 $expected = (grep /^tree /, command(qw/cat-file commit/,
639 $treeish))[0];
640 ($expected) = ($expected =~ /^tree ($sha1)$/o);
641 die "Unable to get tree from $treeish\n" unless $expected;
642 } elsif ($type eq 'tree') {
643 $expected = $treeish;
644 } else {
645 die "$treeish is a $type, expected tree, tag or commit\n";
647 return $expected;
650 sub get_commit_entry {
651 my ($treeish) = shift;
652 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
653 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
654 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
655 open my $log_fh, '>', $commit_editmsg or croak $!;
657 my $type = command_oneline(qw/cat-file -t/, $treeish);
658 if ($type eq 'commit' || $type eq 'tag') {
659 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
660 $type, $treeish);
661 my $in_msg = 0;
662 while (<$msg_fh>) {
663 if (!$in_msg) {
664 $in_msg = 1 if (/^\s*$/);
665 } elsif (/^git-svn-id: /) {
666 # skip this for now, we regenerate the
667 # correct one on re-fetch anyways
668 # TODO: set *:merge properties or like...
669 } else {
670 print $log_fh $_ or croak $!;
673 command_close_pipe($msg_fh, $ctx);
675 close $log_fh or croak $!;
677 if ($_edit || ($type eq 'tree')) {
678 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
679 # TODO: strip out spaces, comments, like git-commit.sh
680 system($editor, $commit_editmsg);
682 rename $commit_editmsg, $commit_msg or croak $!;
683 open $log_fh, '<', $commit_msg or croak $!;
684 { local $/; chomp($log_entry{log} = <$log_fh>); }
685 close $log_fh or croak $!;
686 unlink $commit_msg;
687 \%log_entry;
690 sub s_to_file {
691 my ($str, $file, $mode) = @_;
692 open my $fd,'>',$file or croak $!;
693 print $fd $str,"\n" or croak $!;
694 close $fd or croak $!;
695 chmod ($mode &~ umask, $file) if (defined $mode);
698 sub file_to_s {
699 my $file = shift;
700 open my $fd,'<',$file or croak "$!: file: $file\n";
701 local $/;
702 my $ret = <$fd>;
703 close $fd or croak $!;
704 $ret =~ s/\s*$//s;
705 return $ret;
708 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
709 sub load_authors {
710 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
711 my $log = $cmd eq 'log';
712 while (<$authors>) {
713 chomp;
714 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
715 my ($user, $name, $email) = ($1, $2, $3);
716 if ($log) {
717 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
718 } else {
719 $users{$user} = [$name, $email];
722 close $authors or croak $!;
725 # convert GetOpt::Long specs for use by git-config
726 sub read_repo_config {
727 return unless -d $ENV{GIT_DIR};
728 my $opts = shift;
729 my @config_only;
730 foreach my $o (keys %$opts) {
731 # if we have mixedCase and a long option-only, then
732 # it's a config-only variable that we don't need for
733 # the command-line.
734 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
735 my $v = $opts->{$o};
736 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
737 $key =~ s/-//g;
738 my $arg = 'git-config';
739 $arg .= ' --int' if ($o =~ /[:=]i$/);
740 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
741 if (ref $v eq 'ARRAY') {
742 chomp(my @tmp = `$arg --get-all svn.$key`);
743 @$v = @tmp if @tmp;
744 } else {
745 chomp(my $tmp = `$arg --get svn.$key`);
746 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
747 $$v = $tmp;
751 delete @$opts{@config_only} if @config_only;
754 sub extract_metadata {
755 my $id = shift or return (undef, undef, undef);
756 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
757 \s([a-f\d\-]+)$/x);
758 if (!defined $rev || !$uuid || !$url) {
759 # some of the original repositories I made had
760 # identifiers like this:
761 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
763 return ($url, $rev, $uuid);
766 sub cmt_metadata {
767 return extract_metadata((grep(/^git-svn-id: /,
768 command(qw/cat-file commit/, shift)))[-1]);
771 sub working_head_info {
772 my ($head, $refs) = @_;
773 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
774 while (my $hash = <$fh>) {
775 chomp($hash);
776 my ($url, $rev, $uuid) = cmt_metadata($hash);
777 if (defined $url && defined $rev) {
778 if (my $gs = Git::SVN->find_by_url($url)) {
779 my $c = $gs->rev_db_get($rev);
780 if ($c && $c eq $hash) {
781 close $fh; # break the pipe
782 return ($url, $rev, $uuid, $gs);
786 unshift @$refs, $hash if $refs;
788 command_close_pipe($fh, $ctx);
789 (undef, undef, undef, undef);
792 package Git::SVN;
793 use strict;
794 use warnings;
795 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
796 $_repack $_repack_flags $_use_svm_props $_head
797 $_use_svnsync_props $no_reuse_existing/;
798 use Carp qw/croak/;
799 use File::Path qw/mkpath/;
800 use File::Copy qw/copy/;
801 use IPC::Open3;
803 my $_repack_nr;
804 # properties that we do not log:
805 my %SKIP_PROP;
806 BEGIN {
807 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
808 svn:special svn:executable
809 svn:entry:committed-rev
810 svn:entry:last-author
811 svn:entry:uuid
812 svn:entry:committed-date/;
814 # some options are read globally, but can be overridden locally
815 # per [svn-remote "..."] section. Command-line options will *NOT*
816 # override options set in an [svn-remote "..."] section
817 my $e;
818 foreach (qw/follow_parent no_metadata use_svm_props
819 use_svnsync_props/) {
820 my $key = $_;
821 $key =~ tr/_//d;
822 $e .= "sub $_ {
823 my (\$self) = \@_;
824 return \$self->{-$_} if exists \$self->{-$_};
825 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
826 eval { command_oneline(qw/config --get/, \$k) };
827 if (\$@) {
828 \$self->{-$_} = \$Git::SVN::_$_;
829 } else {
830 my \$v = command_oneline(qw/config --bool/,\$k);
831 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
833 return \$self->{-$_} }\n";
835 $e .= "1;\n";
836 eval $e or die $@;
839 my %LOCKFILES;
840 END { unlink keys %LOCKFILES if %LOCKFILES }
842 sub resolve_local_globs {
843 my ($url, $fetch, $glob_spec) = @_;
844 return unless defined $glob_spec;
845 my $ref = $glob_spec->{ref};
846 my $path = $glob_spec->{path};
847 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
848 next unless m#^refs/remotes/$ref->{regex}$#;
849 my $p = $1;
850 my $pathname = $path->full_path($p);
851 my $refname = $ref->full_path($p);
852 if (my $existing = $fetch->{$pathname}) {
853 if ($existing ne $refname) {
854 die "Refspec conflict:\n",
855 "existing: refs/remotes/$existing\n",
856 " globbed: refs/remotes/$refname\n";
858 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
859 $u =~ s!^\Q$url\E(/|$)!! or die
860 "refs/remotes/$refname: '$url' not found in '$u'\n";
861 if ($pathname ne $u) {
862 warn "W: Refspec glob conflict ",
863 "(ref: refs/remotes/$refname):\n",
864 "expected path: $pathname\n",
865 " real path: $u\n",
866 "Continuing ahead with $u\n";
867 next;
869 } else {
870 $fetch->{$pathname} = $refname;
875 sub parse_revision_argument {
876 my ($base, $head) = @_;
877 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
878 return ($base, $head);
880 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
881 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
882 return ($head, $head) if ($::_revision eq 'HEAD');
883 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
884 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
885 die "revision argument: $::_revision not understood by git-svn\n";
888 sub fetch_all {
889 my ($repo_id, $remotes) = @_;
890 if (ref $repo_id) {
891 my $gs = $repo_id;
892 $repo_id = undef;
893 $repo_id = $gs->{repo_id};
895 $remotes ||= read_all_remotes();
896 my $remote = $remotes->{$repo_id} or
897 die "[svn-remote \"$repo_id\"] unknown\n";
898 my $fetch = $remote->{fetch};
899 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
900 my (@gs, @globs);
901 my $ra = Git::SVN::Ra->new($url);
902 my $uuid = $ra->get_uuid;
903 my $head = $ra->get_latest_revnum;
904 my $base = defined $fetch ? $head : 0;
906 # read the max revs for wildcard expansion (branches/*, tags/*)
907 foreach my $t (qw/branches tags/) {
908 defined $remote->{$t} or next;
909 push @globs, $remote->{$t};
910 my $max_rev = eval { tmp_config(qw/--int --get/,
911 "svn-remote.$repo_id.${t}-maxRev") };
912 if (defined $max_rev && ($max_rev < $base)) {
913 $base = $max_rev;
914 } elsif (!defined $max_rev) {
915 $base = 0;
919 if ($fetch) {
920 foreach my $p (sort keys %$fetch) {
921 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
922 my $lr = $gs->rev_db_max;
923 if (defined $lr) {
924 $base = $lr if ($lr < $base);
926 push @gs, $gs;
930 ($base, $head) = parse_revision_argument($base, $head);
931 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
934 sub read_all_remotes {
935 my $r = {};
936 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
937 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
938 $r->{$1}->{fetch}->{$2} = $3;
939 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
940 $r->{$1}->{url} = $2;
941 } elsif (m!^(.+)\.(branches|tags)=
942 (.*):refs/remotes/(.+)\s*$/!x) {
943 my ($p, $g) = ($3, $4);
944 my $rs = $r->{$1}->{$2} = {
945 t => $2,
946 remote => $1,
947 path => Git::SVN::GlobSpec->new($p),
948 ref => Git::SVN::GlobSpec->new($g) };
949 if (length($rs->{ref}->{right}) != 0) {
950 die "The '*' glob character must be the last ",
951 "character of '$g'\n";
958 sub init_vars {
959 if (defined $_repack) {
960 $_repack = 1000 if ($_repack <= 0);
961 $_repack_nr = $_repack;
962 $_repack_flags ||= '-d';
966 sub verify_remotes_sanity {
967 return unless -d $ENV{GIT_DIR};
968 my %seen;
969 foreach (command(qw/config -l/)) {
970 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
971 if ($seen{$1}) {
972 die "Remote ref refs/remote/$1 is tracked by",
973 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
974 "Please resolve this ambiguity in ",
975 "your git configuration file before ",
976 "continuing\n";
978 $seen{$1} = $_;
983 # we allow more chars than remotes2config.sh...
984 sub sanitize_remote_name {
985 my ($name) = @_;
986 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
987 $name;
990 sub find_existing_remote {
991 my ($url, $remotes) = @_;
992 return undef if $no_reuse_existing;
993 my $existing;
994 foreach my $repo_id (keys %$remotes) {
995 my $u = $remotes->{$repo_id}->{url} or next;
996 next if $u ne $url;
997 $existing = $repo_id;
998 last;
1000 $existing;
1003 sub init_remote_config {
1004 my ($self, $url, $no_write) = @_;
1005 $url =~ s!/+$!!; # strip trailing slash
1006 my $r = read_all_remotes();
1007 my $existing = find_existing_remote($url, $r);
1008 if ($existing) {
1009 unless ($no_write) {
1010 print STDERR "Using existing ",
1011 "[svn-remote \"$existing\"]\n";
1013 $self->{repo_id} = $existing;
1014 } else {
1015 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1016 $existing = find_existing_remote($min_url, $r);
1017 if ($existing) {
1018 unless ($no_write) {
1019 print STDERR "Using existing ",
1020 "[svn-remote \"$existing\"]\n";
1022 $self->{repo_id} = $existing;
1024 if ($min_url ne $url) {
1025 unless ($no_write) {
1026 print STDERR "Using higher level of URL: ",
1027 "$url => $min_url\n";
1029 my $old_path = $self->{path};
1030 $self->{path} = $url;
1031 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1032 if (length $old_path) {
1033 $self->{path} .= "/$old_path";
1035 $url = $min_url;
1038 my $orig_url;
1039 if (!$existing) {
1040 # verify that we aren't overwriting anything:
1041 $orig_url = eval {
1042 command_oneline('config', '--get',
1043 "svn-remote.$self->{repo_id}.url")
1045 if ($orig_url && ($orig_url ne $url)) {
1046 die "svn-remote.$self->{repo_id}.url already set: ",
1047 "$orig_url\nwanted to set to: $url\n";
1050 my ($xrepo_id, $xpath) = find_ref($self->refname);
1051 if (defined $xpath) {
1052 die "svn-remote.$xrepo_id.fetch already set to track ",
1053 "$xpath:refs/remotes/", $self->refname, "\n";
1055 unless ($no_write) {
1056 command_noisy('config',
1057 "svn-remote.$self->{repo_id}.url", $url);
1058 command_noisy('config', '--add',
1059 "svn-remote.$self->{repo_id}.fetch",
1060 "$self->{path}:".$self->refname);
1062 $self->{url} = $url;
1065 sub find_by_url { # repos_root and, path are optional
1066 my ($class, $full_url, $repos_root, $path) = @_;
1068 return undef unless defined $full_url;
1069 remove_username($full_url);
1070 remove_username($repos_root) if defined $repos_root;
1071 my $remotes = read_all_remotes();
1072 if (defined $full_url && defined $repos_root && !defined $path) {
1073 $path = $full_url;
1074 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1076 foreach my $repo_id (keys %$remotes) {
1077 my $u = $remotes->{$repo_id}->{url} or next;
1078 remove_username($u);
1079 next if defined $repos_root && $repos_root ne $u;
1081 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1082 foreach (qw/branches tags/) {
1083 resolve_local_globs($u, $fetch,
1084 $remotes->{$repo_id}->{$_});
1086 my $p = $path;
1087 unless (defined $p) {
1088 $p = $full_url;
1089 $p =~ s#^\Q$u\E(?:/|$)## or next;
1091 foreach my $f (keys %$fetch) {
1092 next if $f ne $p;
1093 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1096 undef;
1099 sub init {
1100 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1101 my $self = _new($class, $repo_id, $ref_id, $path);
1102 if (defined $url) {
1103 $self->init_remote_config($url, $no_write);
1105 $self;
1108 sub find_ref {
1109 my ($ref_id) = @_;
1110 foreach (command(qw/config -l/)) {
1111 next unless m!^svn-remote\.(.+)\.fetch=
1112 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1113 my ($repo_id, $path, $ref) = ($1, $2, $3);
1114 if ($ref eq $ref_id) {
1115 $path = '' if ($path =~ m#^\./?#);
1116 return ($repo_id, $path);
1119 (undef, undef, undef);
1122 sub new {
1123 my ($class, $ref_id, $repo_id, $path) = @_;
1124 if (defined $ref_id && !defined $repo_id && !defined $path) {
1125 ($repo_id, $path) = find_ref($ref_id);
1126 if (!defined $repo_id) {
1127 die "Could not find a \"svn-remote.*.fetch\" key ",
1128 "in the repository configuration matching: ",
1129 "refs/remotes/$ref_id\n";
1132 my $self = _new($class, $repo_id, $ref_id, $path);
1133 if (!defined $self->{path} || !length $self->{path}) {
1134 my $fetch = command_oneline('config', '--get',
1135 "svn-remote.$repo_id.fetch",
1136 ":refs/remotes/$ref_id\$") or
1137 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1138 "\":refs/remotes/$ref_id\$\" in config\n";
1139 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1141 $self->{url} = command_oneline('config', '--get',
1142 "svn-remote.$repo_id.url") or
1143 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1144 $self->rebuild;
1145 $self;
1148 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1150 sub svm_uuid {
1151 my ($self) = @_;
1152 return $self->{svm}->{uuid} if $self->svm;
1153 $self->ra;
1154 unless ($self->{svm}) {
1155 die "SVM UUID not cached, and reading remotely failed\n";
1157 $self->{svm}->{uuid};
1160 sub svm {
1161 my ($self) = @_;
1162 return $self->{svm} if $self->{svm};
1163 my $svm;
1164 # see if we have it in our config, first:
1165 eval {
1166 my $section = "svn-remote.$self->{repo_id}";
1167 $svm = {
1168 source => tmp_config('--get', "$section.svm-source"),
1169 uuid => tmp_config('--get', "$section.svm-uuid"),
1170 replace => tmp_config('--get', "$section.svm-replace"),
1173 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1174 $self->{svm} = $svm;
1176 $self->{svm};
1179 sub _set_svm_vars {
1180 my ($self, $ra) = @_;
1181 return $ra if $self->svm;
1183 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1184 "(svm:source, svm:uuid) ",
1185 "from the following URLs:\n" );
1186 sub read_svm_props {
1187 my ($self, $ra, $path, $r) = @_;
1188 my $props = ($ra->get_dir($path, $r))[2];
1189 my $src = $props->{'svm:source'};
1190 my $uuid = $props->{'svm:uuid'};
1191 return undef if (!$src || !$uuid);
1193 chomp($src, $uuid);
1195 $uuid =~ m{^[0-9a-f\-]{30,}$}
1196 or die "doesn't look right - svm:uuid is '$uuid'\n";
1198 # the '!' is used to mark the repos_root!/relative/path
1199 $src =~ s{/?!/?}{/};
1200 $src =~ s{/+$}{}; # no trailing slashes please
1201 # username is of no interest
1202 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1204 my $replace = $ra->{url};
1205 $replace .= "/$path" if length $path;
1207 my $section = "svn-remote.$self->{repo_id}";
1208 tmp_config("$section.svm-source", $src);
1209 tmp_config("$section.svm-replace", $replace);
1210 tmp_config("$section.svm-uuid", $uuid);
1211 $self->{svm} = {
1212 source => $src,
1213 uuid => $uuid,
1214 replace => $replace
1218 my $r = $ra->get_latest_revnum;
1219 my $path = $self->{path};
1220 my %tried;
1221 while (length $path) {
1222 unless ($tried{"$self->{url}/$path"}) {
1223 return $ra if $self->read_svm_props($ra, $path, $r);
1224 $tried{"$self->{url}/$path"} = 1;
1226 $path =~ s#/?[^/]+$##;
1228 die "Path: '$path' should be ''\n" if $path ne '';
1229 return $ra if $self->read_svm_props($ra, $path, $r);
1230 $tried{"$self->{url}/$path"} = 1;
1232 if ($ra->{repos_root} eq $self->{url}) {
1233 die @err, (map { " $_\n" } keys %tried), "\n";
1236 # nope, make sure we're connected to the repository root:
1237 my $ok;
1238 my @tried_b;
1239 $path = $ra->{svn_path};
1240 $ra = Git::SVN::Ra->new($ra->{repos_root});
1241 while (length $path) {
1242 unless ($tried{"$ra->{url}/$path"}) {
1243 $ok = $self->read_svm_props($ra, $path, $r);
1244 last if $ok;
1245 $tried{"$ra->{url}/$path"} = 1;
1247 $path =~ s#/?[^/]+$##;
1249 die "Path: '$path' should be ''\n" if $path ne '';
1250 $ok ||= $self->read_svm_props($ra, $path, $r);
1251 $tried{"$ra->{url}/$path"} = 1;
1252 if (!$ok) {
1253 die @err, (map { " $_\n" } keys %tried), "\n";
1255 Git::SVN::Ra->new($self->{url});
1258 sub svnsync {
1259 my ($self) = @_;
1260 return $self->{svnsync} if $self->{svnsync};
1262 if ($self->no_metadata) {
1263 die "Can't have both 'noMetadata' and ",
1264 "'useSvnsyncProps' options set!\n";
1266 if ($self->rewrite_root) {
1267 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1268 "options set!\n";
1271 my $svnsync;
1272 # see if we have it in our config, first:
1273 eval {
1274 my $section = "svn-remote.$self->{repo_id}";
1275 $svnsync = {
1276 url => tmp_config('--get', "$section.svnsync-url"),
1277 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1280 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1281 return $self->{svnsync} = $svnsync;
1284 my $err = "useSvnsyncProps set, but failed to read " .
1285 "svnsync property: svn:sync-from-";
1286 my $rp = $self->ra->rev_proplist(0);
1288 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1289 $url =~ m{^[a-z\+]+://} or
1290 die "doesn't look right - svn:sync-from-url is '$url'\n";
1292 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1293 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1294 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1296 my $section = "svn-remote.$self->{repo_id}";
1297 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1298 tmp_config('--add', "$section.svnsync-url", $url);
1299 return $self->{svnsync} = { url => $url, uuid => $uuid };
1302 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1303 # remote lookup (useful for 'git svn log').
1304 sub ra_uuid {
1305 my ($self) = @_;
1306 unless ($self->{ra_uuid}) {
1307 my $key = "svn-remote.$self->{repo_id}.uuid";
1308 my $uuid = eval { tmp_config('--get', $key) };
1309 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1310 $self->{ra_uuid} = $uuid;
1311 } else {
1312 die "ra_uuid called without URL\n" unless $self->{url};
1313 $self->{ra_uuid} = $self->ra->get_uuid;
1314 tmp_config('--add', $key, $self->{ra_uuid});
1317 $self->{ra_uuid};
1320 sub ra {
1321 my ($self) = shift;
1322 my $ra = Git::SVN::Ra->new($self->{url});
1323 if ($self->use_svm_props && !$self->{svm}) {
1324 if ($self->no_metadata) {
1325 die "Can't have both 'noMetadata' and ",
1326 "'useSvmProps' options set!\n";
1327 } elsif ($self->use_svnsync_props) {
1328 die "Can't have both 'useSvnsyncProps' and ",
1329 "'useSvmProps' options set!\n";
1331 $ra = $self->_set_svm_vars($ra);
1332 $self->{-want_revprops} = 1;
1334 $ra;
1337 sub rel_path {
1338 my ($self) = @_;
1339 my $repos_root = $self->ra->{repos_root};
1340 return $self->{path} if ($self->{url} eq $repos_root);
1341 my $url = $self->{url} .
1342 (length $self->{path} ? "/$self->{path}" : $self->{path});
1343 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1344 $url;
1347 sub traverse_ignore {
1348 my ($self, $fh, $path, $r) = @_;
1349 $path =~ s#^/+##g;
1350 my $ra = $self->ra;
1351 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1352 my $p = $path;
1353 $p =~ s#^\Q$self->{path}\E(/|$)##;
1354 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1355 if (my $s = $props->{'svn:ignore'}) {
1356 $s =~ s/[\r\n]+/\n/g;
1357 chomp $s;
1358 if (length $p == 0) {
1359 $s =~ s#\n#\n/$p#g;
1360 print $fh "/$s\n";
1361 } else {
1362 $s =~ s#\n#\n/$p/#g;
1363 print $fh "/$p/$s\n";
1366 foreach (sort keys %$dirent) {
1367 next if $dirent->{$_}->kind != $SVN::Node::dir;
1368 $self->traverse_ignore($fh, "$path/$_", $r);
1372 sub last_rev { ($_[0]->last_rev_commit)[0] }
1373 sub last_commit { ($_[0]->last_rev_commit)[1] }
1375 # returns the newest SVN revision number and newest commit SHA1
1376 sub last_rev_commit {
1377 my ($self) = @_;
1378 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1379 return ($self->{last_rev}, $self->{last_commit});
1381 my $c = ::verify_ref($self->refname.'^0');
1382 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1383 my $rev = (::cmt_metadata($c))[1];
1384 if (defined $rev) {
1385 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1386 return ($rev, $c);
1389 my $db_path = $self->db_path;
1390 unless (-e $db_path) {
1391 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1392 return (undef, undef);
1394 my $offset = -41; # from tail
1395 my $rl;
1396 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1397 sysseek($fh, $offset, 2); # don't care for errors
1398 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1399 chomp $rl;
1400 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1401 $offset -= 41;
1402 sysseek($fh, $offset, 2); # don't care for errors
1403 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1404 chomp $rl;
1406 if ($c && $c ne $rl) {
1407 die "$db_path and ", $self->refname,
1408 " inconsistent!:\n$c != $rl\n";
1410 my $rev = sysseek($fh, 0, 1) or croak $!;
1411 $rev = ($rev - 41) / 41;
1412 close $fh or croak $!;
1413 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1414 return ($rev, $c);
1417 sub get_fetch_range {
1418 my ($self, $min, $max) = @_;
1419 $max ||= $self->ra->get_latest_revnum;
1420 $min ||= $self->rev_db_max;
1421 (++$min, $max);
1424 sub tmp_config {
1425 my (@args) = @_;
1426 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1427 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1428 if (-e $old_def_config && ! -e $config) {
1429 rename $old_def_config, $config or
1430 die "Failed rename $old_def_config => $config: $!\n";
1432 my $old_config = $ENV{GIT_CONFIG};
1433 $ENV{GIT_CONFIG} = $config;
1434 $@ = undef;
1435 my @ret = eval {
1436 unless (-f $config) {
1437 mkfile($config);
1438 open my $fh, '>', $config or
1439 die "Can't open $config: $!\n";
1440 print $fh "; This file is used internally by ",
1441 "git-svn\n" or die
1442 "Couldn't write to $config: $!\n";
1443 print $fh "; You should not have to edit it\n" or
1444 die "Couldn't write to $config: $!\n";
1445 close $fh or die "Couldn't close $config: $!\n";
1447 command('config', @args);
1449 my $err = $@;
1450 if (defined $old_config) {
1451 $ENV{GIT_CONFIG} = $old_config;
1452 } else {
1453 delete $ENV{GIT_CONFIG};
1455 die $err if $err;
1456 wantarray ? @ret : $ret[0];
1459 sub tmp_index_do {
1460 my ($self, $sub) = @_;
1461 my $old_index = $ENV{GIT_INDEX_FILE};
1462 $ENV{GIT_INDEX_FILE} = $self->{index};
1463 $@ = undef;
1464 my @ret = eval {
1465 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1466 mkpath([$dir]) unless -d $dir;
1467 &$sub;
1469 my $err = $@;
1470 if (defined $old_index) {
1471 $ENV{GIT_INDEX_FILE} = $old_index;
1472 } else {
1473 delete $ENV{GIT_INDEX_FILE};
1475 die $err if $err;
1476 wantarray ? @ret : $ret[0];
1479 sub assert_index_clean {
1480 my ($self, $treeish) = @_;
1482 $self->tmp_index_do(sub {
1483 command_noisy('read-tree', $treeish) unless -e $self->{index};
1484 my $x = command_oneline('write-tree');
1485 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1486 /^tree ($::sha1)/mo);
1487 return if $y eq $x;
1489 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1490 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1491 command_noisy('read-tree', $treeish);
1492 $x = command_oneline('write-tree');
1493 if ($y ne $x) {
1494 ::fatal "trees ($treeish) $y != $x\n",
1495 "Something is seriously wrong...\n";
1500 sub get_commit_parents {
1501 my ($self, $log_entry) = @_;
1502 my (%seen, @ret, @tmp);
1503 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1504 if (my $ip = $self->{inject_parents}) {
1505 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1506 push @tmp, $commit;
1509 if (my $cur = ::verify_ref($self->refname.'^0')) {
1510 push @tmp, $cur;
1512 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1513 while (my $p = shift @tmp) {
1514 next if $seen{$p};
1515 $seen{$p} = 1;
1516 push @ret, $p;
1517 # MAXPARENT is defined to 16 in commit-tree.c:
1518 last if @ret >= 16;
1520 if (@tmp) {
1521 die "r$log_entry->{revision}: No room for parents:\n\t",
1522 join("\n\t", @tmp), "\n";
1524 @ret;
1527 sub rewrite_root {
1528 my ($self) = @_;
1529 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1530 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1531 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1532 if ($rwr) {
1533 $rwr =~ s#/+$##;
1534 if ($rwr !~ m#^[a-z\+]+://#) {
1535 die "$rwr is not a valid URL (key: $k)\n";
1538 $self->{-rewrite_root} = $rwr;
1541 sub metadata_url {
1542 my ($self) = @_;
1543 ($self->rewrite_root || $self->{url}) .
1544 (length $self->{path} ? '/' . $self->{path} : '');
1547 sub full_url {
1548 my ($self) = @_;
1549 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1552 sub do_git_commit {
1553 my ($self, $log_entry) = @_;
1554 my $lr = $self->last_rev;
1555 if (defined $lr && $lr >= $log_entry->{revision}) {
1556 die "Last fetched revision of ", $self->refname,
1557 " was r$lr, but we are about to fetch: ",
1558 "r$log_entry->{revision}!\n";
1560 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1561 croak "$log_entry->{revision} = $c already exists! ",
1562 "Why are we refetching it?\n";
1564 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1565 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1566 $log_entry->{email};
1567 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1569 my $tree = $log_entry->{tree};
1570 if (!defined $tree) {
1571 $tree = $self->tmp_index_do(sub {
1572 command_oneline('write-tree') });
1574 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1576 my @exec = ('git-commit-tree', $tree);
1577 foreach ($self->get_commit_parents($log_entry)) {
1578 push @exec, '-p', $_;
1580 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1581 or croak $!;
1582 print $msg_fh $log_entry->{log} or croak $!;
1583 unless ($self->no_metadata) {
1584 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1585 or croak $!;
1587 $msg_fh->flush == 0 or croak $!;
1588 close $msg_fh or croak $!;
1589 chomp(my $commit = do { local $/; <$out_fh> });
1590 close $out_fh or croak $!;
1591 waitpid $pid, 0;
1592 croak $? if $?;
1593 if ($commit !~ /^$::sha1$/o) {
1594 die "Failed to commit, invalid sha1: $commit\n";
1597 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1599 $self->{last_rev} = $log_entry->{revision};
1600 $self->{last_commit} = $commit;
1601 print "r$log_entry->{revision}";
1602 if (defined $log_entry->{svm_revision}) {
1603 print " (\@$log_entry->{svm_revision})";
1604 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1605 0, $self->svm_uuid);
1607 print " = $commit ($self->{ref_id})\n";
1608 if (defined $_repack && (--$_repack_nr == 0)) {
1609 $_repack_nr = $_repack;
1610 # repack doesn't use any arguments with spaces in them, does it?
1611 print "Running git repack $_repack_flags ...\n";
1612 command_noisy('repack', split(/\s+/, $_repack_flags));
1613 print "Done repacking\n";
1615 return $commit;
1618 sub match_paths {
1619 my ($self, $paths, $r) = @_;
1620 return 1 if $self->{path} eq '';
1621 if (my $path = $paths->{"/$self->{path}"}) {
1622 return ($path->{action} eq 'D') ? 0 : 1;
1624 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1625 if (grep /$self->{path_regex}/, keys %$paths) {
1626 return 1;
1628 my $c = '';
1629 foreach (split m#/#, $self->{path}) {
1630 $c .= "/$_";
1631 next unless ($paths->{$c} &&
1632 ($paths->{$c}->{action} =~ /^[AR]$/));
1633 if ($self->ra->check_path($self->{path}, $r) ==
1634 $SVN::Node::dir) {
1635 return 1;
1638 return 0;
1641 sub find_parent_branch {
1642 my ($self, $paths, $rev) = @_;
1643 return undef unless $self->follow_parent;
1644 unless (defined $paths) {
1645 my $err_handler = $SVN::Error::handler;
1646 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1647 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1648 $paths =
1649 Git::SVN::Ra::dup_changed_paths($_[0]) });
1650 $SVN::Error::handler = $err_handler;
1652 return undef unless defined $paths;
1654 # look for a parent from another branch:
1655 my @b_path_components = split m#/#, $self->rel_path;
1656 my @a_path_components;
1657 my $i;
1658 while (@b_path_components) {
1659 $i = $paths->{'/'.join('/', @b_path_components)};
1660 last if $i && defined $i->{copyfrom_path};
1661 unshift(@a_path_components, pop(@b_path_components));
1663 return undef unless defined $i && defined $i->{copyfrom_path};
1664 my $branch_from = $i->{copyfrom_path};
1665 if (@a_path_components) {
1666 print STDERR "branch_from: $branch_from => ";
1667 $branch_from .= '/'.join('/', @a_path_components);
1668 print STDERR $branch_from, "\n";
1670 my $r = $i->{copyfrom_rev};
1671 my $repos_root = $self->ra->{repos_root};
1672 my $url = $self->ra->{url};
1673 my $new_url = $repos_root . $branch_from;
1674 print STDERR "Found possible branch point: ",
1675 "$new_url => ", $self->full_url, ", $r\n";
1676 $branch_from =~ s#^/##;
1677 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1678 unless ($gs) {
1679 my $ref_id = $self->{ref_id};
1680 $ref_id =~ s/\@\d+$//;
1681 $ref_id .= "\@$r";
1682 # just grow a tail if we're not unique enough :x
1683 $ref_id .= '-' while find_ref($ref_id);
1684 print STDERR "Initializing parent: $ref_id\n";
1685 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1687 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1688 if (!defined $r0 || !defined $parent) {
1689 my ($base, $head) = parse_revision_argument(0, $r);
1690 if ($base <= $r) {
1691 $gs->fetch($base, $r);
1693 ($r0, $parent) = $gs->last_rev_commit;
1695 if (defined $r0 && defined $parent) {
1696 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1697 my $ed;
1698 if ($self->ra->can_do_switch) {
1699 $self->assert_index_clean($parent);
1700 print STDERR "Following parent with do_switch\n";
1701 # do_switch works with svn/trunk >= r22312, but that
1702 # is not included with SVN 1.4.3 (the latest version
1703 # at the moment), so we can't rely on it
1704 $self->{last_commit} = $parent;
1705 $ed = SVN::Git::Fetcher->new($self);
1706 $gs->ra->gs_do_switch($r0, $rev, $gs,
1707 $self->full_url, $ed)
1708 or die "SVN connection failed somewhere...\n";
1709 } else {
1710 print STDERR "Following parent with do_update\n";
1711 $ed = SVN::Git::Fetcher->new($self);
1712 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1713 or die "SVN connection failed somewhere...\n";
1715 print STDERR "Successfully followed parent\n";
1716 return $self->make_log_entry($rev, [$parent], $ed);
1718 return undef;
1721 sub do_fetch {
1722 my ($self, $paths, $rev) = @_;
1723 my $ed;
1724 my ($last_rev, @parents);
1725 if (my $lc = $self->last_commit) {
1726 # we can have a branch that was deleted, then re-added
1727 # under the same name but copied from another path, in
1728 # which case we'll have multiple parents (we don't
1729 # want to break the original ref, nor lose copypath info):
1730 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1731 push @{$log_entry->{parents}}, $lc;
1732 return $log_entry;
1734 $ed = SVN::Git::Fetcher->new($self);
1735 $last_rev = $self->{last_rev};
1736 $ed->{c} = $lc;
1737 @parents = ($lc);
1738 } else {
1739 $last_rev = $rev;
1740 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1741 return $log_entry;
1743 $ed = SVN::Git::Fetcher->new($self);
1745 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1746 die "SVN connection failed somewhere...\n";
1748 $self->make_log_entry($rev, \@parents, $ed);
1751 sub get_untracked {
1752 my ($self, $ed) = @_;
1753 my @out;
1754 my $h = $ed->{empty};
1755 foreach (sort keys %$h) {
1756 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1757 push @out, " $act: " . uri_encode($_);
1758 warn "W: $act: $_\n";
1760 foreach my $t (qw/dir_prop file_prop/) {
1761 $h = $ed->{$t} or next;
1762 foreach my $path (sort keys %$h) {
1763 my $ppath = $path eq '' ? '.' : $path;
1764 foreach my $prop (sort keys %{$h->{$path}}) {
1765 next if $SKIP_PROP{$prop};
1766 my $v = $h->{$path}->{$prop};
1767 my $t_ppath_prop = "$t: " .
1768 uri_encode($ppath) . ' ' .
1769 uri_encode($prop);
1770 if (defined $v) {
1771 push @out, " +$t_ppath_prop " .
1772 uri_encode($v);
1773 } else {
1774 push @out, " -$t_ppath_prop";
1779 foreach my $t (qw/absent_file absent_directory/) {
1780 $h = $ed->{$t} or next;
1781 foreach my $parent (sort keys %$h) {
1782 foreach my $path (sort @{$h->{$parent}}) {
1783 push @out, " $t: " .
1784 uri_encode("$parent/$path");
1785 warn "W: $t: $parent/$path ",
1786 "Insufficient permissions?\n";
1790 \@out;
1793 sub parse_svn_date {
1794 my $date = shift || return '+0000 1970-01-01 00:00:00';
1795 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1796 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1797 croak "Unable to parse date: $date\n";
1798 "+0000 $Y-$m-$d $H:$M:$S";
1801 sub check_author {
1802 my ($author) = @_;
1803 if (!defined $author || length $author == 0) {
1804 $author = '(no author)';
1806 if (defined $::_authors && ! defined $::users{$author}) {
1807 die "Author: $author not defined in $::_authors file\n";
1809 $author;
1812 sub make_log_entry {
1813 my ($self, $rev, $parents, $ed) = @_;
1814 my $untracked = $self->get_untracked($ed);
1816 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1817 print $un "r$rev\n" or croak $!;
1818 print $un $_, "\n" foreach @$untracked;
1819 my %log_entry = ( parents => $parents || [], revision => $rev,
1820 log => '');
1822 my $headrev;
1823 my $logged = delete $self->{logged_rev_props};
1824 if (!$logged || $self->{-want_revprops}) {
1825 my $rp = $self->ra->rev_proplist($rev);
1826 foreach (sort keys %$rp) {
1827 my $v = $rp->{$_};
1828 if (/^svn:(author|date|log)$/) {
1829 $log_entry{$1} = $v;
1830 } elsif ($_ eq 'svm:headrev') {
1831 $headrev = $v;
1832 } else {
1833 print $un " rev_prop: ", uri_encode($_), ' ',
1834 uri_encode($v), "\n";
1837 } else {
1838 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1840 close $un or croak $!;
1842 $log_entry{date} = parse_svn_date($log_entry{date});
1843 $log_entry{log} .= "\n";
1844 my $author = $log_entry{author} = check_author($log_entry{author});
1845 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1846 : ($author, undef);
1847 if (defined $headrev && $self->use_svm_props) {
1848 if ($self->rewrite_root) {
1849 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1850 "options set!\n";
1852 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1853 # we don't want "SVM: initializing mirror for junk" ...
1854 return undef if $r == 0;
1855 my $svm = $self->svm;
1856 if ($uuid ne $svm->{uuid}) {
1857 die "UUID mismatch on SVM path:\n",
1858 "expected: $svm->{uuid}\n",
1859 " got: $uuid\n";
1861 my $full_url = $self->full_url;
1862 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1863 die "Failed to replace '$svm->{replace}' with ",
1864 "'$svm->{source}' in $full_url\n";
1865 # throw away username for storing in records
1866 remove_username($full_url);
1867 $log_entry{metadata} = "$full_url\@$r $uuid";
1868 $log_entry{svm_revision} = $r;
1869 $email ||= "$author\@$uuid"
1870 } elsif ($self->use_svnsync_props) {
1871 my $full_url = $self->svnsync->{url};
1872 $full_url .= "/$self->{path}" if length $self->{path};
1873 remove_username($full_url);
1874 my $uuid = $self->svnsync->{uuid};
1875 $log_entry{metadata} = "$full_url\@$rev $uuid";
1876 $email ||= "$author\@$uuid"
1877 } else {
1878 my $url = $self->metadata_url;
1879 remove_username($url);
1880 $log_entry{metadata} = "$url\@$rev " .
1881 $self->ra->get_uuid;
1882 $email ||= "$author\@" . $self->ra->get_uuid;
1884 $log_entry{name} = $name;
1885 $log_entry{email} = $email;
1886 \%log_entry;
1889 sub fetch {
1890 my ($self, $min_rev, $max_rev, @parents) = @_;
1891 my ($last_rev, $last_commit) = $self->last_rev_commit;
1892 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1893 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1896 sub set_tree_cb {
1897 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1898 $self->{inject_parents} = { $rev => $tree };
1899 $self->fetch(undef, undef);
1902 sub set_tree {
1903 my ($self, $tree) = (shift, shift);
1904 my $log_entry = ::get_commit_entry($tree);
1905 unless ($self->{last_rev}) {
1906 fatal("Must have an existing revision to commit\n");
1908 my %ed_opts = ( r => $self->{last_rev},
1909 log => $log_entry->{log},
1910 ra => $self->ra,
1911 tree_a => $self->{last_commit},
1912 tree_b => $tree,
1913 editor_cb => sub {
1914 $self->set_tree_cb($log_entry, $tree, @_) },
1915 svn_path => $self->{path} );
1916 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1917 print "No changes\nr$self->{last_rev} = $tree\n";
1921 sub rebuild {
1922 my ($self) = @_;
1923 my $db_path = $self->db_path;
1924 return if (-e $db_path && ! -z $db_path);
1925 return unless ::verify_ref($self->refname.'^0');
1926 if (-f $self->{db_root}) {
1927 rename $self->{db_root}, $db_path or die
1928 "rename $self->{db_root} => $db_path failed: $!\n";
1929 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1930 symlink $base, $self->{db_root} or die
1931 "symlink $base => $self->{db_root} failed: $!\n";
1932 return;
1934 print "Rebuilding $db_path ...\n";
1935 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1936 my $latest;
1937 my $full_url = $self->full_url;
1938 remove_username($full_url);
1939 my $svn_uuid;
1940 while (<$rev_list>) {
1941 chomp;
1942 my $c = $_;
1943 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1944 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1945 remove_username($url);
1947 # ignore merges (from set-tree)
1948 next if (!defined $rev || !$uuid);
1950 # if we merged or otherwise started elsewhere, this is
1951 # how we break out of it
1952 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1953 ($full_url && $url && ($url ne $full_url))) {
1954 next;
1956 $latest ||= $rev;
1957 $svn_uuid ||= $uuid;
1959 $self->rev_db_set($rev, $c);
1960 print "r$rev = $c\n";
1962 command_close_pipe($rev_list, $ctx);
1963 print "Done rebuilding $db_path\n";
1966 # rev_db:
1967 # Tie::File seems to be prone to offset errors if revisions get sparse,
1968 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1969 # one of my favorite modules is out :< Next up would be one of the DBM
1970 # modules, but I'm not sure which is most portable... So I'll just
1971 # go with something that's plain-text, but still capable of
1972 # being randomly accessed. So here's my ultra-simple fixed-width
1973 # database. All records are 40 characters + "\n", so it's easy to seek
1974 # to a revision: (41 * rev) is the byte offset.
1975 # A record of 40 0s denotes an empty revision.
1976 # And yes, it's still pretty fast (faster than Tie::File).
1977 # These files are disposable unless noMetadata or useSvmProps is set
1979 sub _rev_db_set {
1980 my ($fh, $rev, $commit) = @_;
1981 my $offset = $rev * 41;
1982 # assume that append is the common case:
1983 seek $fh, 0, 2 or croak $!;
1984 my $pos = tell $fh;
1985 if ($pos < $offset) {
1986 for (1 .. (($offset - $pos) / 41)) {
1987 print $fh (('0' x 40),"\n") or croak $!;
1990 seek $fh, $offset, 0 or croak $!;
1991 print $fh $commit,"\n" or croak $!;
1994 sub mkfile {
1995 my ($path) = @_;
1996 unless (-e $path) {
1997 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1998 mkpath([$dir]) unless -d $dir;
1999 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2000 close $fh or die "Couldn't close (create) $path: $!\n";
2004 sub rev_db_set {
2005 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2006 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2007 my $db = $self->db_path($uuid);
2008 my $db_lock = "$db.lock";
2009 my $sig;
2010 if ($update_ref) {
2011 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2012 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2014 mkfile($db);
2016 $LOCKFILES{$db_lock} = 1;
2017 my $sync;
2018 # both of these options make our .rev_db file very, very important
2019 # and we can't afford to lose it because rebuild() won't work
2020 if ($self->use_svm_props || $self->no_metadata) {
2021 $sync = 1;
2022 copy($db, $db_lock) or die "rev_db_set(@_): ",
2023 "Failed to copy: ",
2024 "$db => $db_lock ($!)\n";
2025 } else {
2026 rename $db, $db_lock or die "rev_db_set(@_): ",
2027 "Failed to rename: ",
2028 "$db => $db_lock ($!)\n";
2030 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2031 _rev_db_set($fh, $rev, $commit);
2032 if ($sync) {
2033 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2034 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2036 close $fh or croak $!;
2037 if ($update_ref) {
2038 $_head = $self;
2039 command_noisy('update-ref', '-m', "r$rev",
2040 $self->refname, $commit);
2042 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2043 "$db_lock => $db ($!)\n";
2044 delete $LOCKFILES{$db_lock};
2045 if ($update_ref) {
2046 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2047 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2048 kill $sig, $$ if defined $sig;
2052 sub rev_db_max {
2053 my ($self) = @_;
2054 $self->rebuild;
2055 my $db_path = $self->db_path;
2056 my @stat = stat $db_path or return 0;
2057 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2058 my $max = $stat[7] / 41;
2059 (($max > 0) ? $max - 1 : 0);
2062 sub rev_db_get {
2063 my ($self, $rev, $uuid) = @_;
2064 my $ret;
2065 my $offset = $rev * 41;
2066 my $db_path = $self->db_path($uuid);
2067 return undef unless -e $db_path;
2068 open my $fh, '<', $db_path or croak $!;
2069 if (sysseek($fh, $offset, 0) == $offset) {
2070 my $read = sysread($fh, $ret, 40);
2071 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2073 close $fh or croak $!;
2074 $ret;
2077 sub find_rev_before {
2078 my ($self, $rev, $eq_ok) = @_;
2079 --$rev unless $eq_ok;
2080 while ($rev > 0) {
2081 if (my $c = $self->rev_db_get($rev)) {
2082 return ($rev, $c);
2084 --$rev;
2086 return (undef, undef);
2089 sub _new {
2090 my ($class, $repo_id, $ref_id, $path) = @_;
2091 unless (defined $repo_id && length $repo_id) {
2092 $repo_id = $Git::SVN::default_repo_id;
2094 unless (defined $ref_id && length $ref_id) {
2095 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2097 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2098 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2099 $_[3] = $path = '' unless (defined $path);
2100 mkpath(["$ENV{GIT_DIR}/svn"]);
2101 bless {
2102 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2103 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2104 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2107 sub db_path {
2108 my ($self, $uuid) = @_;
2109 $uuid ||= $self->ra_uuid;
2110 "$self->{db_root}.$uuid";
2113 sub uri_encode {
2114 my ($f) = @_;
2115 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2119 sub remove_username {
2120 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2123 package Git::SVN::Prompt;
2124 use strict;
2125 use warnings;
2126 require SVN::Core;
2127 use vars qw/$_no_auth_cache $_username/;
2129 sub simple {
2130 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2131 $may_save = undef if $_no_auth_cache;
2132 $default_username = $_username if defined $_username;
2133 if (defined $default_username && length $default_username) {
2134 if (defined $realm && length $realm) {
2135 print STDERR "Authentication realm: $realm\n";
2136 STDERR->flush;
2138 $cred->username($default_username);
2139 } else {
2140 username($cred, $realm, $may_save, $pool);
2142 $cred->password(_read_password("Password for '" .
2143 $cred->username . "': ", $realm));
2144 $cred->may_save($may_save);
2145 $SVN::_Core::SVN_NO_ERROR;
2148 sub ssl_server_trust {
2149 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2150 $may_save = undef if $_no_auth_cache;
2151 print STDERR "Error validating server certificate for '$realm':\n";
2152 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2153 print STDERR " - The certificate is not issued by a trusted ",
2154 "authority. Use the\n",
2155 " fingerprint to validate the certificate manually!\n";
2157 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2158 print STDERR " - The certificate hostname does not match.\n";
2160 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2161 print STDERR " - The certificate is not yet valid.\n";
2163 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2164 print STDERR " - The certificate has expired.\n";
2166 if ($failures & $SVN::Auth::SSL::OTHER) {
2167 print STDERR " - The certificate has an unknown error.\n";
2169 printf STDERR
2170 "Certificate information:\n".
2171 " - Hostname: %s\n".
2172 " - Valid: from %s until %s\n".
2173 " - Issuer: %s\n".
2174 " - Fingerprint: %s\n",
2175 map $cert_info->$_, qw(hostname valid_from valid_until
2176 issuer_dname fingerprint);
2177 my $choice;
2178 prompt:
2179 print STDERR $may_save ?
2180 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2181 "(R)eject or accept (t)emporarily? ";
2182 STDERR->flush;
2183 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2184 if ($choice =~ /^t$/i) {
2185 $cred->may_save(undef);
2186 } elsif ($choice =~ /^r$/i) {
2187 return -1;
2188 } elsif ($may_save && $choice =~ /^p$/i) {
2189 $cred->may_save($may_save);
2190 } else {
2191 goto prompt;
2193 $cred->accepted_failures($failures);
2194 $SVN::_Core::SVN_NO_ERROR;
2197 sub ssl_client_cert {
2198 my ($cred, $realm, $may_save, $pool) = @_;
2199 $may_save = undef if $_no_auth_cache;
2200 print STDERR "Client certificate filename: ";
2201 STDERR->flush;
2202 chomp(my $filename = <STDIN>);
2203 $cred->cert_file($filename);
2204 $cred->may_save($may_save);
2205 $SVN::_Core::SVN_NO_ERROR;
2208 sub ssl_client_cert_pw {
2209 my ($cred, $realm, $may_save, $pool) = @_;
2210 $may_save = undef if $_no_auth_cache;
2211 $cred->password(_read_password("Password: ", $realm));
2212 $cred->may_save($may_save);
2213 $SVN::_Core::SVN_NO_ERROR;
2216 sub username {
2217 my ($cred, $realm, $may_save, $pool) = @_;
2218 $may_save = undef if $_no_auth_cache;
2219 if (defined $realm && length $realm) {
2220 print STDERR "Authentication realm: $realm\n";
2222 my $username;
2223 if (defined $_username) {
2224 $username = $_username;
2225 } else {
2226 print STDERR "Username: ";
2227 STDERR->flush;
2228 chomp($username = <STDIN>);
2230 $cred->username($username);
2231 $cred->may_save($may_save);
2232 $SVN::_Core::SVN_NO_ERROR;
2235 sub _read_password {
2236 my ($prompt, $realm) = @_;
2237 print STDERR $prompt;
2238 STDERR->flush;
2239 require Term::ReadKey;
2240 Term::ReadKey::ReadMode('noecho');
2241 my $password = '';
2242 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2243 last if $key =~ /[\012\015]/; # \n\r
2244 $password .= $key;
2246 Term::ReadKey::ReadMode('restore');
2247 print STDERR "\n";
2248 STDERR->flush;
2249 $password;
2252 package main;
2255 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2256 $SVN::Node::dir.$SVN::Node::unknown.
2257 $SVN::Node::none.$SVN::Node::file.
2258 $SVN::Node::dir.$SVN::Node::unknown.
2259 $SVN::Auth::SSL::CNMISMATCH.
2260 $SVN::Auth::SSL::NOTYETVALID.
2261 $SVN::Auth::SSL::EXPIRED.
2262 $SVN::Auth::SSL::UNKNOWNCA.
2263 $SVN::Auth::SSL::OTHER;
2266 package SVN::Git::Fetcher;
2267 use vars qw/@ISA/;
2268 use strict;
2269 use warnings;
2270 use Carp qw/croak/;
2271 use IO::File qw//;
2272 use Digest::MD5;
2274 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2275 sub new {
2276 my ($class, $git_svn) = @_;
2277 my $self = SVN::Delta::Editor->new;
2278 bless $self, $class;
2279 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2280 $self->{empty} = {};
2281 $self->{dir_prop} = {};
2282 $self->{file_prop} = {};
2283 $self->{absent_dir} = {};
2284 $self->{absent_file} = {};
2285 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2286 $self;
2289 sub set_path_strip {
2290 my ($self, $path) = @_;
2291 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2294 sub open_root {
2295 { path => '' };
2298 sub open_directory {
2299 my ($self, $path, $pb, $rev) = @_;
2300 { path => $path };
2303 sub git_path {
2304 my ($self, $path) = @_;
2305 if ($self->{path_strip}) {
2306 $path =~ s!$self->{path_strip}!! or
2307 die "Failed to strip path '$path' ($self->{path_strip})\n";
2309 $path;
2312 sub delete_entry {
2313 my ($self, $path, $rev, $pb) = @_;
2315 my $gpath = $self->git_path($path);
2316 return undef if ($gpath eq '');
2318 # remove entire directories.
2319 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2320 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2321 -r --name-only -z/,
2322 $self->{c}, '--', $gpath);
2323 local $/ = "\0";
2324 while (<$ls>) {
2325 chomp;
2326 $self->{gii}->remove($_);
2327 print "\tD\t$_\n" unless $::_q;
2329 print "\tD\t$gpath/\n" unless $::_q;
2330 command_close_pipe($ls, $ctx);
2331 $self->{empty}->{$path} = 0
2332 } else {
2333 $self->{gii}->remove($gpath);
2334 print "\tD\t$gpath\n" unless $::_q;
2336 undef;
2339 sub open_file {
2340 my ($self, $path, $pb, $rev) = @_;
2341 my $gpath = $self->git_path($path);
2342 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2343 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2344 unless (defined $mode && defined $blob) {
2345 die "$path was not found in commit $self->{c} (r$rev)\n";
2347 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2348 pool => SVN::Pool->new, action => 'M' };
2351 sub add_file {
2352 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2353 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2354 delete $self->{empty}->{$dir};
2355 { path => $path, mode_a => 100644, mode_b => 100644,
2356 pool => SVN::Pool->new, action => 'A' };
2359 sub add_directory {
2360 my ($self, $path, $cp_path, $cp_rev) = @_;
2361 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2362 delete $self->{empty}->{$dir};
2363 $self->{empty}->{$path} = 1;
2364 { path => $path };
2367 sub change_dir_prop {
2368 my ($self, $db, $prop, $value) = @_;
2369 $self->{dir_prop}->{$db->{path}} ||= {};
2370 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2371 undef;
2374 sub absent_directory {
2375 my ($self, $path, $pb) = @_;
2376 $self->{absent_dir}->{$pb->{path}} ||= [];
2377 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2378 undef;
2381 sub absent_file {
2382 my ($self, $path, $pb) = @_;
2383 $self->{absent_file}->{$pb->{path}} ||= [];
2384 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2385 undef;
2388 sub change_file_prop {
2389 my ($self, $fb, $prop, $value) = @_;
2390 if ($prop eq 'svn:executable') {
2391 if ($fb->{mode_b} != 120000) {
2392 $fb->{mode_b} = defined $value ? 100755 : 100644;
2394 } elsif ($prop eq 'svn:special') {
2395 $fb->{mode_b} = defined $value ? 120000 : 100644;
2396 } else {
2397 $self->{file_prop}->{$fb->{path}} ||= {};
2398 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2400 undef;
2403 sub apply_textdelta {
2404 my ($self, $fb, $exp) = @_;
2405 my $fh = IO::File->new_tmpfile;
2406 $fh->autoflush(1);
2407 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2408 # (but $base does not,) so dup() it for reading in close_file
2409 open my $dup, '<&', $fh or croak $!;
2410 my $base = IO::File->new_tmpfile;
2411 $base->autoflush(1);
2412 if ($fb->{blob}) {
2413 defined (my $pid = fork) or croak $!;
2414 if (!$pid) {
2415 open STDOUT, '>&', $base or croak $!;
2416 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2417 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2419 waitpid $pid, 0;
2420 croak $? if $?;
2422 if (defined $exp) {
2423 seek $base, 0, 0 or croak $!;
2424 my $md5 = Digest::MD5->new;
2425 $md5->addfile($base);
2426 my $got = $md5->hexdigest;
2427 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2428 "expected: $exp\n",
2429 " got: $got\n" if ($got ne $exp);
2432 seek $base, 0, 0 or croak $!;
2433 $fb->{fh} = $dup;
2434 $fb->{base} = $base;
2435 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2438 sub close_file {
2439 my ($self, $fb, $exp) = @_;
2440 my $hash;
2441 my $path = $self->git_path($fb->{path});
2442 if (my $fh = $fb->{fh}) {
2443 seek($fh, 0, 0) or croak $!;
2444 my $md5 = Digest::MD5->new;
2445 $md5->addfile($fh);
2446 my $got = $md5->hexdigest;
2447 die "Checksum mismatch: $path\n",
2448 "expected: $exp\n got: $got\n" if ($got ne $exp);
2449 seek($fh, 0, 0) or croak $!;
2450 if ($fb->{mode_b} == 120000) {
2451 read($fh, my $buf, 5) == 5 or croak $!;
2452 $buf eq 'link ' or die "$path has mode 120000",
2453 "but is not a link\n";
2455 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2456 if (!$pid) {
2457 open STDIN, '<&', $fh or croak $!;
2458 exec qw/git-hash-object -w --stdin/ or croak $!;
2460 chomp($hash = do { local $/; <$out> });
2461 close $out or croak $!;
2462 close $fh or croak $!;
2463 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2464 close $fb->{base} or croak $!;
2465 } else {
2466 $hash = $fb->{blob} or die "no blob information\n";
2468 $fb->{pool}->clear;
2469 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2470 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2471 undef;
2474 sub abort_edit {
2475 my $self = shift;
2476 $self->{nr} = $self->{gii}->{nr};
2477 delete $self->{gii};
2478 $self->SUPER::abort_edit(@_);
2481 sub close_edit {
2482 my $self = shift;
2483 $self->{git_commit_ok} = 1;
2484 $self->{nr} = $self->{gii}->{nr};
2485 delete $self->{gii};
2486 $self->SUPER::close_edit(@_);
2489 package SVN::Git::Editor;
2490 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2491 use strict;
2492 use warnings;
2493 use Carp qw/croak/;
2494 use IO::File;
2495 use Digest::MD5;
2497 sub new {
2498 my ($class, $opts) = @_;
2499 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2500 die "$_ required!\n" unless (defined $opts->{$_});
2503 my $pool = SVN::Pool->new;
2504 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2505 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2506 $opts->{r}, $mods);
2508 # $opts->{ra} functions should not be used after this:
2509 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2510 $opts->{editor_cb}, $pool);
2511 my $self = SVN::Delta::Editor->new(@ce, $pool);
2512 bless $self, $class;
2513 foreach (qw/svn_path r tree_a tree_b/) {
2514 $self->{$_} = $opts->{$_};
2516 $self->{url} = $opts->{ra}->{url};
2517 $self->{mods} = $mods;
2518 $self->{types} = $types;
2519 $self->{pool} = $pool;
2520 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2521 $self->{rm} = { };
2522 $self->{path_prefix} = length $self->{svn_path} ?
2523 "$self->{svn_path}/" : '';
2524 return $self;
2527 sub generate_diff {
2528 my ($tree_a, $tree_b) = @_;
2529 my @diff_tree = qw(diff-tree -z -r);
2530 if ($_cp_similarity) {
2531 push @diff_tree, "-C$_cp_similarity";
2532 } else {
2533 push @diff_tree, '-C';
2535 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2536 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2537 push @diff_tree, $tree_a, $tree_b;
2538 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2539 local $/ = "\0";
2540 my $state = 'meta';
2541 my @mods;
2542 while (<$diff_fh>) {
2543 chomp $_; # this gets rid of the trailing "\0"
2544 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2545 $::sha1\s($::sha1)\s
2546 ([MTCRAD])\d*$/xo) {
2547 push @mods, { mode_a => $1, mode_b => $2,
2548 sha1_b => $3, chg => $4 };
2549 if ($4 =~ /^(?:C|R)$/) {
2550 $state = 'file_a';
2551 } else {
2552 $state = 'file_b';
2554 } elsif ($state eq 'file_a') {
2555 my $x = $mods[$#mods] or croak "Empty array\n";
2556 if ($x->{chg} !~ /^(?:C|R)$/) {
2557 croak "Error parsing $_, $x->{chg}\n";
2559 $x->{file_a} = $_;
2560 $state = 'file_b';
2561 } elsif ($state eq 'file_b') {
2562 my $x = $mods[$#mods] or croak "Empty array\n";
2563 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2564 croak "Error parsing $_, $x->{chg}\n";
2566 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2567 croak "Error parsing $_, $x->{chg}\n";
2569 $x->{file_b} = $_;
2570 $state = 'meta';
2571 } else {
2572 croak "Error parsing $_\n";
2575 command_close_pipe($diff_fh, $ctx);
2576 \@mods;
2579 sub check_diff_paths {
2580 my ($ra, $pfx, $rev, $mods) = @_;
2581 my %types;
2582 $pfx .= '/' if length $pfx;
2584 sub type_diff_paths {
2585 my ($ra, $types, $path, $rev) = @_;
2586 my @p = split m#/+#, $path;
2587 my $c = shift @p;
2588 unless (defined $types->{$c}) {
2589 $types->{$c} = $ra->check_path($c, $rev);
2591 while (@p) {
2592 $c .= '/' . shift @p;
2593 next if defined $types->{$c};
2594 $types->{$c} = $ra->check_path($c, $rev);
2598 foreach my $m (@$mods) {
2599 foreach my $f (qw/file_a file_b/) {
2600 next unless defined $m->{$f};
2601 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2602 if (length $pfx.$dir && ! defined $types{$dir}) {
2603 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2607 \%types;
2610 sub split_path {
2611 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2614 sub repo_path {
2615 my ($self, $path) = @_;
2616 $self->{path_prefix}.(defined $path ? $path : '');
2619 sub url_path {
2620 my ($self, $path) = @_;
2621 $self->{url} . '/' . $self->repo_path($path);
2624 sub rmdirs {
2625 my ($self) = @_;
2626 my $rm = $self->{rm};
2627 delete $rm->{''}; # we never delete the url we're tracking
2628 return unless %$rm;
2630 foreach (keys %$rm) {
2631 my @d = split m#/#, $_;
2632 my $c = shift @d;
2633 $rm->{$c} = 1;
2634 while (@d) {
2635 $c .= '/' . shift @d;
2636 $rm->{$c} = 1;
2639 delete $rm->{$self->{svn_path}};
2640 delete $rm->{''}; # we never delete the url we're tracking
2641 return unless %$rm;
2643 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2644 $self->{tree_b});
2645 local $/ = "\0";
2646 while (<$fh>) {
2647 chomp;
2648 my @dn = split m#/#, $_;
2649 while (pop @dn) {
2650 delete $rm->{join '/', @dn};
2652 unless (%$rm) {
2653 close $fh;
2654 return;
2657 command_close_pipe($fh, $ctx);
2659 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2660 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2661 $self->close_directory($bat->{$d}, $p);
2662 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2663 print "\tD+\t$d/\n" unless $::_q;
2664 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2665 delete $bat->{$d};
2669 sub open_or_add_dir {
2670 my ($self, $full_path, $baton) = @_;
2671 my $t = $self->{types}->{$full_path};
2672 if (!defined $t) {
2673 die "$full_path not known in r$self->{r} or we have a bug!\n";
2675 if ($t == $SVN::Node::none) {
2676 return $self->add_directory($full_path, $baton,
2677 undef, -1, $self->{pool});
2678 } elsif ($t == $SVN::Node::dir) {
2679 return $self->open_directory($full_path, $baton,
2680 $self->{r}, $self->{pool});
2682 print STDERR "$full_path already exists in repository at ",
2683 "r$self->{r} and it is not a directory (",
2684 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2685 exit 1;
2688 sub ensure_path {
2689 my ($self, $path) = @_;
2690 my $bat = $self->{bat};
2691 my $repo_path = $self->repo_path($path);
2692 return $bat->{''} unless (length $repo_path);
2693 my @p = split m#/+#, $repo_path;
2694 my $c = shift @p;
2695 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2696 while (@p) {
2697 my $c0 = $c;
2698 $c .= '/' . shift @p;
2699 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2701 return $bat->{$c};
2704 sub A {
2705 my ($self, $m) = @_;
2706 my ($dir, $file) = split_path($m->{file_b});
2707 my $pbat = $self->ensure_path($dir);
2708 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2709 undef, -1);
2710 print "\tA\t$m->{file_b}\n" unless $::_q;
2711 $self->chg_file($fbat, $m);
2712 $self->close_file($fbat,undef,$self->{pool});
2715 sub C {
2716 my ($self, $m) = @_;
2717 my ($dir, $file) = split_path($m->{file_b});
2718 my $pbat = $self->ensure_path($dir);
2719 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2720 $self->url_path($m->{file_a}), $self->{r});
2721 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2722 $self->chg_file($fbat, $m);
2723 $self->close_file($fbat,undef,$self->{pool});
2726 sub delete_entry {
2727 my ($self, $path, $pbat) = @_;
2728 my $rpath = $self->repo_path($path);
2729 my ($dir, $file) = split_path($rpath);
2730 $self->{rm}->{$dir} = 1;
2731 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2734 sub R {
2735 my ($self, $m) = @_;
2736 my ($dir, $file) = split_path($m->{file_b});
2737 my $pbat = $self->ensure_path($dir);
2738 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2739 $self->url_path($m->{file_a}), $self->{r});
2740 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2741 $self->chg_file($fbat, $m);
2742 $self->close_file($fbat,undef,$self->{pool});
2744 ($dir, $file) = split_path($m->{file_a});
2745 $pbat = $self->ensure_path($dir);
2746 $self->delete_entry($m->{file_a}, $pbat);
2749 sub M {
2750 my ($self, $m) = @_;
2751 my ($dir, $file) = split_path($m->{file_b});
2752 my $pbat = $self->ensure_path($dir);
2753 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2754 $pbat,$self->{r},$self->{pool});
2755 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2756 $self->chg_file($fbat, $m);
2757 $self->close_file($fbat,undef,$self->{pool});
2760 sub T { shift->M(@_) }
2762 sub change_file_prop {
2763 my ($self, $fbat, $pname, $pval) = @_;
2764 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2767 sub chg_file {
2768 my ($self, $fbat, $m) = @_;
2769 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2770 $self->change_file_prop($fbat,'svn:executable','*');
2771 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2772 $self->change_file_prop($fbat,'svn:executable',undef);
2774 my $fh = IO::File->new_tmpfile or croak $!;
2775 if ($m->{mode_b} =~ /^120/) {
2776 print $fh 'link ' or croak $!;
2777 $self->change_file_prop($fbat,'svn:special','*');
2778 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2779 $self->change_file_prop($fbat,'svn:special',undef);
2781 defined(my $pid = fork) or croak $!;
2782 if (!$pid) {
2783 open STDOUT, '>&', $fh or croak $!;
2784 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2786 waitpid $pid, 0;
2787 croak $? if $?;
2788 $fh->flush == 0 or croak $!;
2789 seek $fh, 0, 0 or croak $!;
2791 my $md5 = Digest::MD5->new;
2792 $md5->addfile($fh) or croak $!;
2793 seek $fh, 0, 0 or croak $!;
2795 my $exp = $md5->hexdigest;
2796 my $pool = SVN::Pool->new;
2797 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2798 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2799 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2800 $pool->clear;
2802 close $fh or croak $!;
2805 sub D {
2806 my ($self, $m) = @_;
2807 my ($dir, $file) = split_path($m->{file_b});
2808 my $pbat = $self->ensure_path($dir);
2809 print "\tD\t$m->{file_b}\n" unless $::_q;
2810 $self->delete_entry($m->{file_b}, $pbat);
2813 sub close_edit {
2814 my ($self) = @_;
2815 my ($p,$bat) = ($self->{pool}, $self->{bat});
2816 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2817 $self->close_directory($bat->{$_}, $p);
2819 $self->SUPER::close_edit($p);
2820 $p->clear;
2823 sub abort_edit {
2824 my ($self) = @_;
2825 $self->SUPER::abort_edit($self->{pool});
2828 sub DESTROY {
2829 my $self = shift;
2830 $self->SUPER::DESTROY(@_);
2831 $self->{pool}->clear;
2834 # this drives the editor
2835 sub apply_diff {
2836 my ($self) = @_;
2837 my $mods = $self->{mods};
2838 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2839 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2840 my $f = $m->{chg};
2841 if (defined $o{$f}) {
2842 $self->$f($m);
2843 } else {
2844 fatal("Invalid change type: $f\n");
2847 $self->rmdirs if $_rmdir;
2848 if (@$mods == 0) {
2849 $self->abort_edit;
2850 } else {
2851 $self->close_edit;
2853 return scalar @$mods;
2856 package Git::SVN::Ra;
2857 use vars qw/@ISA $config_dir $_log_window_size/;
2858 use strict;
2859 use warnings;
2860 my ($can_do_switch, %ignored_err, $RA);
2862 BEGIN {
2863 # enforce temporary pool usage for some simple functions
2864 my $e;
2865 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2866 $e .= "sub $_ {
2867 my \$self = shift;
2868 my \$pool = SVN::Pool->new;
2869 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2870 \$pool->clear;
2871 wantarray ? \@ret : \$ret[0]; }\n";
2874 # get_dir needs $pool held in cache for dirents to work,
2875 # check_path is cacheable and rev_proplist is close enough
2876 # for our purposes.
2877 foreach (qw/check_path get_dir rev_proplist/) {
2878 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2879 my \$self = shift;
2880 my \$r = pop;
2881 my \$k = join(\"\\0\", \@_);
2882 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2883 return wantarray ? \@\$x : \$x->[0];
2885 my \$pool = SVN::Pool->new;
2886 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2887 if (\$r != \$${_}_rev) {
2888 \%${_}_cache = ( pool => [] );
2889 \$${_}_rev = \$r;
2891 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2892 push \@{\$${_}_cache{pool}}, \$pool;
2893 wantarray ? \@ret : \$ret[0]; }\n";
2895 $e .= "\n1;";
2896 eval $e or die $@;
2899 sub new {
2900 my ($class, $url) = @_;
2901 $url =~ s!/+$!!;
2902 return $RA if ($RA && $RA->{url} eq $url);
2903 $RA->{pool}->clear if $RA;
2905 SVN::_Core::svn_config_ensure($config_dir, undef);
2906 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2907 SVN::Client::get_simple_provider(),
2908 SVN::Client::get_ssl_server_trust_file_provider(),
2909 SVN::Client::get_simple_prompt_provider(
2910 \&Git::SVN::Prompt::simple, 2),
2911 SVN::Client::get_ssl_client_cert_prompt_provider(
2912 \&Git::SVN::Prompt::ssl_client_cert, 2),
2913 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2914 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2915 SVN::Client::get_username_provider(),
2916 SVN::Client::get_ssl_server_trust_prompt_provider(
2917 \&Git::SVN::Prompt::ssl_server_trust),
2918 SVN::Client::get_username_prompt_provider(
2919 \&Git::SVN::Prompt::username, 2),
2921 my $config = SVN::Core::config_get_config($config_dir);
2922 my $self = SVN::Ra->new(url => $url, auth => $baton,
2923 config => $config,
2924 pool => SVN::Pool->new,
2925 auth_provider_callbacks => $callbacks);
2926 $self->{svn_path} = $url;
2927 $self->{repos_root} = $self->get_repos_root;
2928 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2929 $RA = bless $self, $class;
2932 sub DESTROY {
2933 # do not call the real DESTROY since we store ourselves in $RA
2936 sub get_log {
2937 my ($self, @args) = @_;
2938 my $pool = SVN::Pool->new;
2939 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2940 my $ret = $self->SUPER::get_log(@args, $pool);
2941 $pool->clear;
2942 $ret;
2945 sub get_commit_editor {
2946 my ($self, $log, $cb, $pool) = @_;
2947 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2948 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2951 sub gs_do_update {
2952 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2953 my $new = ($rev_a == $rev_b);
2954 my $path = $gs->{path};
2956 if ($new && -e $gs->{index}) {
2957 unlink $gs->{index} or die
2958 "Couldn't unlink index: $gs->{index}: $!\n";
2960 my $pool = SVN::Pool->new;
2961 $editor->set_path_strip($path);
2962 my (@pc) = split m#/#, $path;
2963 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2964 1, $editor, $pool);
2965 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2967 # Since we can't rely on svn_ra_reparent being available, we'll
2968 # just have to do some magic with set_path to make it so
2969 # we only want a partial path.
2970 my $sp = '';
2971 my $final = join('/', @pc);
2972 while (@pc) {
2973 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2974 $sp .= '/' if length $sp;
2975 $sp .= shift @pc;
2977 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2979 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2981 $reporter->finish_report($pool);
2982 $pool->clear;
2983 $editor->{git_commit_ok};
2986 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2987 # svn_ra_reparent didn't work before 1.4)
2988 sub gs_do_switch {
2989 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2990 my $path = $gs->{path};
2991 my $pool = SVN::Pool->new;
2993 my $full_url = $self->{url};
2994 my $old_url = $full_url;
2995 $full_url .= "/$path" if length $path;
2996 my ($ra, $reparented);
2997 if ($old_url ne $full_url) {
2998 if ($old_url !~ m#^svn(\+ssh)?://#) {
2999 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3000 $pool);
3001 $self->{url} = $full_url;
3002 $reparented = 1;
3003 } else {
3004 $ra = Git::SVN::Ra->new($full_url);
3007 $ra ||= $self;
3008 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3009 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3010 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3011 $reporter->finish_report($pool);
3013 if ($reparented) {
3014 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3015 $self->{url} = $old_url;
3018 $pool->clear;
3019 $editor->{git_commit_ok};
3022 sub gs_fetch_loop_common {
3023 my ($self, $base, $head, $gsv, $globs) = @_;
3024 return if ($base > $head);
3025 my $inc = $_log_window_size;
3026 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3027 my %common;
3028 my $common_max = scalar @$gsv;
3030 foreach my $gs (@$gsv) {
3031 my @tmp = split m#/#, $gs->{path};
3032 my $p = '';
3033 foreach (@tmp) {
3034 $p .= length($p) ? "/$_" : $_;
3035 $common{$p} ||= 0;
3036 $common{$p}++;
3039 $globs ||= [];
3040 $common_max += scalar @$globs;
3041 foreach my $glob (@$globs) {
3042 my @tmp = split m#/#, $glob->{path}->{left};
3043 my $p = '';
3044 foreach (@tmp) {
3045 $p .= length($p) ? "/$_" : $_;
3046 $common{$p} ||= 0;
3047 $common{$p}++;
3051 my $longest_path = '';
3052 foreach (sort {length $b <=> length $a} keys %common) {
3053 if ($common{$_} == $common_max) {
3054 $longest_path = $_;
3055 last;
3058 while (1) {
3059 my %revs;
3060 my $err;
3061 my $err_handler = $SVN::Error::handler;
3062 $SVN::Error::handler = sub {
3063 ($err) = @_;
3064 skip_unknown_revs($err);
3066 sub _cb {
3067 my ($paths, $r, $author, $date, $log) = @_;
3068 [ dup_changed_paths($paths),
3069 { author => $author, date => $date, log => $log } ];
3071 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3072 sub { $revs{$_[1]} = _cb(@_) });
3073 if ($err && $max >= $head) {
3074 print STDERR "Path '$longest_path' ",
3075 "was probably deleted:\n",
3076 $err->expanded_message,
3077 "\nWill attempt to follow ",
3078 "revisions r$min .. r$max ",
3079 "committed before the deletion\n";
3080 my $hi = $max;
3081 while (--$hi >= $min) {
3082 my $ok;
3083 $self->get_log([$longest_path], $min, $hi,
3084 0, 1, 1, sub {
3085 $ok ||= $_[1];
3086 $revs{$_[1]} = _cb(@_) });
3087 if ($ok) {
3088 print STDERR "r$min .. r$ok OK\n";
3089 last;
3093 $SVN::Error::handler = $err_handler;
3095 my %exists = map { $_->{path} => $_ } @$gsv;
3096 foreach my $r (sort {$a <=> $b} keys %revs) {
3097 my ($paths, $logged) = @{$revs{$r}};
3099 foreach my $gs ($self->match_globs(\%exists, $paths,
3100 $globs, $r)) {
3101 if ($gs->rev_db_max >= $r) {
3102 next;
3104 next unless $gs->match_paths($paths, $r);
3105 $gs->{logged_rev_props} = $logged;
3106 if (my $last_commit = $gs->last_commit) {
3107 $gs->assert_index_clean($last_commit);
3109 my $log_entry = $gs->do_fetch($paths, $r);
3110 if ($log_entry) {
3111 $gs->do_git_commit($log_entry);
3114 foreach my $g (@$globs) {
3115 my $k = "svn-remote.$g->{remote}." .
3116 "$g->{t}-maxRev";
3117 Git::SVN::tmp_config($k, $r);
3120 # pre-fill the .rev_db since it'll eventually get filled in
3121 # with '0' x40 if something new gets committed
3122 foreach my $gs (@$gsv) {
3123 next if defined $gs->rev_db_get($max);
3124 $gs->rev_db_set($max, 0 x40);
3126 foreach my $g (@$globs) {
3127 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3128 Git::SVN::tmp_config($k, $max);
3130 last if $max >= $head;
3131 $min = $max + 1;
3132 $max += $inc;
3133 $max = $head if ($max > $head);
3137 sub match_globs {
3138 my ($self, $exists, $paths, $globs, $r) = @_;
3140 sub get_dir_check {
3141 my ($self, $exists, $g, $r) = @_;
3142 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3143 return unless scalar @x == 3;
3144 my $dirents = $x[0];
3145 foreach my $de (keys %$dirents) {
3146 next if $dirents->{$de}->kind != $SVN::Node::dir;
3147 my $p = $g->{path}->full_path($de);
3148 next if $exists->{$p};
3149 next if (length $g->{path}->{right} &&
3150 ($self->check_path($p, $r) !=
3151 $SVN::Node::dir));
3152 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3153 $g->{ref}->full_path($de), 1);
3156 foreach my $g (@$globs) {
3157 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3158 if ($path->{action} =~ /^[AR]$/) {
3159 get_dir_check($self, $exists, $g, $r);
3162 foreach (keys %$paths) {
3163 if (/$g->{path}->{left_regex}/ &&
3164 !/$g->{path}->{regex}/) {
3165 next if $paths->{$_}->{action} !~ /^[AR]$/;
3166 get_dir_check($self, $exists, $g, $r);
3168 next unless /$g->{path}->{regex}/;
3169 my $p = $1;
3170 my $pathname = $g->{path}->full_path($p);
3171 next if $exists->{$pathname};
3172 next if ($self->check_path($pathname, $r) !=
3173 $SVN::Node::dir);
3174 $exists->{$pathname} = Git::SVN->init(
3175 $self->{url}, $pathname, undef,
3176 $g->{ref}->full_path($p), 1);
3178 my $c = '';
3179 foreach (split m#/#, $g->{path}->{left}) {
3180 $c .= "/$_";
3181 next unless ($paths->{$c} &&
3182 ($paths->{$c}->{action} =~ /^[AR]$/));
3183 get_dir_check($self, $exists, $g, $r);
3186 values %$exists;
3189 sub minimize_url {
3190 my ($self) = @_;
3191 return $self->{url} if ($self->{url} eq $self->{repos_root});
3192 my $url = $self->{repos_root};
3193 my @components = split(m!/!, $self->{svn_path});
3194 my $c = '';
3195 do {
3196 $url .= "/$c" if length $c;
3197 eval { (ref $self)->new($url)->get_latest_revnum };
3198 } while ($@ && ($c = shift @components));
3199 $url;
3202 sub can_do_switch {
3203 my $self = shift;
3204 unless (defined $can_do_switch) {
3205 my $pool = SVN::Pool->new;
3206 my $rep = eval {
3207 $self->do_switch(1, '', 0, $self->{url},
3208 SVN::Delta::Editor->new, $pool);
3210 if ($@) {
3211 $can_do_switch = 0;
3212 } else {
3213 $rep->abort_report($pool);
3214 $can_do_switch = 1;
3216 $pool->clear;
3218 $can_do_switch;
3221 sub skip_unknown_revs {
3222 my ($err) = @_;
3223 my $errno = $err->apr_err();
3224 # Maybe the branch we're tracking didn't
3225 # exist when the repo started, so it's
3226 # not an error if it doesn't, just continue
3228 # Wonderfully consistent library, eh?
3229 # 160013 - svn:// and file://
3230 # 175002 - http(s)://
3231 # 175007 - http(s):// (this repo required authorization, too...)
3232 # More codes may be discovered later...
3233 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3234 my $err_key = $err->expanded_message;
3235 # revision numbers change every time, filter them out
3236 $err_key =~ s/\d+/\0/g;
3237 $err_key = "$errno\0$err_key";
3238 unless ($ignored_err{$err_key}) {
3239 warn "W: Ignoring error from SVN, path probably ",
3240 "does not exist: ($errno): ",
3241 $err->expanded_message,"\n";
3242 $ignored_err{$err_key} = 1;
3244 return;
3246 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3249 # svn_log_changed_path_t objects passed to get_log are likely to be
3250 # overwritten even if only the refs are copied to an external variable,
3251 # so we should dup the structures in their entirety. Using an externally
3252 # passed pool (instead of our temporary and quickly cleared pool in
3253 # Git::SVN::Ra) does not help matters at all...
3254 sub dup_changed_paths {
3255 my ($paths) = @_;
3256 return undef unless $paths;
3257 my %ret;
3258 foreach my $p (keys %$paths) {
3259 my $i = $paths->{$p};
3260 my %s = map { $_ => $i->$_ }
3261 qw/copyfrom_path copyfrom_rev action/;
3262 $ret{$p} = \%s;
3264 \%ret;
3267 package Git::SVN::Log;
3268 use strict;
3269 use warnings;
3270 use POSIX qw/strftime/;
3271 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3272 %rusers $show_commit $incremental/;
3273 my $l_fmt;
3275 sub cmt_showable {
3276 my ($c) = @_;
3277 return 1 if defined $c->{r};
3279 # big commit message got truncated by the 16k pretty buffer in rev-list
3280 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3281 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3282 @{$c->{l}} = ();
3283 my @log = command(qw/cat-file commit/, $c->{c});
3285 # shift off the headers
3286 shift @log while ($log[0] ne '');
3287 shift @log;
3289 # TODO: make $c->{l} not have a trailing newline in the future
3290 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3292 (undef, $c->{r}, undef) = ::extract_metadata(
3293 (grep(/^git-svn-id: /, @log))[-1]);
3295 return defined $c->{r};
3298 sub log_use_color {
3299 return 1 if $color;
3300 my ($dc, $dcvar);
3301 $dcvar = 'color.diff';
3302 $dc = `git-config --get $dcvar`;
3303 if ($dc eq '') {
3304 # nothing at all; fallback to "diff.color"
3305 $dcvar = 'diff.color';
3306 $dc = `git-config --get $dcvar`;
3308 chomp($dc);
3309 if ($dc eq 'auto') {
3310 my $pc;
3311 $pc = `git-config --get color.pager`;
3312 if ($pc eq '') {
3313 # does not have it -- fallback to pager.color
3314 $pc = `git-config --bool --get pager.color`;
3316 else {
3317 $pc = `git-config --bool --get color.pager`;
3318 if ($?) {
3319 $pc = 'false';
3322 chomp($pc);
3323 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3324 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3326 return 0;
3328 return 0 if $dc eq 'never';
3329 return 1 if $dc eq 'always';
3330 chomp($dc = `git-config --bool --get $dcvar`);
3331 return ($dc eq 'true');
3334 sub git_svn_log_cmd {
3335 my ($r_min, $r_max, @args) = @_;
3336 my $head = 'HEAD';
3337 foreach my $x (@args) {
3338 last if $x eq '--';
3339 next unless ::verify_ref("$x^0");
3340 $head = $x;
3341 last;
3344 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3345 $gs ||= Git::SVN->_new;
3346 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3347 $gs->refname);
3348 push @cmd, '-r' unless $non_recursive;
3349 push @cmd, qw/--raw --name-status/ if $verbose;
3350 push @cmd, '--color' if log_use_color();
3351 return @cmd unless defined $r_max;
3352 if ($r_max == $r_min) {
3353 push @cmd, '--max-count=1';
3354 if (my $c = $gs->rev_db_get($r_max)) {
3355 push @cmd, $c;
3357 } else {
3358 my ($c_min, $c_max);
3359 $c_max = $gs->rev_db_get($r_max);
3360 $c_min = $gs->rev_db_get($r_min);
3361 if (defined $c_min && defined $c_max) {
3362 if ($r_max > $r_max) {
3363 push @cmd, "$c_min..$c_max";
3364 } else {
3365 push @cmd, "$c_max..$c_min";
3367 } elsif ($r_max > $r_min) {
3368 push @cmd, $c_max;
3369 } else {
3370 push @cmd, $c_min;
3373 return @cmd;
3376 # adapted from pager.c
3377 sub config_pager {
3378 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3379 if (!defined $pager) {
3380 $pager = 'less';
3381 } elsif (length $pager == 0 || $pager eq 'cat') {
3382 $pager = undef;
3386 sub run_pager {
3387 return unless -t *STDOUT;
3388 pipe my $rfd, my $wfd or return;
3389 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3390 if (!$pid) {
3391 open STDOUT, '>&', $wfd or
3392 ::fatal "Can't redirect to stdout: $!\n";
3393 return;
3395 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3396 $ENV{LESS} ||= 'FRSX';
3397 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3400 sub tz_to_s_offset {
3401 my ($tz) = @_;
3402 $tz =~ s/(\d\d)$//;
3403 return ($1 * 60) + ($tz * 3600);
3406 sub get_author_info {
3407 my ($dest, $author, $t, $tz) = @_;
3408 $author =~ s/(?:^\s*|\s*$)//g;
3409 $dest->{a_raw} = $author;
3410 my $au;
3411 if ($::_authors) {
3412 $au = $rusers{$author} || undef;
3414 if (!$au) {
3415 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3417 $dest->{t} = $t;
3418 $dest->{tz} = $tz;
3419 $dest->{a} = $au;
3420 # Date::Parse isn't in the standard Perl distro :(
3421 if ($tz =~ s/^\+//) {
3422 $t += tz_to_s_offset($tz);
3423 } elsif ($tz =~ s/^\-//) {
3424 $t -= tz_to_s_offset($tz);
3426 $dest->{t_utc} = $t;
3429 sub process_commit {
3430 my ($c, $r_min, $r_max, $defer) = @_;
3431 if (defined $r_min && defined $r_max) {
3432 if ($r_min == $c->{r} && $r_min == $r_max) {
3433 show_commit($c);
3434 return 0;
3436 return 1 if $r_min == $r_max;
3437 if ($r_min < $r_max) {
3438 # we need to reverse the print order
3439 return 0 if (defined $limit && --$limit < 0);
3440 push @$defer, $c;
3441 return 1;
3443 if ($r_min != $r_max) {
3444 return 1 if ($r_min < $c->{r});
3445 return 1 if ($r_max > $c->{r});
3448 return 0 if (defined $limit && --$limit < 0);
3449 show_commit($c);
3450 return 1;
3453 sub show_commit {
3454 my $c = shift;
3455 if ($oneline) {
3456 my $x = "\n";
3457 if (my $l = $c->{l}) {
3458 while ($l->[0] =~ /^\s*$/) { shift @$l }
3459 $x = $l->[0];
3461 $l_fmt ||= 'A' . length($c->{r});
3462 print 'r',pack($l_fmt, $c->{r}),' | ';
3463 print "$c->{c} | " if $show_commit;
3464 print $x;
3465 } else {
3466 show_commit_normal($c);
3470 sub show_commit_changed_paths {
3471 my ($c) = @_;
3472 return unless $c->{changed};
3473 print "Changed paths:\n", @{$c->{changed}};
3476 sub show_commit_normal {
3477 my ($c) = @_;
3478 print '-' x72, "\nr$c->{r} | ";
3479 print "$c->{c} | " if $show_commit;
3480 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3481 localtime($c->{t_utc})), ' | ';
3482 my $nr_line = 0;
3484 if (my $l = $c->{l}) {
3485 while ($l->[$#$l] eq "\n" && $#$l > 0
3486 && $l->[($#$l - 1)] eq "\n") {
3487 pop @$l;
3489 $nr_line = scalar @$l;
3490 if (!$nr_line) {
3491 print "1 line\n\n\n";
3492 } else {
3493 if ($nr_line == 1) {
3494 $nr_line = '1 line';
3495 } else {
3496 $nr_line .= ' lines';
3498 print $nr_line, "\n";
3499 show_commit_changed_paths($c);
3500 print "\n";
3501 print $_ foreach @$l;
3503 } else {
3504 print "1 line\n";
3505 show_commit_changed_paths($c);
3506 print "\n";
3509 foreach my $x (qw/raw stat diff/) {
3510 if ($c->{$x}) {
3511 print "\n";
3512 print $_ foreach @{$c->{$x}}
3517 sub cmd_show_log {
3518 my (@args) = @_;
3519 my ($r_min, $r_max);
3520 my $r_last = -1; # prevent dupes
3521 if (defined $TZ) {
3522 $ENV{TZ} = $TZ;
3523 } else {
3524 delete $ENV{TZ};
3526 if (defined $::_revision) {
3527 if ($::_revision =~ /^(\d+):(\d+)$/) {
3528 ($r_min, $r_max) = ($1, $2);
3529 } elsif ($::_revision =~ /^\d+$/) {
3530 $r_min = $r_max = $::_revision;
3531 } else {
3532 ::fatal "-r$::_revision is not supported, use ",
3533 "standard \'git log\' arguments instead\n";
3537 config_pager();
3538 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3539 my $log = command_output_pipe(@args);
3540 run_pager();
3541 my (@k, $c, $d, $stat);
3542 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3543 while (<$log>) {
3544 if (/^${esc_color}commit ($::sha1_short)/o) {
3545 my $cmt = $1;
3546 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3547 $r_last = $c->{r};
3548 process_commit($c, $r_min, $r_max, \@k) or
3549 goto out;
3551 $d = undef;
3552 $c = { c => $cmt };
3553 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3554 get_author_info($c, $1, $2, $3);
3555 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3556 # ignore
3557 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3558 push @{$c->{raw}}, $_;
3559 } elsif (/^${esc_color}[ACRMDT]\t/) {
3560 # we could add $SVN->{svn_path} here, but that requires
3561 # remote access at the moment (repo_path_split)...
3562 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3563 push @{$c->{changed}}, $_;
3564 } elsif (/^${esc_color}diff /o) {
3565 $d = 1;
3566 push @{$c->{diff}}, $_;
3567 } elsif ($d) {
3568 push @{$c->{diff}}, $_;
3569 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3570 $esc_color*[\+\-]*$esc_color$/x) {
3571 $stat = 1;
3572 push @{$c->{stat}}, $_;
3573 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3574 push @{$c->{stat}}, $_;
3575 $stat = undef;
3576 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3577 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3578 } elsif (s/^${esc_color} //o) {
3579 push @{$c->{l}}, $_;
3582 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3583 $r_last = $c->{r};
3584 process_commit($c, $r_min, $r_max, \@k);
3586 if (@k) {
3587 my $swap = $r_max;
3588 $r_max = $r_min;
3589 $r_min = $swap;
3590 process_commit($_, $r_min, $r_max) foreach reverse @k;
3592 out:
3593 close $log;
3594 print '-' x72,"\n" unless $incremental || $oneline;
3597 package Git::SVN::Migration;
3598 # these version numbers do NOT correspond to actual version numbers
3599 # of git nor git-svn. They are just relative.
3601 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3603 # v1 layout: .git/$id/info/url, refs/remotes/$id
3605 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3607 # v3 layout: .git/svn/$id, refs/remotes/$id
3608 # - info/url may remain for backwards compatibility
3609 # - this is what we migrate up to this layout automatically,
3610 # - this will be used by git svn init on single branches
3611 # v3.1 layout (auto migrated):
3612 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3613 # for backwards compatibility
3615 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3616 # - this is only created for newly multi-init-ed
3617 # repositories. Similar in spirit to the
3618 # --use-separate-remotes option in git-clone (now default)
3619 # - we do not automatically migrate to this (following
3620 # the example set by core git)
3621 use strict;
3622 use warnings;
3623 use Carp qw/croak/;
3624 use File::Path qw/mkpath/;
3625 use File::Basename qw/dirname basename/;
3626 use vars qw/$_minimize/;
3628 sub migrate_from_v0 {
3629 my $git_dir = $ENV{GIT_DIR};
3630 return undef unless -d $git_dir;
3631 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3632 my $migrated = 0;
3633 while (<$fh>) {
3634 chomp;
3635 my ($id, $orig_ref) = ($_, $_);
3636 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3637 next unless -f "$git_dir/$id/info/url";
3638 my $new_ref = "refs/remotes/$id";
3639 if (::verify_ref("$new_ref^0")) {
3640 print STDERR "W: $orig_ref is probably an old ",
3641 "branch used by an ancient version of ",
3642 "git-svn.\n",
3643 "However, $new_ref also exists.\n",
3644 "We will not be able ",
3645 "to use this branch until this ",
3646 "ambiguity is resolved.\n";
3647 next;
3649 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3650 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3651 command_noisy('update-ref', $new_ref, $orig_ref);
3652 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3653 $migrated++;
3655 command_close_pipe($fh, $ctx);
3656 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3657 $migrated;
3660 sub migrate_from_v1 {
3661 my $git_dir = $ENV{GIT_DIR};
3662 my $migrated = 0;
3663 return $migrated unless -d $git_dir;
3664 my $svn_dir = "$git_dir/svn";
3666 # just in case somebody used 'svn' as their $id at some point...
3667 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3669 print STDERR "Migrating from a git-svn v1 layout...\n";
3670 mkpath([$svn_dir]);
3671 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3672 "$svn_dir\n\t(required for this version ",
3673 "($::VERSION) of git-svn) does not. exist\n";
3674 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3675 while (<$fh>) {
3676 my $x = $_;
3677 next unless $x =~ s#^refs/remotes/##;
3678 chomp $x;
3679 next unless -f "$git_dir/$x/info/url";
3680 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3681 next unless $u;
3682 my $dn = dirname("$git_dir/svn/$x");
3683 mkpath([$dn]) unless -d $dn;
3684 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3685 mkpath(["$git_dir/svn/svn"]);
3686 print STDERR " - $git_dir/$x/info => ",
3687 "$git_dir/svn/$x/info\n";
3688 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3689 croak "$!: $x";
3690 # don't worry too much about these, they probably
3691 # don't exist with repos this old (save for index,
3692 # and we can easily regenerate that)
3693 foreach my $f (qw/unhandled.log index .rev_db/) {
3694 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3696 } else {
3697 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3698 rename "$git_dir/$x", "$git_dir/svn/$x" or
3699 croak "$!: $x";
3701 $migrated++;
3703 command_close_pipe($fh, $ctx);
3704 print STDERR "Done migrating from a git-svn v1 layout\n";
3705 $migrated;
3708 sub read_old_urls {
3709 my ($l_map, $pfx, $path) = @_;
3710 my @dir;
3711 foreach (<$path/*>) {
3712 if (-r "$_/info/url") {
3713 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3714 my $ref_id = $pfx . basename $_;
3715 my $url = ::file_to_s("$_/info/url");
3716 $l_map->{$ref_id} = $url;
3717 } elsif (-d $_) {
3718 push @dir, $_;
3721 foreach (@dir) {
3722 my $x = $_;
3723 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3724 read_old_urls($l_map, $x, $_);
3728 sub migrate_from_v2 {
3729 my @cfg = command(qw/config -l/);
3730 return if grep /^svn-remote\..+\.url=/, @cfg;
3731 my %l_map;
3732 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3733 my $migrated = 0;
3735 foreach my $ref_id (sort keys %l_map) {
3736 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3737 if ($@) {
3738 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3740 $migrated++;
3742 $migrated;
3745 sub minimize_connections {
3746 my $r = Git::SVN::read_all_remotes();
3747 my $new_urls = {};
3748 my $root_repos = {};
3749 foreach my $repo_id (keys %$r) {
3750 my $url = $r->{$repo_id}->{url} or next;
3751 my $fetch = $r->{$repo_id}->{fetch} or next;
3752 my $ra = Git::SVN::Ra->new($url);
3754 # skip existing cases where we already connect to the root
3755 if (($ra->{url} eq $ra->{repos_root}) ||
3756 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3757 $repo_id)) {
3758 $root_repos->{$ra->{url}} = $repo_id;
3759 next;
3762 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3763 my $root_path = $ra->{url};
3764 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3765 foreach my $path (keys %$fetch) {
3766 my $ref_id = $fetch->{$path};
3767 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3769 # make sure we can read when connecting to
3770 # a higher level of a repository
3771 my ($last_rev, undef) = $gs->last_rev_commit;
3772 if (!defined $last_rev) {
3773 $last_rev = eval {
3774 $root_ra->get_latest_revnum;
3776 next if $@;
3778 my $new = $root_path;
3779 $new .= length $path ? "/$path" : '';
3780 eval {
3781 $root_ra->get_log([$new], $last_rev, $last_rev,
3782 0, 0, 1, sub { });
3784 next if $@;
3785 $new_urls->{$ra->{repos_root}}->{$new} =
3786 { ref_id => $ref_id,
3787 old_repo_id => $repo_id,
3788 old_path => $path };
3792 my @emptied;
3793 foreach my $url (keys %$new_urls) {
3794 # see if we can re-use an existing [svn-remote "repo_id"]
3795 # instead of creating a(n ugly) new section:
3796 my $repo_id = $root_repos->{$url} ||
3797 Git::SVN::sanitize_remote_name($url);
3799 my $fetch = $new_urls->{$url};
3800 foreach my $path (keys %$fetch) {
3801 my $x = $fetch->{$path};
3802 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3803 my $pfx = "svn-remote.$x->{old_repo_id}";
3805 my $old_fetch = quotemeta("$x->{old_path}:".
3806 "refs/remotes/$x->{ref_id}");
3807 command_noisy(qw/config --unset/,
3808 "$pfx.fetch", '^'. $old_fetch . '$');
3809 delete $r->{$x->{old_repo_id}}->
3810 {fetch}->{$x->{old_path}};
3811 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3812 command_noisy(qw/config --unset/,
3813 "$pfx.url");
3814 push @emptied, $x->{old_repo_id}
3818 if (@emptied) {
3819 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3820 "$ENV{GIT_DIR}/config";
3821 print STDERR <<EOF;
3822 The following [svn-remote] sections in your config file ($file) are empty
3823 and can be safely removed:
3825 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3829 sub migration_check {
3830 migrate_from_v0();
3831 migrate_from_v1();
3832 migrate_from_v2();
3833 minimize_connections() if $_minimize;
3836 package Git::IndexInfo;
3837 use strict;
3838 use warnings;
3839 use Git qw/command_input_pipe command_close_pipe/;
3841 sub new {
3842 my ($class) = @_;
3843 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3844 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3847 sub remove {
3848 my ($self, $path) = @_;
3849 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3850 return ++$self->{nr};
3852 undef;
3855 sub update {
3856 my ($self, $mode, $hash, $path) = @_;
3857 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3858 return ++$self->{nr};
3860 undef;
3863 sub DESTROY {
3864 my ($self) = @_;
3865 command_close_pipe($self->{gui}, $self->{ctx});
3868 package Git::SVN::GlobSpec;
3869 use strict;
3870 use warnings;
3872 sub new {
3873 my ($class, $glob) = @_;
3874 my $re = $glob;
3875 $re =~ s!/+$!!g; # no need for trailing slashes
3876 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3877 my ($left, $right) = ($1, $2);
3878 if ($nr > 1) {
3879 die "Only one '*' wildcard expansion ",
3880 "is supported (got $nr): '$glob'\n";
3881 } elsif ($nr == 0) {
3882 die "One '*' is needed for glob: '$glob'\n";
3884 $re = quotemeta($left) . $re . quotemeta($right);
3885 if (length $left && !($left =~ s!/+$!!g)) {
3886 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3888 if (length $right && !($right =~ s!^/+!!g)) {
3889 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3891 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3892 bless { left => $left, right => $right, left_regex => $left_re,
3893 regex => qr/$re/, glob => $glob }, $class;
3896 sub full_path {
3897 my ($self, $path) = @_;
3898 return (length $self->{left} ? "$self->{left}/" : '') .
3899 $path . (length $self->{right} ? "/$self->{right}" : '');
3902 __END__
3904 Data structures:
3907 $remotes = { # returned by read_all_remotes()
3908 'svn' => {
3909 # svn-remote.svn.url=https://svn.musicpd.org
3910 url => 'https://svn.musicpd.org',
3911 # svn-remote.svn.fetch=mpd/trunk:trunk
3912 fetch => {
3913 'mpd/trunk' => 'trunk',
3915 # svn-remote.svn.tags=mpd/tags/*:tags/*
3916 tags => {
3917 path => {
3918 left => 'mpd/tags',
3919 right => '',
3920 regex => qr!mpd/tags/([^/]+)$!,
3921 glob => 'tags/*',
3923 ref => {
3924 left => 'tags',
3925 right => '',
3926 regex => qr!tags/([^/]+)$!,
3927 glob => 'tags/*',
3933 $log_entry hashref as returned by libsvn_log_entry()
3935 log => 'whitespace-formatted log entry
3936 ', # trailing newline is preserved
3937 revision => '8', # integer
3938 date => '2004-02-24T17:01:44.108345Z', # commit date
3939 author => 'committer name'
3943 # this is generated by generate_diff();
3944 @mods = array of diff-index line hashes, each element represents one line
3945 of diff-index output
3947 diff-index line ($m hash)
3949 mode_a => first column of diff-index output, no leading ':',
3950 mode_b => second column of diff-index output,
3951 sha1_b => sha1sum of the final blob,
3952 chg => change type [MCRADT],
3953 file_a => original file name of a file (iff chg is 'C' or 'R')
3954 file_b => new/current file name of a file (any chg)
3958 # retval of read_url_paths{,_all}();
3959 $l_map = {
3960 # repository root url
3961 'https://svn.musicpd.org' => {
3962 # repository path # GIT_SVN_ID
3963 'mpd/trunk' => 'trunk',
3964 'mpd/tags/0.11.5' => 'tags/0.11.5',
3968 Notes:
3969 I don't trust the each() function on unless I created %hash myself
3970 because the internal iterator may not have started at base.