Replace "runstatus" with "status" in the tests
[git/mingw/4msysgit/wingit-dll.git] / git-svn.perl
blob43e1591cef4e69a1d06463ad996190b89df6cfe6
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 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use IO::File qw//;
39 use File::Basename qw/dirname basename/;
40 use File::Path qw/mkpath/;
41 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
42 use IPC::Open3;
43 use Git;
45 BEGIN {
46 # import functions from Git into our packages, en masse
47 no strict 'refs';
48 foreach (qw/command command_oneline command_noisy command_output_pipe
49 command_input_pipe command_close_pipe/) {
50 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
51 Git::SVN::Migration Git::SVN::Log Git::SVN
52 Git::SVN::Util),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose);
69 $Git::SVN::_follow_parent = 1;
70 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
71 'config-dir=s' => \$Git::SVN::Ra::config_dir,
72 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
73 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
74 'authors-file|A=s' => \$_authors,
75 'repack:i' => \$Git::SVN::_repack,
76 'noMetadata' => \$Git::SVN::_no_metadata,
77 'useSvmProps' => \$Git::SVN::_use_svm_props,
78 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
79 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
80 'no-checkout' => \$_no_checkout,
81 'quiet|q' => \$_q,
82 'repack-flags|repack-args|repack-opts=s' =>
83 \$Git::SVN::_repack_flags,
84 %remote_opts );
86 my ($_trunk, $_tags, $_branches, $_stdlayout);
87 my %icv;
88 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
89 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
90 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
91 'stdlayout|s' => \$_stdlayout,
92 'minimize-url|m' => \$Git::SVN::_minimize_url,
93 'no-metadata' => sub { $icv{noMetadata} = 1 },
94 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
95 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
96 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
97 %remote_opts );
98 my %cmt_opts = ( 'edit|e' => \$_edit,
99 'rmdir' => \$SVN::Git::Editor::_rmdir,
100 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
101 'l=i' => \$SVN::Git::Editor::_rename_limit,
102 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
105 my %cmd = (
106 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
107 { 'revision|r=s' => \$_revision,
108 'fetch-all|all' => \$_fetch_all,
109 %fc_opts } ],
110 clone => [ \&cmd_clone, "Initialize and fetch revisions",
111 { 'revision|r=s' => \$_revision,
112 %fc_opts, %init_opts } ],
113 init => [ \&cmd_init, "Initialize a repo for tracking" .
114 " (requires URL argument)",
115 \%init_opts ],
116 'multi-init' => [ \&cmd_multi_init,
117 "Deprecated alias for ".
118 "'$0 init -T<trunk> -b<branches> -t<tags>'",
119 \%init_opts ],
120 dcommit => [ \&cmd_dcommit,
121 'Commit several diffs to merge with upstream',
122 { 'merge|m|M' => \$_merge,
123 'strategy|s=s' => \$_strategy,
124 'verbose|v' => \$_verbose,
125 'dry-run|n' => \$_dry_run,
126 'fetch-all|all' => \$_fetch_all,
127 'no-rebase' => \$_no_rebase,
128 %cmt_opts, %fc_opts } ],
129 'set-tree' => [ \&cmd_set_tree,
130 "Set an SVN repository to a git tree-ish",
131 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
132 'create-ignore' => [ \&cmd_create_ignore,
133 'Create a .gitignore per svn:ignore',
134 { 'revision|r=i' => \$_revision
135 } ],
136 'propget' => [ \&cmd_propget,
137 'Print the value of a property on a file or directory',
138 { 'revision|r=i' => \$_revision } ],
139 'proplist' => [ \&cmd_proplist,
140 'List all properties of a file or directory',
141 { 'revision|r=i' => \$_revision } ],
142 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
143 { 'revision|r=i' => \$_revision
144 } ],
145 'multi-fetch' => [ \&cmd_multi_fetch,
146 "Deprecated alias for $0 fetch --all",
147 { 'revision|r=s' => \$_revision, %fc_opts } ],
148 'migrate' => [ sub { },
149 # no-op, we automatically run this anyways,
150 'Migrate configuration/metadata/layout from
151 previous versions of git-svn',
152 { 'minimize' => \$Git::SVN::Migration::_minimize,
153 %remote_opts } ],
154 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
155 { 'limit=i' => \$Git::SVN::Log::limit,
156 'revision|r=s' => \$_revision,
157 'verbose|v' => \$Git::SVN::Log::verbose,
158 'incremental' => \$Git::SVN::Log::incremental,
159 'oneline' => \$Git::SVN::Log::oneline,
160 'show-commit' => \$Git::SVN::Log::show_commit,
161 'non-recursive' => \$Git::SVN::Log::non_recursive,
162 'authors-file|A=s' => \$_authors,
163 'color' => \$Git::SVN::Log::color,
164 'pager=s' => \$Git::SVN::Log::pager
165 } ],
166 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
167 {} ],
168 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
169 { 'merge|m|M' => \$_merge,
170 'verbose|v' => \$_verbose,
171 'strategy|s=s' => \$_strategy,
172 'local|l' => \$_local,
173 'fetch-all|all' => \$_fetch_all,
174 %fc_opts } ],
175 'commit-diff' => [ \&cmd_commit_diff,
176 'Commit a diff between two trees',
177 { 'message|m=s' => \$_message,
178 'file|F=s' => \$_file,
179 'revision|r=s' => \$_revision,
180 %cmt_opts } ],
181 'info' => [ \&cmd_info,
182 "Show info about the latest SVN revision
183 on the current branch",
184 { 'url' => \$_url, } ],
187 my $cmd;
188 for (my $i = 0; $i < @ARGV; $i++) {
189 if (defined $cmd{$ARGV[$i]}) {
190 $cmd = $ARGV[$i];
191 splice @ARGV, $i, 1;
192 last;
196 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
198 read_repo_config(\%opts);
199 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
200 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
201 'minimize-connections' => \$Git::SVN::Migration::_minimize,
202 'id|i=s' => \$Git::SVN::default_ref_id,
203 'svn-remote|remote|R=s' => sub {
204 $Git::SVN::no_reuse_existing = 1;
205 $Git::SVN::default_repo_id = $_[1] });
206 exit 1 if (!$rv && $cmd && $cmd ne 'log');
208 usage(0) if $_help;
209 version() if $_version;
210 usage(1) unless defined $cmd;
211 load_authors() if $_authors;
213 # make sure we're always running
214 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
215 unless (-d $ENV{GIT_DIR}) {
216 if ($git_dir_user_set) {
217 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
218 "but it is not a directory\n";
220 my $git_dir = delete $ENV{GIT_DIR};
221 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
222 unless (length $cdup) {
223 die "Already at toplevel, but $git_dir ",
224 "not found '$cdup'\n";
226 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
227 unless (-d $git_dir) {
228 die "$git_dir still not found after going to ",
229 "'$cdup'\n";
231 $ENV{GIT_DIR} = $git_dir;
234 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
235 Git::SVN::Migration::migration_check();
237 Git::SVN::init_vars();
238 eval {
239 Git::SVN::verify_remotes_sanity();
240 $cmd{$cmd}->[0]->(@ARGV);
242 fatal $@ if $@;
243 post_fetch_checkout();
244 exit 0;
246 ####################### primary functions ######################
247 sub usage {
248 my $exit = shift || 0;
249 my $fd = $exit ? \*STDERR : \*STDOUT;
250 print $fd <<"";
251 git-svn - bidirectional operations between a single Subversion tree and git
252 Usage: $0 <command> [options] [arguments]\n
254 print $fd "Available commands:\n" unless $cmd;
256 foreach (sort keys %cmd) {
257 next if $cmd && $cmd ne $_;
258 next if /^multi-/; # don't show deprecated commands
259 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
260 foreach (sort keys %{$cmd{$_}->[2]}) {
261 # mixed-case options are for .git/config only
262 next if /[A-Z]/ && /^[a-z]+$/i;
263 # prints out arguments as they should be passed:
264 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
265 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
266 "--$_" : "-$_" }
267 split /\|/,$_)," $x\n";
270 print $fd <<"";
271 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
272 arbitrary identifier if you're tracking multiple SVN branches/repositories in
273 one git repository and want to keep them separate. See git-svn(1) for more
274 information.
276 exit $exit;
279 sub version {
280 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
281 exit 0;
284 sub do_git_init_db {
285 unless (-d $ENV{GIT_DIR}) {
286 my @init_db = ('init');
287 push @init_db, "--template=$_template" if defined $_template;
288 if (defined $_shared) {
289 if ($_shared =~ /[a-z]/) {
290 push @init_db, "--shared=$_shared";
291 } else {
292 push @init_db, "--shared";
295 command_noisy(@init_db);
297 my $set;
298 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
299 foreach my $i (keys %icv) {
300 die "'$set' and '$i' cannot both be set\n" if $set;
301 next unless defined $icv{$i};
302 command_noisy('config', "$pfx.$i", $icv{$i});
303 $set = $i;
307 sub init_subdir {
308 my $repo_path = shift or return;
309 mkpath([$repo_path]) unless -d $repo_path;
310 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
311 $ENV{GIT_DIR} = '.git';
314 sub cmd_clone {
315 my ($url, $path) = @_;
316 if (!defined $path &&
317 (defined $_trunk || defined $_branches || defined $_tags ||
318 defined $_stdlayout) &&
319 $url !~ m#^[a-z\+]+://#) {
320 $path = $url;
322 $path = basename($url) if !defined $path || !length $path;
323 cmd_init($url, $path);
324 Git::SVN::fetch_all($Git::SVN::default_repo_id);
327 sub cmd_init {
328 if (defined $_stdlayout) {
329 $_trunk = 'trunk' if (!defined $_trunk);
330 $_tags = 'tags' if (!defined $_tags);
331 $_branches = 'branches' if (!defined $_branches);
333 if (defined $_trunk || defined $_branches || defined $_tags) {
334 return cmd_multi_init(@_);
336 my $url = shift or die "SVN repository location required ",
337 "as a command-line argument\n";
338 init_subdir(@_);
339 do_git_init_db();
341 Git::SVN->init($url);
344 sub cmd_fetch {
345 if (grep /^\d+=./, @_) {
346 die "'<rev>=<commit>' fetch arguments are ",
347 "no longer supported.\n";
349 my ($remote) = @_;
350 if (@_ > 1) {
351 die "Usage: $0 fetch [--all] [svn-remote]\n";
353 $remote ||= $Git::SVN::default_repo_id;
354 if ($_fetch_all) {
355 cmd_multi_fetch();
356 } else {
357 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
361 sub cmd_set_tree {
362 my (@commits) = @_;
363 if ($_stdin || !@commits) {
364 print "Reading from stdin...\n";
365 @commits = ();
366 while (<STDIN>) {
367 if (/\b($sha1_short)\b/o) {
368 unshift @commits, $1;
372 my @revs;
373 foreach my $c (@commits) {
374 my @tmp = command('rev-parse',$c);
375 if (scalar @tmp == 1) {
376 push @revs, $tmp[0];
377 } elsif (scalar @tmp > 1) {
378 push @revs, reverse(command('rev-list',@tmp));
379 } else {
380 fatal "Failed to rev-parse $c";
383 my $gs = Git::SVN->new;
384 my ($r_last, $cmt_last) = $gs->last_rev_commit;
385 $gs->fetch;
386 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
387 fatal "There are new revisions that were fetched ",
388 "and need to be merged (or acknowledged) ",
389 "before committing.\nlast rev: $r_last\n",
390 " current: $gs->{last_rev}";
392 $gs->set_tree($_) foreach @revs;
393 print "Done committing ",scalar @revs," revisions to SVN\n";
396 sub cmd_dcommit {
397 my $head = shift;
398 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
399 'Cannot dcommit with a dirty index. Commit your changes first, '
400 . "or stash them with `git stash'.\n";
401 $head ||= 'HEAD';
402 my @refs;
403 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
404 print "Committing to $url ...\n";
405 unless ($gs) {
406 die "Unable to determine upstream SVN information from ",
407 "$head history\n";
409 my $last_rev;
410 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
411 if ($_no_rebase && scalar(@$linear_refs) > 1) {
412 warn "Attempting to commit more than one change while ",
413 "--no-rebase is enabled.\n",
414 "If these changes depend on each other, re-running ",
415 "without --no-rebase will be required."
417 while (1) {
418 my $d = shift @$linear_refs or last;
419 unless (defined $last_rev) {
420 (undef, $last_rev, undef) = cmt_metadata("$d~1");
421 unless (defined $last_rev) {
422 fatal "Unable to extract revision information ",
423 "from commit $d~1";
426 if ($_dry_run) {
427 print "diff-tree $d~1 $d\n";
428 } else {
429 my $cmt_rev;
430 my %ed_opts = ( r => $last_rev,
431 log => get_commit_entry($d)->{log},
432 ra => Git::SVN::Ra->new($gs->full_url),
433 config => SVN::Core::config_get_config(
434 $Git::SVN::Ra::config_dir
436 tree_a => "$d~1",
437 tree_b => $d,
438 editor_cb => sub {
439 print "Committed r$_[0]\n";
440 $cmt_rev = $_[0];
442 svn_path => '');
443 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
444 print "No changes\n$d~1 == $d\n";
445 } elsif ($parents->{$d} && @{$parents->{$d}}) {
446 $gs->{inject_parents_dcommit}->{$cmt_rev} =
447 $parents->{$d};
449 $_fetch_all ? $gs->fetch_all : $gs->fetch;
450 next if $_no_rebase;
452 # we always want to rebase against the current HEAD,
453 # not any head that was passed to us
454 my @diff = command('diff-tree', $d,
455 $gs->refname, '--');
456 my @finish;
457 if (@diff) {
458 @finish = rebase_cmd();
459 print STDERR "W: $d and ", $gs->refname,
460 " differ, using @finish:\n",
461 join("\n", @diff), "\n";
462 } else {
463 print "No changes between current HEAD and ",
464 $gs->refname,
465 "\nResetting to the latest ",
466 $gs->refname, "\n";
467 @finish = qw/reset --mixed/;
469 command_noisy(@finish, $gs->refname);
470 if (@diff) {
471 @refs = ();
472 my ($url_, $rev_, $uuid_, $gs_) =
473 working_head_info($head, \@refs);
474 my ($linear_refs_, $parents_) =
475 linearize_history($gs_, \@refs);
476 if (scalar(@$linear_refs) !=
477 scalar(@$linear_refs_)) {
478 fatal "# of revisions changed ",
479 "\nbefore:\n",
480 join("\n", @$linear_refs),
481 "\n\nafter:\n",
482 join("\n", @$linear_refs_), "\n",
483 'If you are attempting to commit ',
484 "merges, try running:\n\t",
485 'git rebase --interactive',
486 '--preserve-merges ',
487 $gs->refname,
488 "\nBefore dcommitting";
490 if ($url_ ne $url) {
491 fatal "URL mismatch after rebase: ",
492 "$url_ != $url";
494 if ($uuid_ ne $uuid) {
495 fatal "uuid mismatch after rebase: ",
496 "$uuid_ != $uuid";
498 # remap parents
499 my (%p, @l, $i);
500 for ($i = 0; $i < scalar @$linear_refs; $i++) {
501 my $new = $linear_refs_->[$i] or next;
502 $p{$new} =
503 $parents->{$linear_refs->[$i]};
504 push @l, $new;
506 $parents = \%p;
507 $linear_refs = \@l;
509 $last_rev = $cmt_rev;
514 sub cmd_find_rev {
515 my $revision_or_hash = shift;
516 my $result;
517 if ($revision_or_hash =~ /^r\d+$/) {
518 my $head = shift;
519 $head ||= 'HEAD';
520 my @refs;
521 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
522 unless ($gs) {
523 die "Unable to determine upstream SVN information from ",
524 "$head history\n";
526 my $desired_revision = substr($revision_or_hash, 1);
527 $result = $gs->rev_db_get($desired_revision);
528 } else {
529 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
530 $result = $rev;
532 print "$result\n" if $result;
535 sub cmd_rebase {
536 command_noisy(qw/update-index --refresh/);
537 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
538 unless ($gs) {
539 die "Unable to determine upstream SVN information from ",
540 "working tree history\n";
542 if (command(qw/diff-index HEAD --/)) {
543 print STDERR "Cannot rebase with uncommited changes:\n";
544 command_noisy('status');
545 exit 1;
547 unless ($_local) {
548 $_fetch_all ? $gs->fetch_all : $gs->fetch;
550 command_noisy(rebase_cmd(), $gs->refname);
553 sub cmd_show_ignore {
554 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
555 $gs ||= Git::SVN->new;
556 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
557 $gs->prop_walk($gs->{path}, $r, sub {
558 my ($gs, $path, $props) = @_;
559 print STDOUT "\n# $path\n";
560 my $s = $props->{'svn:ignore'} or return;
561 $s =~ s/[\r\n]+/\n/g;
562 chomp $s;
563 $s =~ s#^#$path#gm;
564 print STDOUT "$s\n";
568 sub cmd_create_ignore {
569 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
570 $gs ||= Git::SVN->new;
571 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
572 $gs->prop_walk($gs->{path}, $r, sub {
573 my ($gs, $path, $props) = @_;
574 # $path is of the form /path/to/dir/
575 my $ignore = '.' . $path . '.gitignore';
576 my $s = $props->{'svn:ignore'} or return;
577 open(GITIGNORE, '>', $ignore)
578 or fatal("Failed to open `$ignore' for writing: $!");
579 $s =~ s/[\r\n]+/\n/g;
580 chomp $s;
581 # Prefix all patterns so that the ignore doesn't apply
582 # to sub-directories.
583 $s =~ s#^#/#gm;
584 print GITIGNORE "$s\n";
585 close(GITIGNORE)
586 or fatal("Failed to close `$ignore': $!");
587 command_noisy('add', $ignore);
591 sub canonicalize_path {
592 my ($path) = @_;
593 my $dot_slash_added = 0;
594 if (substr($path, 0, 1) ne "/") {
595 $path = "./" . $path;
596 $dot_slash_added = 1;
598 # File::Spec->canonpath doesn't collapse x/../y into y (for a
599 # good reason), so let's do this manually.
600 $path =~ s#/+#/#g;
601 $path =~ s#/\.(?:/|$)#/#g;
602 $path =~ s#/[^/]+/\.\.##g;
603 $path =~ s#/$##g;
604 $path =~ s#^\./## if $dot_slash_added;
605 return $path;
608 # get_svnprops(PATH)
609 # ------------------
610 # Helper for cmd_propget and cmd_proplist below.
611 sub get_svnprops {
612 my $path = shift;
613 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
614 $gs ||= Git::SVN->new;
616 # prefix THE PATH by the sub-directory from which the user
617 # invoked us.
618 $path = $cmd_dir_prefix . $path;
619 fatal("No such file or directory: $path") unless -e $path;
620 my $is_dir = -d $path ? 1 : 0;
621 $path = $gs->{path} . '/' . $path;
623 # canonicalize the path (otherwise libsvn will abort or fail to
624 # find the file)
625 $path = canonicalize_path($path);
627 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
628 my $props;
629 if ($is_dir) {
630 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
632 else {
633 (undef, $props) = $gs->ra->get_file($path, $r, undef);
635 return $props;
638 # cmd_propget (PROP, PATH)
639 # ------------------------
640 # Print the SVN property PROP for PATH.
641 sub cmd_propget {
642 my ($prop, $path) = @_;
643 $path = '.' if not defined $path;
644 usage(1) if not defined $prop;
645 my $props = get_svnprops($path);
646 if (not defined $props->{$prop}) {
647 fatal("`$path' does not have a `$prop' SVN property.");
649 print $props->{$prop} . "\n";
652 # cmd_proplist (PATH)
653 # -------------------
654 # Print the list of SVN properties for PATH.
655 sub cmd_proplist {
656 my $path = shift;
657 $path = '.' if not defined $path;
658 my $props = get_svnprops($path);
659 print "Properties on '$path':\n";
660 foreach (sort keys %{$props}) {
661 print " $_\n";
665 sub cmd_multi_init {
666 my $url = shift;
667 unless (defined $_trunk || defined $_branches || defined $_tags) {
668 usage(1);
671 # there are currently some bugs that prevent multi-init/multi-fetch
672 # setups from working well without this.
673 $Git::SVN::_minimize_url = 1;
675 $_prefix = '' unless defined $_prefix;
676 if (defined $url) {
677 $url =~ s#/+$##;
678 init_subdir(@_);
680 do_git_init_db();
681 if (defined $_trunk) {
682 my $trunk_ref = $_prefix . 'trunk';
683 # try both old-style and new-style lookups:
684 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
685 unless ($gs_trunk) {
686 my ($trunk_url, $trunk_path) =
687 complete_svn_url($url, $_trunk);
688 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
689 undef, $trunk_ref);
692 return unless defined $_branches || defined $_tags;
693 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
694 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
695 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
698 sub cmd_multi_fetch {
699 my $remotes = Git::SVN::read_all_remotes();
700 foreach my $repo_id (sort keys %$remotes) {
701 if ($remotes->{$repo_id}->{url}) {
702 Git::SVN::fetch_all($repo_id, $remotes);
707 # this command is special because it requires no metadata
708 sub cmd_commit_diff {
709 my ($ta, $tb, $url) = @_;
710 my $usage = "Usage: $0 commit-diff -r<revision> ".
711 "<tree-ish> <tree-ish> [<URL>]";
712 fatal($usage) if (!defined $ta || !defined $tb);
713 my $svn_path;
714 if (!defined $url) {
715 my $gs = eval { Git::SVN->new };
716 if (!$gs) {
717 fatal("Needed URL or usable git-svn --id in ",
718 "the command-line\n", $usage);
720 $url = $gs->{url};
721 $svn_path = $gs->{path};
723 unless (defined $_revision) {
724 fatal("-r|--revision is a required argument\n", $usage);
726 if (defined $_message && defined $_file) {
727 fatal("Both --message/-m and --file/-F specified ",
728 "for the commit message.\n",
729 "I have no idea what you mean");
731 if (defined $_file) {
732 $_message = file_to_s($_file);
733 } else {
734 $_message ||= get_commit_entry($tb)->{log};
736 my $ra ||= Git::SVN::Ra->new($url);
737 $svn_path ||= $ra->{svn_path};
738 my $r = $_revision;
739 if ($r eq 'HEAD') {
740 $r = $ra->get_latest_revnum;
741 } elsif ($r !~ /^\d+$/) {
742 die "revision argument: $r not understood by git-svn\n";
744 my %ed_opts = ( r => $r,
745 log => $_message,
746 ra => $ra,
747 tree_a => $ta,
748 tree_b => $tb,
749 editor_cb => sub { print "Committed r$_[0]\n" },
750 svn_path => $svn_path );
751 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
752 print "No changes\n$ta == $tb\n";
756 sub cmd_info {
757 my $path = canonicalize_path(shift or ".");
758 unless (scalar(@_) == 0) {
759 die "Too many arguments specified\n";
762 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
764 if (!$file_type && !$diff_status) {
765 print STDERR "$path: (Not a versioned resource)\n\n";
766 return;
769 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
770 unless ($gs) {
771 die "Unable to determine upstream SVN information from ",
772 "working tree history\n";
774 my $full_url = $url . ($path eq "." ? "" : "/$path");
776 if ($_url) {
777 print $full_url, "\n";
778 return;
781 my $result = "Path: $path\n";
782 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
783 $result .= "URL: " . $full_url . "\n";
785 eval {
786 my $repos_root = $gs->repos_root;
787 Git::SVN::remove_username($repos_root);
788 $result .= "Repository Root: $repos_root\n";
790 if ($@) {
791 $result .= "Repository Root: (offline)\n";
793 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
794 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
796 $result .= "Node Kind: " .
797 ($file_type eq "dir" ? "directory" : "file") . "\n";
799 my $schedule = $diff_status eq "A"
800 ? "add"
801 : ($diff_status eq "D" ? "delete" : "normal");
802 $result .= "Schedule: $schedule\n";
804 if ($diff_status eq "A") {
805 print $result, "\n";
806 return;
809 my ($lc_author, $lc_rev, $lc_date_utc);
810 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
811 my $log = command_output_pipe(@args);
812 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
813 while (<$log>) {
814 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
815 $lc_author = $1;
816 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
817 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
818 (undef, $lc_rev, undef) = ::extract_metadata($1);
821 close $log;
823 Git::SVN::Log::set_local_timezone();
825 $result .= "Last Changed Author: $lc_author\n";
826 $result .= "Last Changed Rev: $lc_rev\n";
827 $result .= "Last Changed Date: " .
828 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
830 if ($file_type ne "dir") {
831 my $text_last_updated_date =
832 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
833 $result .=
834 "Text Last Updated: " .
835 Git::SVN::Log::format_svn_date($text_last_updated_date) .
836 "\n";
837 my $checksum;
838 if ($diff_status eq "D") {
839 my ($fh, $ctx) =
840 command_output_pipe(qw(cat-file blob), "HEAD:$path");
841 if ($file_type eq "link") {
842 my $file_name = <$fh>;
843 $checksum = Git::SVN::Util::md5sum("link $file_name");
844 } else {
845 $checksum = Git::SVN::Util::md5sum($fh);
847 command_close_pipe($fh, $ctx);
848 } elsif ($file_type eq "link") {
849 my $file_name =
850 command(qw(cat-file blob), "HEAD:$path");
851 $checksum =
852 Git::SVN::Util::md5sum("link " . $file_name);
853 } else {
854 open FILE, "<", $path or die $!;
855 $checksum = Git::SVN::Util::md5sum(\*FILE);
856 close FILE or die $!;
858 $result .= "Checksum: " . $checksum . "\n";
861 print $result, "\n";
864 ########################### utility functions #########################
866 sub rebase_cmd {
867 my @cmd = qw/rebase/;
868 push @cmd, '-v' if $_verbose;
869 push @cmd, qw/--merge/ if $_merge;
870 push @cmd, "--strategy=$_strategy" if $_strategy;
871 @cmd;
874 sub post_fetch_checkout {
875 return if $_no_checkout;
876 my $gs = $Git::SVN::_head or return;
877 return if verify_ref('refs/heads/master^0');
879 my $valid_head = verify_ref('HEAD^0');
880 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
881 return if ($valid_head || !verify_ref('HEAD^0'));
883 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
884 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
885 return if -f $index;
887 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
888 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
889 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
890 print STDERR "Checked out HEAD:\n ",
891 $gs->full_url, " r", $gs->last_rev, "\n";
894 sub complete_svn_url {
895 my ($url, $path) = @_;
896 $path =~ s#/+$##;
897 if ($path !~ m#^[a-z\+]+://#) {
898 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
899 fatal("E: '$path' is not a complete URL ",
900 "and a separate URL is not specified");
902 return ($url, $path);
904 return ($path, '');
907 sub complete_url_ls_init {
908 my ($ra, $repo_path, $switch, $pfx) = @_;
909 unless ($repo_path) {
910 print STDERR "W: $switch not specified\n";
911 return;
913 $repo_path =~ s#/+$##;
914 if ($repo_path =~ m#^[a-z\+]+://#) {
915 $ra = Git::SVN::Ra->new($repo_path);
916 $repo_path = '';
917 } else {
918 $repo_path =~ s#^/+##;
919 unless ($ra) {
920 fatal("E: '$repo_path' is not a complete URL ",
921 "and a separate URL is not specified");
924 my $url = $ra->{url};
925 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
926 my $k = "svn-remote.$gs->{repo_id}.url";
927 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
928 if ($orig_url && ($orig_url ne $gs->{url})) {
929 die "$k already set: $orig_url\n",
930 "wanted to set to: $gs->{url}\n";
932 command_oneline('config', $k, $gs->{url}) unless $orig_url;
933 my $remote_path = "$ra->{svn_path}/$repo_path/*";
934 $remote_path =~ s#/+#/#g;
935 $remote_path =~ s#^/##g;
936 my ($n) = ($switch =~ /^--(\w+)/);
937 if (length $pfx && $pfx !~ m#/$#) {
938 die "--prefix='$pfx' must have a trailing slash '/'\n";
940 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
941 "$remote_path:refs/remotes/$pfx*");
944 sub verify_ref {
945 my ($ref) = @_;
946 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
947 { STDERR => 0 }); };
950 sub get_tree_from_treeish {
951 my ($treeish) = @_;
952 # $treeish can be a symbolic ref, too:
953 my $type = command_oneline(qw/cat-file -t/, $treeish);
954 my $expected;
955 while ($type eq 'tag') {
956 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
958 if ($type eq 'commit') {
959 $expected = (grep /^tree /, command(qw/cat-file commit/,
960 $treeish))[0];
961 ($expected) = ($expected =~ /^tree ($sha1)$/o);
962 die "Unable to get tree from $treeish\n" unless $expected;
963 } elsif ($type eq 'tree') {
964 $expected = $treeish;
965 } else {
966 die "$treeish is a $type, expected tree, tag or commit\n";
968 return $expected;
971 sub get_commit_entry {
972 my ($treeish) = shift;
973 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
974 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
975 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
976 open my $log_fh, '>', $commit_editmsg or croak $!;
978 my $type = command_oneline(qw/cat-file -t/, $treeish);
979 if ($type eq 'commit' || $type eq 'tag') {
980 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
981 $type, $treeish);
982 my $in_msg = 0;
983 while (<$msg_fh>) {
984 if (!$in_msg) {
985 $in_msg = 1 if (/^\s*$/);
986 } elsif (/^git-svn-id: /) {
987 # skip this for now, we regenerate the
988 # correct one on re-fetch anyways
989 # TODO: set *:merge properties or like...
990 } else {
991 print $log_fh $_ or croak $!;
994 command_close_pipe($msg_fh, $ctx);
996 close $log_fh or croak $!;
998 if ($_edit || ($type eq 'tree')) {
999 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1000 # TODO: strip out spaces, comments, like git-commit.sh
1001 system($editor, $commit_editmsg);
1003 rename $commit_editmsg, $commit_msg or croak $!;
1004 open $log_fh, '<', $commit_msg or croak $!;
1005 { local $/; chomp($log_entry{log} = <$log_fh>); }
1006 close $log_fh or croak $!;
1007 unlink $commit_msg;
1008 \%log_entry;
1011 sub s_to_file {
1012 my ($str, $file, $mode) = @_;
1013 open my $fd,'>',$file or croak $!;
1014 print $fd $str,"\n" or croak $!;
1015 close $fd or croak $!;
1016 chmod ($mode &~ umask, $file) if (defined $mode);
1019 sub file_to_s {
1020 my $file = shift;
1021 open my $fd,'<',$file or croak "$!: file: $file\n";
1022 local $/;
1023 my $ret = <$fd>;
1024 close $fd or croak $!;
1025 $ret =~ s/\s*$//s;
1026 return $ret;
1029 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1030 sub load_authors {
1031 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1032 my $log = $cmd eq 'log';
1033 while (<$authors>) {
1034 chomp;
1035 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1036 my ($user, $name, $email) = ($1, $2, $3);
1037 if ($log) {
1038 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1039 } else {
1040 $users{$user} = [$name, $email];
1043 close $authors or croak $!;
1046 # convert GetOpt::Long specs for use by git-config
1047 sub read_repo_config {
1048 return unless -d $ENV{GIT_DIR};
1049 my $opts = shift;
1050 my @config_only;
1051 foreach my $o (keys %$opts) {
1052 # if we have mixedCase and a long option-only, then
1053 # it's a config-only variable that we don't need for
1054 # the command-line.
1055 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1056 my $v = $opts->{$o};
1057 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1058 $key =~ s/-//g;
1059 my $arg = 'git-config';
1060 $arg .= ' --int' if ($o =~ /[:=]i$/);
1061 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1062 if (ref $v eq 'ARRAY') {
1063 chomp(my @tmp = `$arg --get-all svn.$key`);
1064 @$v = @tmp if @tmp;
1065 } else {
1066 chomp(my $tmp = `$arg --get svn.$key`);
1067 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1068 $$v = $tmp;
1072 delete @$opts{@config_only} if @config_only;
1075 sub extract_metadata {
1076 my $id = shift or return (undef, undef, undef);
1077 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1078 \s([a-f\d\-]+)$/x);
1079 if (!defined $rev || !$uuid || !$url) {
1080 # some of the original repositories I made had
1081 # identifiers like this:
1082 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1084 return ($url, $rev, $uuid);
1087 sub cmt_metadata {
1088 return extract_metadata((grep(/^git-svn-id: /,
1089 command(qw/cat-file commit/, shift)))[-1]);
1092 sub working_head_info {
1093 my ($head, $refs) = @_;
1094 my @args = ('log', '--no-color', '--first-parent');
1095 my ($fh, $ctx) = command_output_pipe(@args, $head);
1096 my $hash;
1097 my %max;
1098 while (<$fh>) {
1099 if ( m{^commit ($::sha1)$} ) {
1100 unshift @$refs, $hash if $hash and $refs;
1101 $hash = $1;
1102 next;
1104 next unless s{^\s*(git-svn-id:)}{$1};
1105 my ($url, $rev, $uuid) = extract_metadata($_);
1106 if (defined $url && defined $rev) {
1107 next if $max{$url} and $max{$url} < $rev;
1108 if (my $gs = Git::SVN->find_by_url($url)) {
1109 my $c = $gs->rev_db_get($rev);
1110 if ($c && $c eq $hash) {
1111 close $fh; # break the pipe
1112 return ($url, $rev, $uuid, $gs);
1113 } else {
1114 $max{$url} ||= $gs->rev_db_max;
1119 command_close_pipe($fh, $ctx);
1120 (undef, undef, undef, undef);
1123 sub read_commit_parents {
1124 my ($parents, $c) = @_;
1125 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1126 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1127 @{$parents->{$c}} = split(/ /, $p);
1130 sub linearize_history {
1131 my ($gs, $refs) = @_;
1132 my %parents;
1133 foreach my $c (@$refs) {
1134 read_commit_parents(\%parents, $c);
1137 my @linear_refs;
1138 my %skip = ();
1139 my $last_svn_commit = $gs->last_commit;
1140 foreach my $c (reverse @$refs) {
1141 next if $c eq $last_svn_commit;
1142 last if $skip{$c};
1144 unshift @linear_refs, $c;
1145 $skip{$c} = 1;
1147 # we only want the first parent to diff against for linear
1148 # history, we save the rest to inject when we finalize the
1149 # svn commit
1150 my $fp_a = verify_ref("$c~1");
1151 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1152 if (!$fp_a || !$fp_b) {
1153 die "Commit $c\n",
1154 "has no parent commit, and therefore ",
1155 "nothing to diff against.\n",
1156 "You should be working from a repository ",
1157 "originally created by git-svn\n";
1159 if ($fp_a ne $fp_b) {
1160 die "$c~1 = $fp_a, however parsing commit $c ",
1161 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1164 foreach my $p (@{$parents{$c}}) {
1165 $skip{$p} = 1;
1168 (\@linear_refs, \%parents);
1171 sub find_file_type_and_diff_status {
1172 my ($path) = @_;
1173 return ('dir', '') if $path eq '.';
1175 my $diff_output =
1176 command_oneline(qw(diff --cached --name-status --), $path) || "";
1177 my $diff_status = (split(' ', $diff_output))[0] || "";
1179 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1181 return (undef, undef) if !$diff_status && !$ls_tree;
1183 if ($diff_status eq "A") {
1184 return ("link", $diff_status) if -l $path;
1185 return ("dir", $diff_status) if -d $path;
1186 return ("file", $diff_status);
1189 my $mode = (split(' ', $ls_tree))[0] || "";
1191 return ("link", $diff_status) if $mode eq "120000";
1192 return ("dir", $diff_status) if $mode eq "040000";
1193 return ("file", $diff_status);
1196 package Git::SVN::Util;
1197 use strict;
1198 use warnings;
1199 use Digest::MD5;
1201 sub md5sum {
1202 my $arg = shift;
1203 my $ref = ref $arg;
1204 my $md5 = Digest::MD5->new();
1205 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1206 $md5->addfile($arg) or croak $!;
1207 } elsif ($ref eq 'SCALAR') {
1208 $md5->add($$arg) or croak $!;
1209 } elsif (!$ref) {
1210 $md5->add($arg) or croak $!;
1211 } else {
1212 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1214 return $md5->hexdigest();
1217 package Git::SVN;
1218 use strict;
1219 use warnings;
1220 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1221 $_repack $_repack_flags $_use_svm_props $_head
1222 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1223 use Carp qw/croak/;
1224 use File::Path qw/mkpath/;
1225 use File::Copy qw/copy/;
1226 use IPC::Open3;
1228 my $_repack_nr;
1229 # properties that we do not log:
1230 my %SKIP_PROP;
1231 BEGIN {
1232 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1233 svn:special svn:executable
1234 svn:entry:committed-rev
1235 svn:entry:last-author
1236 svn:entry:uuid
1237 svn:entry:committed-date/;
1239 # some options are read globally, but can be overridden locally
1240 # per [svn-remote "..."] section. Command-line options will *NOT*
1241 # override options set in an [svn-remote "..."] section
1242 no strict 'refs';
1243 for my $option (qw/follow_parent no_metadata use_svm_props
1244 use_svnsync_props/) {
1245 my $key = $option;
1246 $key =~ tr/_//d;
1247 my $prop = "-$option";
1248 *$option = sub {
1249 my ($self) = @_;
1250 return $self->{$prop} if exists $self->{$prop};
1251 my $k = "svn-remote.$self->{repo_id}.$key";
1252 eval { command_oneline(qw/config --get/, $k) };
1253 if ($@) {
1254 $self->{$prop} = ${"Git::SVN::_$option"};
1255 } else {
1256 my $v = command_oneline(qw/config --bool/,$k);
1257 $self->{$prop} = $v eq 'false' ? 0 : 1;
1259 return $self->{$prop};
1264 my %LOCKFILES;
1265 END { unlink keys %LOCKFILES if %LOCKFILES }
1267 sub resolve_local_globs {
1268 my ($url, $fetch, $glob_spec) = @_;
1269 return unless defined $glob_spec;
1270 my $ref = $glob_spec->{ref};
1271 my $path = $glob_spec->{path};
1272 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1273 next unless m#^refs/remotes/$ref->{regex}$#;
1274 my $p = $1;
1275 my $pathname = desanitize_refname($path->full_path($p));
1276 my $refname = desanitize_refname($ref->full_path($p));
1277 if (my $existing = $fetch->{$pathname}) {
1278 if ($existing ne $refname) {
1279 die "Refspec conflict:\n",
1280 "existing: refs/remotes/$existing\n",
1281 " globbed: refs/remotes/$refname\n";
1283 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1284 $u =~ s!^\Q$url\E(/|$)!! or die
1285 "refs/remotes/$refname: '$url' not found in '$u'\n";
1286 if ($pathname ne $u) {
1287 warn "W: Refspec glob conflict ",
1288 "(ref: refs/remotes/$refname):\n",
1289 "expected path: $pathname\n",
1290 " real path: $u\n",
1291 "Continuing ahead with $u\n";
1292 next;
1294 } else {
1295 $fetch->{$pathname} = $refname;
1300 sub parse_revision_argument {
1301 my ($base, $head) = @_;
1302 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1303 return ($base, $head);
1305 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1306 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1307 return ($head, $head) if ($::_revision eq 'HEAD');
1308 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1309 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1310 die "revision argument: $::_revision not understood by git-svn\n";
1313 sub fetch_all {
1314 my ($repo_id, $remotes) = @_;
1315 if (ref $repo_id) {
1316 my $gs = $repo_id;
1317 $repo_id = undef;
1318 $repo_id = $gs->{repo_id};
1320 $remotes ||= read_all_remotes();
1321 my $remote = $remotes->{$repo_id} or
1322 die "[svn-remote \"$repo_id\"] unknown\n";
1323 my $fetch = $remote->{fetch};
1324 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1325 my (@gs, @globs);
1326 my $ra = Git::SVN::Ra->new($url);
1327 my $uuid = $ra->get_uuid;
1328 my $head = $ra->get_latest_revnum;
1329 my $base = defined $fetch ? $head : 0;
1331 # read the max revs for wildcard expansion (branches/*, tags/*)
1332 foreach my $t (qw/branches tags/) {
1333 defined $remote->{$t} or next;
1334 push @globs, $remote->{$t};
1335 my $max_rev = eval { tmp_config(qw/--int --get/,
1336 "svn-remote.$repo_id.${t}-maxRev") };
1337 if (defined $max_rev && ($max_rev < $base)) {
1338 $base = $max_rev;
1339 } elsif (!defined $max_rev) {
1340 $base = 0;
1344 if ($fetch) {
1345 foreach my $p (sort keys %$fetch) {
1346 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1347 my $lr = $gs->rev_db_max;
1348 if (defined $lr) {
1349 $base = $lr if ($lr < $base);
1351 push @gs, $gs;
1355 ($base, $head) = parse_revision_argument($base, $head);
1356 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1359 sub read_all_remotes {
1360 my $r = {};
1361 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1362 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1363 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1364 $local_ref =~ s{^/}{};
1365 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1366 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1367 $r->{$1}->{url} = $2;
1368 } elsif (m!^(.+)\.(branches|tags)=
1369 (.*):refs/remotes/(.+)\s*$/!x) {
1370 my ($p, $g) = ($3, $4);
1371 my $rs = $r->{$1}->{$2} = {
1372 t => $2,
1373 remote => $1,
1374 path => Git::SVN::GlobSpec->new($p),
1375 ref => Git::SVN::GlobSpec->new($g) };
1376 if (length($rs->{ref}->{right}) != 0) {
1377 die "The '*' glob character must be the last ",
1378 "character of '$g'\n";
1385 sub init_vars {
1386 if (defined $_repack) {
1387 $_repack = 1000 if ($_repack <= 0);
1388 $_repack_nr = $_repack;
1389 $_repack_flags ||= '-d';
1393 sub verify_remotes_sanity {
1394 return unless -d $ENV{GIT_DIR};
1395 my %seen;
1396 foreach (command(qw/config -l/)) {
1397 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1398 if ($seen{$1}) {
1399 die "Remote ref refs/remote/$1 is tracked by",
1400 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1401 "Please resolve this ambiguity in ",
1402 "your git configuration file before ",
1403 "continuing\n";
1405 $seen{$1} = $_;
1410 # we allow more chars than remotes2config.sh...
1411 sub sanitize_remote_name {
1412 my ($name) = @_;
1413 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1414 $name;
1417 sub find_existing_remote {
1418 my ($url, $remotes) = @_;
1419 return undef if $no_reuse_existing;
1420 my $existing;
1421 foreach my $repo_id (keys %$remotes) {
1422 my $u = $remotes->{$repo_id}->{url} or next;
1423 next if $u ne $url;
1424 $existing = $repo_id;
1425 last;
1427 $existing;
1430 sub init_remote_config {
1431 my ($self, $url, $no_write) = @_;
1432 $url =~ s!/+$!!; # strip trailing slash
1433 my $r = read_all_remotes();
1434 my $existing = find_existing_remote($url, $r);
1435 if ($existing) {
1436 unless ($no_write) {
1437 print STDERR "Using existing ",
1438 "[svn-remote \"$existing\"]\n";
1440 $self->{repo_id} = $existing;
1441 } elsif ($_minimize_url) {
1442 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1443 $existing = find_existing_remote($min_url, $r);
1444 if ($existing) {
1445 unless ($no_write) {
1446 print STDERR "Using existing ",
1447 "[svn-remote \"$existing\"]\n";
1449 $self->{repo_id} = $existing;
1451 if ($min_url ne $url) {
1452 unless ($no_write) {
1453 print STDERR "Using higher level of URL: ",
1454 "$url => $min_url\n";
1456 my $old_path = $self->{path};
1457 $self->{path} = $url;
1458 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1459 if (length $old_path) {
1460 $self->{path} .= "/$old_path";
1462 $url = $min_url;
1465 my $orig_url;
1466 if (!$existing) {
1467 # verify that we aren't overwriting anything:
1468 $orig_url = eval {
1469 command_oneline('config', '--get',
1470 "svn-remote.$self->{repo_id}.url")
1472 if ($orig_url && ($orig_url ne $url)) {
1473 die "svn-remote.$self->{repo_id}.url already set: ",
1474 "$orig_url\nwanted to set to: $url\n";
1477 my ($xrepo_id, $xpath) = find_ref($self->refname);
1478 if (defined $xpath) {
1479 die "svn-remote.$xrepo_id.fetch already set to track ",
1480 "$xpath:refs/remotes/", $self->refname, "\n";
1482 unless ($no_write) {
1483 command_noisy('config',
1484 "svn-remote.$self->{repo_id}.url", $url);
1485 $self->{path} =~ s{^/}{};
1486 command_noisy('config', '--add',
1487 "svn-remote.$self->{repo_id}.fetch",
1488 "$self->{path}:".$self->refname);
1490 $self->{url} = $url;
1493 sub find_by_url { # repos_root and, path are optional
1494 my ($class, $full_url, $repos_root, $path) = @_;
1496 return undef unless defined $full_url;
1497 remove_username($full_url);
1498 remove_username($repos_root) if defined $repos_root;
1499 my $remotes = read_all_remotes();
1500 if (defined $full_url && defined $repos_root && !defined $path) {
1501 $path = $full_url;
1502 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1504 foreach my $repo_id (keys %$remotes) {
1505 my $u = $remotes->{$repo_id}->{url} or next;
1506 remove_username($u);
1507 next if defined $repos_root && $repos_root ne $u;
1509 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1510 foreach (qw/branches tags/) {
1511 resolve_local_globs($u, $fetch,
1512 $remotes->{$repo_id}->{$_});
1514 my $p = $path;
1515 unless (defined $p) {
1516 $p = $full_url;
1517 $p =~ s#^\Q$u\E(?:/|$)## or next;
1519 foreach my $f (keys %$fetch) {
1520 next if $f ne $p;
1521 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1524 undef;
1527 sub init {
1528 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1529 my $self = _new($class, $repo_id, $ref_id, $path);
1530 if (defined $url) {
1531 $self->init_remote_config($url, $no_write);
1533 $self;
1536 sub find_ref {
1537 my ($ref_id) = @_;
1538 foreach (command(qw/config -l/)) {
1539 next unless m!^svn-remote\.(.+)\.fetch=
1540 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1541 my ($repo_id, $path, $ref) = ($1, $2, $3);
1542 if ($ref eq $ref_id) {
1543 $path = '' if ($path =~ m#^\./?#);
1544 return ($repo_id, $path);
1547 (undef, undef, undef);
1550 sub new {
1551 my ($class, $ref_id, $repo_id, $path) = @_;
1552 if (defined $ref_id && !defined $repo_id && !defined $path) {
1553 ($repo_id, $path) = find_ref($ref_id);
1554 if (!defined $repo_id) {
1555 die "Could not find a \"svn-remote.*.fetch\" key ",
1556 "in the repository configuration matching: ",
1557 "refs/remotes/$ref_id\n";
1560 my $self = _new($class, $repo_id, $ref_id, $path);
1561 if (!defined $self->{path} || !length $self->{path}) {
1562 my $fetch = command_oneline('config', '--get',
1563 "svn-remote.$repo_id.fetch",
1564 ":refs/remotes/$ref_id\$") or
1565 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1566 "\":refs/remotes/$ref_id\$\" in config\n";
1567 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1569 $self->{url} = command_oneline('config', '--get',
1570 "svn-remote.$repo_id.url") or
1571 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1572 $self->rebuild;
1573 $self;
1576 sub refname {
1577 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1579 # It cannot end with a slash /, we'll throw up on this because
1580 # SVN can't have directories with a slash in their name, either:
1581 if ($refname =~ m{/$}) {
1582 die "ref: '$refname' ends with a trailing slash, this is ",
1583 "not permitted by git nor Subversion\n";
1586 # It cannot have ASCII control character space, tilde ~, caret ^,
1587 # colon :, question-mark ?, asterisk *, space, or open bracket [
1588 # anywhere.
1590 # Additionally, % must be escaped because it is used for escaping
1591 # and we want our escaped refname to be reversible
1592 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1594 # no slash-separated component can begin with a dot .
1595 # /.* becomes /%2E*
1596 $refname =~ s{/\.}{/%2E}g;
1598 # It cannot have two consecutive dots .. anywhere
1599 # .. becomes %2E%2E
1600 $refname =~ s{\.\.}{%2E%2E}g;
1602 return $refname;
1605 sub desanitize_refname {
1606 my ($refname) = @_;
1607 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1608 return $refname;
1611 sub svm_uuid {
1612 my ($self) = @_;
1613 return $self->{svm}->{uuid} if $self->svm;
1614 $self->ra;
1615 unless ($self->{svm}) {
1616 die "SVM UUID not cached, and reading remotely failed\n";
1618 $self->{svm}->{uuid};
1621 sub svm {
1622 my ($self) = @_;
1623 return $self->{svm} if $self->{svm};
1624 my $svm;
1625 # see if we have it in our config, first:
1626 eval {
1627 my $section = "svn-remote.$self->{repo_id}";
1628 $svm = {
1629 source => tmp_config('--get', "$section.svm-source"),
1630 uuid => tmp_config('--get', "$section.svm-uuid"),
1631 replace => tmp_config('--get', "$section.svm-replace"),
1634 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1635 $self->{svm} = $svm;
1637 $self->{svm};
1640 sub _set_svm_vars {
1641 my ($self, $ra) = @_;
1642 return $ra if $self->svm;
1644 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1645 "(svm:source, svm:uuid) ",
1646 "from the following URLs:\n" );
1647 sub read_svm_props {
1648 my ($self, $ra, $path, $r) = @_;
1649 my $props = ($ra->get_dir($path, $r))[2];
1650 my $src = $props->{'svm:source'};
1651 my $uuid = $props->{'svm:uuid'};
1652 return undef if (!$src || !$uuid);
1654 chomp($src, $uuid);
1656 $uuid =~ m{^[0-9a-f\-]{30,}$}
1657 or die "doesn't look right - svm:uuid is '$uuid'\n";
1659 # the '!' is used to mark the repos_root!/relative/path
1660 $src =~ s{/?!/?}{/};
1661 $src =~ s{/+$}{}; # no trailing slashes please
1662 # username is of no interest
1663 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1665 my $replace = $ra->{url};
1666 $replace .= "/$path" if length $path;
1668 my $section = "svn-remote.$self->{repo_id}";
1669 tmp_config("$section.svm-source", $src);
1670 tmp_config("$section.svm-replace", $replace);
1671 tmp_config("$section.svm-uuid", $uuid);
1672 $self->{svm} = {
1673 source => $src,
1674 uuid => $uuid,
1675 replace => $replace
1679 my $r = $ra->get_latest_revnum;
1680 my $path = $self->{path};
1681 my %tried;
1682 while (length $path) {
1683 unless ($tried{"$self->{url}/$path"}) {
1684 return $ra if $self->read_svm_props($ra, $path, $r);
1685 $tried{"$self->{url}/$path"} = 1;
1687 $path =~ s#/?[^/]+$##;
1689 die "Path: '$path' should be ''\n" if $path ne '';
1690 return $ra if $self->read_svm_props($ra, $path, $r);
1691 $tried{"$self->{url}/$path"} = 1;
1693 if ($ra->{repos_root} eq $self->{url}) {
1694 die @err, (map { " $_\n" } keys %tried), "\n";
1697 # nope, make sure we're connected to the repository root:
1698 my $ok;
1699 my @tried_b;
1700 $path = $ra->{svn_path};
1701 $ra = Git::SVN::Ra->new($ra->{repos_root});
1702 while (length $path) {
1703 unless ($tried{"$ra->{url}/$path"}) {
1704 $ok = $self->read_svm_props($ra, $path, $r);
1705 last if $ok;
1706 $tried{"$ra->{url}/$path"} = 1;
1708 $path =~ s#/?[^/]+$##;
1710 die "Path: '$path' should be ''\n" if $path ne '';
1711 $ok ||= $self->read_svm_props($ra, $path, $r);
1712 $tried{"$ra->{url}/$path"} = 1;
1713 if (!$ok) {
1714 die @err, (map { " $_\n" } keys %tried), "\n";
1716 Git::SVN::Ra->new($self->{url});
1719 sub svnsync {
1720 my ($self) = @_;
1721 return $self->{svnsync} if $self->{svnsync};
1723 if ($self->no_metadata) {
1724 die "Can't have both 'noMetadata' and ",
1725 "'useSvnsyncProps' options set!\n";
1727 if ($self->rewrite_root) {
1728 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1729 "options set!\n";
1732 my $svnsync;
1733 # see if we have it in our config, first:
1734 eval {
1735 my $section = "svn-remote.$self->{repo_id}";
1736 $svnsync = {
1737 url => tmp_config('--get', "$section.svnsync-url"),
1738 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1741 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1742 return $self->{svnsync} = $svnsync;
1745 my $err = "useSvnsyncProps set, but failed to read " .
1746 "svnsync property: svn:sync-from-";
1747 my $rp = $self->ra->rev_proplist(0);
1749 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1750 $url =~ m{^[a-z\+]+://} or
1751 die "doesn't look right - svn:sync-from-url is '$url'\n";
1753 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1754 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1755 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1757 my $section = "svn-remote.$self->{repo_id}";
1758 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1759 tmp_config('--add', "$section.svnsync-url", $url);
1760 return $self->{svnsync} = { url => $url, uuid => $uuid };
1763 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1764 # remote lookup (useful for 'git svn log').
1765 sub ra_uuid {
1766 my ($self) = @_;
1767 unless ($self->{ra_uuid}) {
1768 my $key = "svn-remote.$self->{repo_id}.uuid";
1769 my $uuid = eval { tmp_config('--get', $key) };
1770 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1771 $self->{ra_uuid} = $uuid;
1772 } else {
1773 die "ra_uuid called without URL\n" unless $self->{url};
1774 $self->{ra_uuid} = $self->ra->get_uuid;
1775 tmp_config('--add', $key, $self->{ra_uuid});
1778 $self->{ra_uuid};
1781 sub _set_repos_root {
1782 my ($self, $repos_root) = @_;
1783 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1784 $repos_root ||= $self->ra->{repos_root};
1785 tmp_config($k, $repos_root);
1786 $repos_root;
1789 sub repos_root {
1790 my ($self) = @_;
1791 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1792 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1795 sub ra {
1796 my ($self) = shift;
1797 my $ra = Git::SVN::Ra->new($self->{url});
1798 $self->_set_repos_root($ra->{repos_root});
1799 if ($self->use_svm_props && !$self->{svm}) {
1800 if ($self->no_metadata) {
1801 die "Can't have both 'noMetadata' and ",
1802 "'useSvmProps' options set!\n";
1803 } elsif ($self->use_svnsync_props) {
1804 die "Can't have both 'useSvnsyncProps' and ",
1805 "'useSvmProps' options set!\n";
1807 $ra = $self->_set_svm_vars($ra);
1808 $self->{-want_revprops} = 1;
1810 $ra;
1813 sub rel_path {
1814 my ($self) = @_;
1815 my $repos_root = $self->ra->{repos_root};
1816 return $self->{path} if ($self->{url} eq $repos_root);
1817 my $url = $self->{url} .
1818 (length $self->{path} ? "/$self->{path}" : $self->{path});
1819 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1820 $url;
1823 # prop_walk(PATH, REV, SUB)
1824 # -------------------------
1825 # Recursively traverse PATH at revision REV and invoke SUB for each
1826 # directory that contains a SVN property. SUB will be invoked as
1827 # follows: &SUB(gs, path, props); where `gs' is this instance of
1828 # Git::SVN, `path' the path to the directory where the properties
1829 # `props' were found. The `path' will be relative to point of checkout,
1830 # that is, if url://repo/trunk is the current Git branch, and that
1831 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1832 # as `path' (note the trailing `/').
1833 sub prop_walk {
1834 my ($self, $path, $rev, $sub) = @_;
1836 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1837 $path =~ s#^/*#/#g;
1838 my $p = $path;
1839 # Strip the irrelevant part of the path.
1840 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1841 # Ensure the path is terminated by a `/'.
1842 $p =~ s#/*$#/#;
1844 # The properties contain all the internal SVN stuff nobody
1845 # (usually) cares about.
1846 my $interesting_props = 0;
1847 foreach (keys %{$props}) {
1848 # If it doesn't start with `svn:', it must be a
1849 # user-defined property.
1850 ++$interesting_props and next if $_ !~ /^svn:/;
1851 # FIXME: Fragile, if SVN adds new public properties,
1852 # this needs to be updated.
1853 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1854 |eol-style|mime-type
1855 |externals|needs-lock)$/x;
1857 &$sub($self, $p, $props) if $interesting_props;
1859 foreach (sort keys %$dirent) {
1860 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1861 $self->prop_walk($path . '/' . $_, $rev, $sub);
1865 sub last_rev { ($_[0]->last_rev_commit)[0] }
1866 sub last_commit { ($_[0]->last_rev_commit)[1] }
1868 # returns the newest SVN revision number and newest commit SHA1
1869 sub last_rev_commit {
1870 my ($self) = @_;
1871 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1872 return ($self->{last_rev}, $self->{last_commit});
1874 my $c = ::verify_ref($self->refname.'^0');
1875 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1876 my $rev = (::cmt_metadata($c))[1];
1877 if (defined $rev) {
1878 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1879 return ($rev, $c);
1882 my $db_path = $self->db_path;
1883 unless (-e $db_path) {
1884 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1885 return (undef, undef);
1887 my $offset = -41; # from tail
1888 my $rl;
1889 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1890 sysseek($fh, $offset, 2); # don't care for errors
1891 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1892 chomp $rl;
1893 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1894 $offset -= 41;
1895 sysseek($fh, $offset, 2); # don't care for errors
1896 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1897 chomp $rl;
1899 if ($c && $c ne $rl) {
1900 die "$db_path and ", $self->refname,
1901 " inconsistent!:\n$c != $rl\n";
1903 my $rev = sysseek($fh, 0, 1) or croak $!;
1904 $rev = ($rev - 41) / 41;
1905 close $fh or croak $!;
1906 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1907 return ($rev, $c);
1910 sub get_fetch_range {
1911 my ($self, $min, $max) = @_;
1912 $max ||= $self->ra->get_latest_revnum;
1913 $min ||= $self->rev_db_max;
1914 (++$min, $max);
1917 sub tmp_config {
1918 my (@args) = @_;
1919 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1920 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1921 if (! -f $config && -f $old_def_config) {
1922 rename $old_def_config, $config or
1923 die "Failed rename $old_def_config => $config: $!\n";
1925 my $old_config = $ENV{GIT_CONFIG};
1926 $ENV{GIT_CONFIG} = $config;
1927 $@ = undef;
1928 my @ret = eval {
1929 unless (-f $config) {
1930 mkfile($config);
1931 open my $fh, '>', $config or
1932 die "Can't open $config: $!\n";
1933 print $fh "; This file is used internally by ",
1934 "git-svn\n" or die
1935 "Couldn't write to $config: $!\n";
1936 print $fh "; You should not have to edit it\n" or
1937 die "Couldn't write to $config: $!\n";
1938 close $fh or die "Couldn't close $config: $!\n";
1940 command('config', @args);
1942 my $err = $@;
1943 if (defined $old_config) {
1944 $ENV{GIT_CONFIG} = $old_config;
1945 } else {
1946 delete $ENV{GIT_CONFIG};
1948 die $err if $err;
1949 wantarray ? @ret : $ret[0];
1952 sub tmp_index_do {
1953 my ($self, $sub) = @_;
1954 my $old_index = $ENV{GIT_INDEX_FILE};
1955 $ENV{GIT_INDEX_FILE} = $self->{index};
1956 $@ = undef;
1957 my @ret = eval {
1958 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1959 mkpath([$dir]) unless -d $dir;
1960 &$sub;
1962 my $err = $@;
1963 if (defined $old_index) {
1964 $ENV{GIT_INDEX_FILE} = $old_index;
1965 } else {
1966 delete $ENV{GIT_INDEX_FILE};
1968 die $err if $err;
1969 wantarray ? @ret : $ret[0];
1972 sub assert_index_clean {
1973 my ($self, $treeish) = @_;
1975 $self->tmp_index_do(sub {
1976 command_noisy('read-tree', $treeish) unless -e $self->{index};
1977 my $x = command_oneline('write-tree');
1978 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1979 /^tree ($::sha1)/mo);
1980 return if $y eq $x;
1982 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1983 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1984 command_noisy('read-tree', $treeish);
1985 $x = command_oneline('write-tree');
1986 if ($y ne $x) {
1987 ::fatal "trees ($treeish) $y != $x\n",
1988 "Something is seriously wrong...";
1993 sub get_commit_parents {
1994 my ($self, $log_entry) = @_;
1995 my (%seen, @ret, @tmp);
1996 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1997 if (my $ip = $self->{inject_parents}) {
1998 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1999 push @tmp, $commit;
2002 if (my $cur = ::verify_ref($self->refname.'^0')) {
2003 push @tmp, $cur;
2005 if (my $ipd = $self->{inject_parents_dcommit}) {
2006 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2007 push @tmp, @$commit;
2010 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2011 while (my $p = shift @tmp) {
2012 next if $seen{$p};
2013 $seen{$p} = 1;
2014 push @ret, $p;
2015 # MAXPARENT is defined to 16 in commit-tree.c:
2016 last if @ret >= 16;
2018 if (@tmp) {
2019 die "r$log_entry->{revision}: No room for parents:\n\t",
2020 join("\n\t", @tmp), "\n";
2022 @ret;
2025 sub rewrite_root {
2026 my ($self) = @_;
2027 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2028 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2029 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2030 if ($rwr) {
2031 $rwr =~ s#/+$##;
2032 if ($rwr !~ m#^[a-z\+]+://#) {
2033 die "$rwr is not a valid URL (key: $k)\n";
2036 $self->{-rewrite_root} = $rwr;
2039 sub metadata_url {
2040 my ($self) = @_;
2041 ($self->rewrite_root || $self->{url}) .
2042 (length $self->{path} ? '/' . $self->{path} : '');
2045 sub full_url {
2046 my ($self) = @_;
2047 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2050 sub do_git_commit {
2051 my ($self, $log_entry) = @_;
2052 my $lr = $self->last_rev;
2053 if (defined $lr && $lr >= $log_entry->{revision}) {
2054 die "Last fetched revision of ", $self->refname,
2055 " was r$lr, but we are about to fetch: ",
2056 "r$log_entry->{revision}!\n";
2058 if (my $c = $self->rev_db_get($log_entry->{revision})) {
2059 croak "$log_entry->{revision} = $c already exists! ",
2060 "Why are we refetching it?\n";
2062 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
2063 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
2064 $log_entry->{email};
2065 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2067 my $tree = $log_entry->{tree};
2068 if (!defined $tree) {
2069 $tree = $self->tmp_index_do(sub {
2070 command_oneline('write-tree') });
2072 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2074 my @exec = ('git-commit-tree', $tree);
2075 foreach ($self->get_commit_parents($log_entry)) {
2076 push @exec, '-p', $_;
2078 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2079 or croak $!;
2080 print $msg_fh $log_entry->{log} or croak $!;
2081 unless ($self->no_metadata) {
2082 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2083 or croak $!;
2085 $msg_fh->flush == 0 or croak $!;
2086 close $msg_fh or croak $!;
2087 chomp(my $commit = do { local $/; <$out_fh> });
2088 close $out_fh or croak $!;
2089 waitpid $pid, 0;
2090 croak $? if $?;
2091 if ($commit !~ /^$::sha1$/o) {
2092 die "Failed to commit, invalid sha1: $commit\n";
2095 $self->rev_db_set($log_entry->{revision}, $commit, 1);
2097 $self->{last_rev} = $log_entry->{revision};
2098 $self->{last_commit} = $commit;
2099 print "r$log_entry->{revision}";
2100 if (defined $log_entry->{svm_revision}) {
2101 print " (\@$log_entry->{svm_revision})";
2102 $self->rev_db_set($log_entry->{svm_revision}, $commit,
2103 0, $self->svm_uuid);
2105 print " = $commit ($self->{ref_id})\n";
2106 if (defined $_repack && (--$_repack_nr == 0)) {
2107 $_repack_nr = $_repack;
2108 # repack doesn't use any arguments with spaces in them, does it?
2109 print "Running git repack $_repack_flags ...\n";
2110 command_noisy('repack', split(/\s+/, $_repack_flags));
2111 print "Done repacking\n";
2113 return $commit;
2116 sub match_paths {
2117 my ($self, $paths, $r) = @_;
2118 return 1 if $self->{path} eq '';
2119 if (my $path = $paths->{"/$self->{path}"}) {
2120 return ($path->{action} eq 'D') ? 0 : 1;
2122 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2123 if (grep /$self->{path_regex}/, keys %$paths) {
2124 return 1;
2126 my $c = '';
2127 foreach (split m#/#, $self->{path}) {
2128 $c .= "/$_";
2129 next unless ($paths->{$c} &&
2130 ($paths->{$c}->{action} =~ /^[AR]$/));
2131 if ($self->ra->check_path($self->{path}, $r) ==
2132 $SVN::Node::dir) {
2133 return 1;
2136 return 0;
2139 sub find_parent_branch {
2140 my ($self, $paths, $rev) = @_;
2141 return undef unless $self->follow_parent;
2142 unless (defined $paths) {
2143 my $err_handler = $SVN::Error::handler;
2144 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2145 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2146 $paths =
2147 Git::SVN::Ra::dup_changed_paths($_[0]) });
2148 $SVN::Error::handler = $err_handler;
2150 return undef unless defined $paths;
2152 # look for a parent from another branch:
2153 my @b_path_components = split m#/#, $self->rel_path;
2154 my @a_path_components;
2155 my $i;
2156 while (@b_path_components) {
2157 $i = $paths->{'/'.join('/', @b_path_components)};
2158 last if $i && defined $i->{copyfrom_path};
2159 unshift(@a_path_components, pop(@b_path_components));
2161 return undef unless defined $i && defined $i->{copyfrom_path};
2162 my $branch_from = $i->{copyfrom_path};
2163 if (@a_path_components) {
2164 print STDERR "branch_from: $branch_from => ";
2165 $branch_from .= '/'.join('/', @a_path_components);
2166 print STDERR $branch_from, "\n";
2168 my $r = $i->{copyfrom_rev};
2169 my $repos_root = $self->ra->{repos_root};
2170 my $url = $self->ra->{url};
2171 my $new_url = $repos_root . $branch_from;
2172 print STDERR "Found possible branch point: ",
2173 "$new_url => ", $self->full_url, ", $r\n";
2174 $branch_from =~ s#^/##;
2175 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2176 unless ($gs) {
2177 my $ref_id = $self->{ref_id};
2178 $ref_id =~ s/\@\d+$//;
2179 $ref_id .= "\@$r";
2180 # just grow a tail if we're not unique enough :x
2181 $ref_id .= '-' while find_ref($ref_id);
2182 print STDERR "Initializing parent: $ref_id\n";
2183 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
2185 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2186 if (!defined $r0 || !defined $parent) {
2187 my ($base, $head) = parse_revision_argument(0, $r);
2188 if ($base <= $r) {
2189 $gs->fetch($base, $r);
2191 ($r0, $parent) = $gs->last_rev_commit;
2193 if (defined $r0 && defined $parent) {
2194 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2195 my $ed;
2196 if ($self->ra->can_do_switch) {
2197 $self->assert_index_clean($parent);
2198 print STDERR "Following parent with do_switch\n";
2199 # do_switch works with svn/trunk >= r22312, but that
2200 # is not included with SVN 1.4.3 (the latest version
2201 # at the moment), so we can't rely on it
2202 $self->{last_commit} = $parent;
2203 $ed = SVN::Git::Fetcher->new($self);
2204 $gs->ra->gs_do_switch($r0, $rev, $gs,
2205 $self->full_url, $ed)
2206 or die "SVN connection failed somewhere...\n";
2207 } elsif ($self->ra->trees_match($new_url, $r0,
2208 $self->full_url, $rev)) {
2209 print STDERR "Trees match:\n",
2210 " $new_url\@$r0\n",
2211 " ${\$self->full_url}\@$rev\n",
2212 "Following parent with no changes\n";
2213 $self->tmp_index_do(sub {
2214 command_noisy('read-tree', $parent);
2216 $self->{last_commit} = $parent;
2217 } else {
2218 print STDERR "Following parent with do_update\n";
2219 $ed = SVN::Git::Fetcher->new($self);
2220 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2221 or die "SVN connection failed somewhere...\n";
2223 print STDERR "Successfully followed parent\n";
2224 return $self->make_log_entry($rev, [$parent], $ed);
2226 return undef;
2229 sub do_fetch {
2230 my ($self, $paths, $rev) = @_;
2231 my $ed;
2232 my ($last_rev, @parents);
2233 if (my $lc = $self->last_commit) {
2234 # we can have a branch that was deleted, then re-added
2235 # under the same name but copied from another path, in
2236 # which case we'll have multiple parents (we don't
2237 # want to break the original ref, nor lose copypath info):
2238 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2239 push @{$log_entry->{parents}}, $lc;
2240 return $log_entry;
2242 $ed = SVN::Git::Fetcher->new($self);
2243 $last_rev = $self->{last_rev};
2244 $ed->{c} = $lc;
2245 @parents = ($lc);
2246 } else {
2247 $last_rev = $rev;
2248 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2249 return $log_entry;
2251 $ed = SVN::Git::Fetcher->new($self);
2253 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2254 die "SVN connection failed somewhere...\n";
2256 $self->make_log_entry($rev, \@parents, $ed);
2259 sub get_untracked {
2260 my ($self, $ed) = @_;
2261 my @out;
2262 my $h = $ed->{empty};
2263 foreach (sort keys %$h) {
2264 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2265 push @out, " $act: " . uri_encode($_);
2266 warn "W: $act: $_\n";
2268 foreach my $t (qw/dir_prop file_prop/) {
2269 $h = $ed->{$t} or next;
2270 foreach my $path (sort keys %$h) {
2271 my $ppath = $path eq '' ? '.' : $path;
2272 foreach my $prop (sort keys %{$h->{$path}}) {
2273 next if $SKIP_PROP{$prop};
2274 my $v = $h->{$path}->{$prop};
2275 my $t_ppath_prop = "$t: " .
2276 uri_encode($ppath) . ' ' .
2277 uri_encode($prop);
2278 if (defined $v) {
2279 push @out, " +$t_ppath_prop " .
2280 uri_encode($v);
2281 } else {
2282 push @out, " -$t_ppath_prop";
2287 foreach my $t (qw/absent_file absent_directory/) {
2288 $h = $ed->{$t} or next;
2289 foreach my $parent (sort keys %$h) {
2290 foreach my $path (sort @{$h->{$parent}}) {
2291 push @out, " $t: " .
2292 uri_encode("$parent/$path");
2293 warn "W: $t: $parent/$path ",
2294 "Insufficient permissions?\n";
2298 \@out;
2301 sub parse_svn_date {
2302 my $date = shift || return '+0000 1970-01-01 00:00:00';
2303 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2304 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2305 croak "Unable to parse date: $date\n";
2306 "+0000 $Y-$m-$d $H:$M:$S";
2309 sub check_author {
2310 my ($author) = @_;
2311 if (!defined $author || length $author == 0) {
2312 $author = '(no author)';
2314 if (defined $::_authors && ! defined $::users{$author}) {
2315 die "Author: $author not defined in $::_authors file\n";
2317 $author;
2320 sub make_log_entry {
2321 my ($self, $rev, $parents, $ed) = @_;
2322 my $untracked = $self->get_untracked($ed);
2324 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2325 print $un "r$rev\n" or croak $!;
2326 print $un $_, "\n" foreach @$untracked;
2327 my %log_entry = ( parents => $parents || [], revision => $rev,
2328 log => '');
2330 my $headrev;
2331 my $logged = delete $self->{logged_rev_props};
2332 if (!$logged || $self->{-want_revprops}) {
2333 my $rp = $self->ra->rev_proplist($rev);
2334 foreach (sort keys %$rp) {
2335 my $v = $rp->{$_};
2336 if (/^svn:(author|date|log)$/) {
2337 $log_entry{$1} = $v;
2338 } elsif ($_ eq 'svm:headrev') {
2339 $headrev = $v;
2340 } else {
2341 print $un " rev_prop: ", uri_encode($_), ' ',
2342 uri_encode($v), "\n";
2345 } else {
2346 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2348 close $un or croak $!;
2350 $log_entry{date} = parse_svn_date($log_entry{date});
2351 $log_entry{log} .= "\n";
2352 my $author = $log_entry{author} = check_author($log_entry{author});
2353 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2354 : ($author, undef);
2355 if (defined $headrev && $self->use_svm_props) {
2356 if ($self->rewrite_root) {
2357 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2358 "options set!\n";
2360 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2361 # we don't want "SVM: initializing mirror for junk" ...
2362 return undef if $r == 0;
2363 my $svm = $self->svm;
2364 if ($uuid ne $svm->{uuid}) {
2365 die "UUID mismatch on SVM path:\n",
2366 "expected: $svm->{uuid}\n",
2367 " got: $uuid\n";
2369 my $full_url = $self->full_url;
2370 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2371 die "Failed to replace '$svm->{replace}' with ",
2372 "'$svm->{source}' in $full_url\n";
2373 # throw away username for storing in records
2374 remove_username($full_url);
2375 $log_entry{metadata} = "$full_url\@$r $uuid";
2376 $log_entry{svm_revision} = $r;
2377 $email ||= "$author\@$uuid"
2378 } elsif ($self->use_svnsync_props) {
2379 my $full_url = $self->svnsync->{url};
2380 $full_url .= "/$self->{path}" if length $self->{path};
2381 remove_username($full_url);
2382 my $uuid = $self->svnsync->{uuid};
2383 $log_entry{metadata} = "$full_url\@$rev $uuid";
2384 $email ||= "$author\@$uuid"
2385 } else {
2386 my $url = $self->metadata_url;
2387 remove_username($url);
2388 $log_entry{metadata} = "$url\@$rev " .
2389 $self->ra->get_uuid;
2390 $email ||= "$author\@" . $self->ra->get_uuid;
2392 $log_entry{name} = $name;
2393 $log_entry{email} = $email;
2394 \%log_entry;
2397 sub fetch {
2398 my ($self, $min_rev, $max_rev, @parents) = @_;
2399 my ($last_rev, $last_commit) = $self->last_rev_commit;
2400 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2401 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2404 sub set_tree_cb {
2405 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2406 $self->{inject_parents} = { $rev => $tree };
2407 $self->fetch(undef, undef);
2410 sub set_tree {
2411 my ($self, $tree) = (shift, shift);
2412 my $log_entry = ::get_commit_entry($tree);
2413 unless ($self->{last_rev}) {
2414 fatal("Must have an existing revision to commit");
2416 my %ed_opts = ( r => $self->{last_rev},
2417 log => $log_entry->{log},
2418 ra => $self->ra,
2419 tree_a => $self->{last_commit},
2420 tree_b => $tree,
2421 editor_cb => sub {
2422 $self->set_tree_cb($log_entry, $tree, @_) },
2423 svn_path => $self->{path} );
2424 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2425 print "No changes\nr$self->{last_rev} = $tree\n";
2429 sub rebuild {
2430 my ($self) = @_;
2431 my $db_path = $self->db_path;
2432 return if (-e $db_path && ! -z $db_path);
2433 return unless ::verify_ref($self->refname.'^0');
2434 if (-f $self->{db_root}) {
2435 rename $self->{db_root}, $db_path or die
2436 "rename $self->{db_root} => $db_path failed: $!\n";
2437 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2438 symlink $base, $self->{db_root} or die
2439 "symlink $base => $self->{db_root} failed: $!\n";
2440 return;
2442 print "Rebuilding $db_path ...\n";
2443 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2444 my $latest;
2445 my $full_url = $self->full_url;
2446 remove_username($full_url);
2447 my $svn_uuid;
2448 my $c;
2449 while (<$log>) {
2450 if ( m{^commit ($::sha1)$} ) {
2451 $c = $1;
2452 next;
2454 next unless s{^\s*(git-svn-id:)}{$1};
2455 my ($url, $rev, $uuid) = ::extract_metadata($_);
2456 remove_username($url);
2458 # ignore merges (from set-tree)
2459 next if (!defined $rev || !$uuid);
2461 # if we merged or otherwise started elsewhere, this is
2462 # how we break out of it
2463 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2464 ($full_url && $url && ($url ne $full_url))) {
2465 next;
2467 $latest ||= $rev;
2468 $svn_uuid ||= $uuid;
2470 $self->rev_db_set($rev, $c);
2471 print "r$rev = $c\n";
2473 command_close_pipe($log, $ctx);
2474 print "Done rebuilding $db_path\n";
2477 # rev_db:
2478 # Tie::File seems to be prone to offset errors if revisions get sparse,
2479 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2480 # one of my favorite modules is out :< Next up would be one of the DBM
2481 # modules, but I'm not sure which is most portable... So I'll just
2482 # go with something that's plain-text, but still capable of
2483 # being randomly accessed. So here's my ultra-simple fixed-width
2484 # database. All records are 40 characters + "\n", so it's easy to seek
2485 # to a revision: (41 * rev) is the byte offset.
2486 # A record of 40 0s denotes an empty revision.
2487 # And yes, it's still pretty fast (faster than Tie::File).
2488 # These files are disposable unless noMetadata or useSvmProps is set
2490 sub _rev_db_set {
2491 my ($fh, $rev, $commit) = @_;
2492 my $offset = $rev * 41;
2493 # assume that append is the common case:
2494 seek $fh, 0, 2 or croak $!;
2495 my $pos = tell $fh;
2496 if ($pos < $offset) {
2497 for (1 .. (($offset - $pos) / 41)) {
2498 print $fh (('0' x 40),"\n") or croak $!;
2501 seek $fh, $offset, 0 or croak $!;
2502 print $fh $commit,"\n" or croak $!;
2505 sub mkfile {
2506 my ($path) = @_;
2507 unless (-e $path) {
2508 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2509 mkpath([$dir]) unless -d $dir;
2510 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2511 close $fh or die "Couldn't close (create) $path: $!\n";
2515 sub rev_db_set {
2516 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2517 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2518 my $db = $self->db_path($uuid);
2519 my $db_lock = "$db.lock";
2520 my $sig;
2521 if ($update_ref) {
2522 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2523 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2525 mkfile($db);
2527 $LOCKFILES{$db_lock} = 1;
2528 my $sync;
2529 # both of these options make our .rev_db file very, very important
2530 # and we can't afford to lose it because rebuild() won't work
2531 if ($self->use_svm_props || $self->no_metadata) {
2532 $sync = 1;
2533 copy($db, $db_lock) or die "rev_db_set(@_): ",
2534 "Failed to copy: ",
2535 "$db => $db_lock ($!)\n";
2536 } else {
2537 rename $db, $db_lock or die "rev_db_set(@_): ",
2538 "Failed to rename: ",
2539 "$db => $db_lock ($!)\n";
2541 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2542 _rev_db_set($fh, $rev, $commit);
2543 if ($sync) {
2544 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2545 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2547 close $fh or croak $!;
2548 if ($update_ref) {
2549 $_head = $self;
2550 command_noisy('update-ref', '-m', "r$rev",
2551 $self->refname, $commit);
2553 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2554 "$db_lock => $db ($!)\n";
2555 delete $LOCKFILES{$db_lock};
2556 if ($update_ref) {
2557 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2558 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2559 kill $sig, $$ if defined $sig;
2563 sub rev_db_max {
2564 my ($self) = @_;
2565 $self->rebuild;
2566 my $db_path = $self->db_path;
2567 my @stat = stat $db_path or return 0;
2568 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2569 my $max = $stat[7] / 41;
2570 (($max > 0) ? $max - 1 : 0);
2573 sub rev_db_get {
2574 my ($self, $rev, $uuid) = @_;
2575 my $ret;
2576 my $offset = $rev * 41;
2577 my $db_path = $self->db_path($uuid);
2578 return undef unless -e $db_path;
2579 open my $fh, '<', $db_path or croak $!;
2580 if (sysseek($fh, $offset, 0) == $offset) {
2581 my $read = sysread($fh, $ret, 40);
2582 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2584 close $fh or croak $!;
2585 $ret;
2588 # Finds the first svn revision that exists on (if $eq_ok is true) or
2589 # before $rev for the current branch. It will not search any lower
2590 # than $min_rev. Returns the git commit hash and svn revision number
2591 # if found, else (undef, undef).
2592 sub find_rev_before {
2593 my ($self, $rev, $eq_ok, $min_rev) = @_;
2594 --$rev unless $eq_ok;
2595 $min_rev ||= 1;
2596 while ($rev >= $min_rev) {
2597 if (my $c = $self->rev_db_get($rev)) {
2598 return ($rev, $c);
2600 --$rev;
2602 return (undef, undef);
2605 # Finds the first svn revision that exists on (if $eq_ok is true) or
2606 # after $rev for the current branch. It will not search any higher
2607 # than $max_rev. Returns the git commit hash and svn revision number
2608 # if found, else (undef, undef).
2609 sub find_rev_after {
2610 my ($self, $rev, $eq_ok, $max_rev) = @_;
2611 ++$rev unless $eq_ok;
2612 $max_rev ||= $self->rev_db_max();
2613 while ($rev <= $max_rev) {
2614 if (my $c = $self->rev_db_get($rev)) {
2615 return ($rev, $c);
2617 ++$rev;
2619 return (undef, undef);
2622 sub _new {
2623 my ($class, $repo_id, $ref_id, $path) = @_;
2624 unless (defined $repo_id && length $repo_id) {
2625 $repo_id = $Git::SVN::default_repo_id;
2627 unless (defined $ref_id && length $ref_id) {
2628 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2630 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2631 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2632 $_[3] = $path = '' unless (defined $path);
2633 mkpath(["$ENV{GIT_DIR}/svn"]);
2634 bless {
2635 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2636 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2637 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2640 sub db_path {
2641 my ($self, $uuid) = @_;
2642 $uuid ||= $self->ra_uuid;
2643 "$self->{db_root}.$uuid";
2646 sub uri_encode {
2647 my ($f) = @_;
2648 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2652 sub remove_username {
2653 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2656 package Git::SVN::Prompt;
2657 use strict;
2658 use warnings;
2659 require SVN::Core;
2660 use vars qw/$_no_auth_cache $_username/;
2662 sub simple {
2663 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2664 $may_save = undef if $_no_auth_cache;
2665 $default_username = $_username if defined $_username;
2666 if (defined $default_username && length $default_username) {
2667 if (defined $realm && length $realm) {
2668 print STDERR "Authentication realm: $realm\n";
2669 STDERR->flush;
2671 $cred->username($default_username);
2672 } else {
2673 username($cred, $realm, $may_save, $pool);
2675 $cred->password(_read_password("Password for '" .
2676 $cred->username . "': ", $realm));
2677 $cred->may_save($may_save);
2678 $SVN::_Core::SVN_NO_ERROR;
2681 sub ssl_server_trust {
2682 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2683 $may_save = undef if $_no_auth_cache;
2684 print STDERR "Error validating server certificate for '$realm':\n";
2686 no warnings 'once';
2687 # All variables SVN::Auth::SSL::* are used only once,
2688 # so we're shutting up Perl warnings about this.
2689 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2690 print STDERR " - The certificate is not issued ",
2691 "by a trusted authority. Use the\n",
2692 " fingerprint to validate ",
2693 "the certificate manually!\n";
2695 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2696 print STDERR " - The certificate hostname ",
2697 "does not match.\n";
2699 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2700 print STDERR " - The certificate is not yet valid.\n";
2702 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2703 print STDERR " - The certificate has expired.\n";
2705 if ($failures & $SVN::Auth::SSL::OTHER) {
2706 print STDERR " - The certificate has ",
2707 "an unknown error.\n";
2709 } # no warnings 'once'
2710 printf STDERR
2711 "Certificate information:\n".
2712 " - Hostname: %s\n".
2713 " - Valid: from %s until %s\n".
2714 " - Issuer: %s\n".
2715 " - Fingerprint: %s\n",
2716 map $cert_info->$_, qw(hostname valid_from valid_until
2717 issuer_dname fingerprint);
2718 my $choice;
2719 prompt:
2720 print STDERR $may_save ?
2721 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2722 "(R)eject or accept (t)emporarily? ";
2723 STDERR->flush;
2724 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2725 if ($choice =~ /^t$/i) {
2726 $cred->may_save(undef);
2727 } elsif ($choice =~ /^r$/i) {
2728 return -1;
2729 } elsif ($may_save && $choice =~ /^p$/i) {
2730 $cred->may_save($may_save);
2731 } else {
2732 goto prompt;
2734 $cred->accepted_failures($failures);
2735 $SVN::_Core::SVN_NO_ERROR;
2738 sub ssl_client_cert {
2739 my ($cred, $realm, $may_save, $pool) = @_;
2740 $may_save = undef if $_no_auth_cache;
2741 print STDERR "Client certificate filename: ";
2742 STDERR->flush;
2743 chomp(my $filename = <STDIN>);
2744 $cred->cert_file($filename);
2745 $cred->may_save($may_save);
2746 $SVN::_Core::SVN_NO_ERROR;
2749 sub ssl_client_cert_pw {
2750 my ($cred, $realm, $may_save, $pool) = @_;
2751 $may_save = undef if $_no_auth_cache;
2752 $cred->password(_read_password("Password: ", $realm));
2753 $cred->may_save($may_save);
2754 $SVN::_Core::SVN_NO_ERROR;
2757 sub username {
2758 my ($cred, $realm, $may_save, $pool) = @_;
2759 $may_save = undef if $_no_auth_cache;
2760 if (defined $realm && length $realm) {
2761 print STDERR "Authentication realm: $realm\n";
2763 my $username;
2764 if (defined $_username) {
2765 $username = $_username;
2766 } else {
2767 print STDERR "Username: ";
2768 STDERR->flush;
2769 chomp($username = <STDIN>);
2771 $cred->username($username);
2772 $cred->may_save($may_save);
2773 $SVN::_Core::SVN_NO_ERROR;
2776 sub _read_password {
2777 my ($prompt, $realm) = @_;
2778 print STDERR $prompt;
2779 STDERR->flush;
2780 require Term::ReadKey;
2781 Term::ReadKey::ReadMode('noecho');
2782 my $password = '';
2783 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2784 last if $key =~ /[\012\015]/; # \n\r
2785 $password .= $key;
2787 Term::ReadKey::ReadMode('restore');
2788 print STDERR "\n";
2789 STDERR->flush;
2790 $password;
2793 package SVN::Git::Fetcher;
2794 use vars qw/@ISA/;
2795 use strict;
2796 use warnings;
2797 use Carp qw/croak/;
2798 use IO::File qw//;
2800 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2801 sub new {
2802 my ($class, $git_svn) = @_;
2803 my $self = SVN::Delta::Editor->new;
2804 bless $self, $class;
2805 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2806 $self->{empty} = {};
2807 $self->{dir_prop} = {};
2808 $self->{file_prop} = {};
2809 $self->{absent_dir} = {};
2810 $self->{absent_file} = {};
2811 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2812 $self;
2815 sub set_path_strip {
2816 my ($self, $path) = @_;
2817 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2820 sub open_root {
2821 { path => '' };
2824 sub open_directory {
2825 my ($self, $path, $pb, $rev) = @_;
2826 { path => $path };
2829 sub git_path {
2830 my ($self, $path) = @_;
2831 if ($self->{path_strip}) {
2832 $path =~ s!$self->{path_strip}!! or
2833 die "Failed to strip path '$path' ($self->{path_strip})\n";
2835 $path;
2838 sub delete_entry {
2839 my ($self, $path, $rev, $pb) = @_;
2841 my $gpath = $self->git_path($path);
2842 return undef if ($gpath eq '');
2844 # remove entire directories.
2845 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2846 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2847 -r --name-only -z/,
2848 $self->{c}, '--', $gpath);
2849 local $/ = "\0";
2850 while (<$ls>) {
2851 chomp;
2852 $self->{gii}->remove($_);
2853 print "\tD\t$_\n" unless $::_q;
2855 print "\tD\t$gpath/\n" unless $::_q;
2856 command_close_pipe($ls, $ctx);
2857 $self->{empty}->{$path} = 0
2858 } else {
2859 $self->{gii}->remove($gpath);
2860 print "\tD\t$gpath\n" unless $::_q;
2862 undef;
2865 sub open_file {
2866 my ($self, $path, $pb, $rev) = @_;
2867 my $gpath = $self->git_path($path);
2868 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2869 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2870 unless (defined $mode && defined $blob) {
2871 die "$path was not found in commit $self->{c} (r$rev)\n";
2873 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2874 pool => SVN::Pool->new, action => 'M' };
2877 sub add_file {
2878 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2879 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2880 delete $self->{empty}->{$dir};
2881 { path => $path, mode_a => 100644, mode_b => 100644,
2882 pool => SVN::Pool->new, action => 'A' };
2885 sub add_directory {
2886 my ($self, $path, $cp_path, $cp_rev) = @_;
2887 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2888 delete $self->{empty}->{$dir};
2889 $self->{empty}->{$path} = 1;
2890 { path => $path };
2893 sub change_dir_prop {
2894 my ($self, $db, $prop, $value) = @_;
2895 $self->{dir_prop}->{$db->{path}} ||= {};
2896 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2897 undef;
2900 sub absent_directory {
2901 my ($self, $path, $pb) = @_;
2902 $self->{absent_dir}->{$pb->{path}} ||= [];
2903 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2904 undef;
2907 sub absent_file {
2908 my ($self, $path, $pb) = @_;
2909 $self->{absent_file}->{$pb->{path}} ||= [];
2910 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2911 undef;
2914 sub change_file_prop {
2915 my ($self, $fb, $prop, $value) = @_;
2916 if ($prop eq 'svn:executable') {
2917 if ($fb->{mode_b} != 120000) {
2918 $fb->{mode_b} = defined $value ? 100755 : 100644;
2920 } elsif ($prop eq 'svn:special') {
2921 $fb->{mode_b} = defined $value ? 120000 : 100644;
2922 } else {
2923 $self->{file_prop}->{$fb->{path}} ||= {};
2924 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2926 undef;
2929 sub apply_textdelta {
2930 my ($self, $fb, $exp) = @_;
2931 my $fh = IO::File->new_tmpfile;
2932 $fh->autoflush(1);
2933 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2934 # (but $base does not,) so dup() it for reading in close_file
2935 open my $dup, '<&', $fh or croak $!;
2936 my $base = IO::File->new_tmpfile;
2937 $base->autoflush(1);
2938 if ($fb->{blob}) {
2939 defined (my $pid = fork) or croak $!;
2940 if (!$pid) {
2941 open STDOUT, '>&', $base or croak $!;
2942 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2943 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2945 waitpid $pid, 0;
2946 croak $? if $?;
2948 if (defined $exp) {
2949 seek $base, 0, 0 or croak $!;
2950 my $got = Git::SVN::Util::md5sum($base);
2951 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2952 "expected: $exp\n",
2953 " got: $got\n" if ($got ne $exp);
2956 seek $base, 0, 0 or croak $!;
2957 $fb->{fh} = $dup;
2958 $fb->{base} = $base;
2959 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2962 sub close_file {
2963 my ($self, $fb, $exp) = @_;
2964 my $hash;
2965 my $path = $self->git_path($fb->{path});
2966 if (my $fh = $fb->{fh}) {
2967 if (defined $exp) {
2968 seek($fh, 0, 0) or croak $!;
2969 my $got = Git::SVN::Util::md5sum($fh);
2970 if ($got ne $exp) {
2971 die "Checksum mismatch: $path\n",
2972 "expected: $exp\n got: $got\n";
2975 sysseek($fh, 0, 0) or croak $!;
2976 if ($fb->{mode_b} == 120000) {
2977 sysread($fh, my $buf, 5) == 5 or croak $!;
2978 $buf eq 'link ' or die "$path has mode 120000",
2979 "but is not a link\n";
2981 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2982 if (!$pid) {
2983 open STDIN, '<&', $fh or croak $!;
2984 exec qw/git-hash-object -w --stdin/ or croak $!;
2986 chomp($hash = do { local $/; <$out> });
2987 close $out or croak $!;
2988 close $fh or croak $!;
2989 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2990 close $fb->{base} or croak $!;
2991 } else {
2992 $hash = $fb->{blob} or die "no blob information\n";
2994 $fb->{pool}->clear;
2995 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2996 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2997 undef;
3000 sub abort_edit {
3001 my $self = shift;
3002 $self->{nr} = $self->{gii}->{nr};
3003 delete $self->{gii};
3004 $self->SUPER::abort_edit(@_);
3007 sub close_edit {
3008 my $self = shift;
3009 $self->{git_commit_ok} = 1;
3010 $self->{nr} = $self->{gii}->{nr};
3011 delete $self->{gii};
3012 $self->SUPER::close_edit(@_);
3015 package SVN::Git::Editor;
3016 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3017 use strict;
3018 use warnings;
3019 use Carp qw/croak/;
3020 use IO::File;
3022 sub new {
3023 my ($class, $opts) = @_;
3024 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3025 die "$_ required!\n" unless (defined $opts->{$_});
3028 my $pool = SVN::Pool->new;
3029 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3030 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3031 $opts->{r}, $mods);
3033 # $opts->{ra} functions should not be used after this:
3034 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3035 $opts->{editor_cb}, $pool);
3036 my $self = SVN::Delta::Editor->new(@ce, $pool);
3037 bless $self, $class;
3038 foreach (qw/svn_path r tree_a tree_b/) {
3039 $self->{$_} = $opts->{$_};
3041 $self->{url} = $opts->{ra}->{url};
3042 $self->{mods} = $mods;
3043 $self->{types} = $types;
3044 $self->{pool} = $pool;
3045 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3046 $self->{rm} = { };
3047 $self->{path_prefix} = length $self->{svn_path} ?
3048 "$self->{svn_path}/" : '';
3049 return $self;
3052 sub generate_diff {
3053 my ($tree_a, $tree_b) = @_;
3054 my @diff_tree = qw(diff-tree -z -r);
3055 if ($_cp_similarity) {
3056 push @diff_tree, "-C$_cp_similarity";
3057 } else {
3058 push @diff_tree, '-C';
3060 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3061 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3062 push @diff_tree, $tree_a, $tree_b;
3063 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3064 local $/ = "\0";
3065 my $state = 'meta';
3066 my @mods;
3067 while (<$diff_fh>) {
3068 chomp $_; # this gets rid of the trailing "\0"
3069 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3070 $::sha1\s($::sha1)\s
3071 ([MTCRAD])\d*$/xo) {
3072 push @mods, { mode_a => $1, mode_b => $2,
3073 sha1_b => $3, chg => $4 };
3074 if ($4 =~ /^(?:C|R)$/) {
3075 $state = 'file_a';
3076 } else {
3077 $state = 'file_b';
3079 } elsif ($state eq 'file_a') {
3080 my $x = $mods[$#mods] or croak "Empty array\n";
3081 if ($x->{chg} !~ /^(?:C|R)$/) {
3082 croak "Error parsing $_, $x->{chg}\n";
3084 $x->{file_a} = $_;
3085 $state = 'file_b';
3086 } elsif ($state eq 'file_b') {
3087 my $x = $mods[$#mods] or croak "Empty array\n";
3088 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3089 croak "Error parsing $_, $x->{chg}\n";
3091 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3092 croak "Error parsing $_, $x->{chg}\n";
3094 $x->{file_b} = $_;
3095 $state = 'meta';
3096 } else {
3097 croak "Error parsing $_\n";
3100 command_close_pipe($diff_fh, $ctx);
3101 \@mods;
3104 sub check_diff_paths {
3105 my ($ra, $pfx, $rev, $mods) = @_;
3106 my %types;
3107 $pfx .= '/' if length $pfx;
3109 sub type_diff_paths {
3110 my ($ra, $types, $path, $rev) = @_;
3111 my @p = split m#/+#, $path;
3112 my $c = shift @p;
3113 unless (defined $types->{$c}) {
3114 $types->{$c} = $ra->check_path($c, $rev);
3116 while (@p) {
3117 $c .= '/' . shift @p;
3118 next if defined $types->{$c};
3119 $types->{$c} = $ra->check_path($c, $rev);
3123 foreach my $m (@$mods) {
3124 foreach my $f (qw/file_a file_b/) {
3125 next unless defined $m->{$f};
3126 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3127 if (length $pfx.$dir && ! defined $types{$dir}) {
3128 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3132 \%types;
3135 sub split_path {
3136 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3139 sub repo_path {
3140 my ($self, $path) = @_;
3141 $self->{path_prefix}.(defined $path ? $path : '');
3144 sub url_path {
3145 my ($self, $path) = @_;
3146 if ($self->{url} =~ m#^https?://#) {
3147 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3149 $self->{url} . '/' . $self->repo_path($path);
3152 sub rmdirs {
3153 my ($self) = @_;
3154 my $rm = $self->{rm};
3155 delete $rm->{''}; # we never delete the url we're tracking
3156 return unless %$rm;
3158 foreach (keys %$rm) {
3159 my @d = split m#/#, $_;
3160 my $c = shift @d;
3161 $rm->{$c} = 1;
3162 while (@d) {
3163 $c .= '/' . shift @d;
3164 $rm->{$c} = 1;
3167 delete $rm->{$self->{svn_path}};
3168 delete $rm->{''}; # we never delete the url we're tracking
3169 return unless %$rm;
3171 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3172 $self->{tree_b});
3173 local $/ = "\0";
3174 while (<$fh>) {
3175 chomp;
3176 my @dn = split m#/#, $_;
3177 while (pop @dn) {
3178 delete $rm->{join '/', @dn};
3180 unless (%$rm) {
3181 close $fh;
3182 return;
3185 command_close_pipe($fh, $ctx);
3187 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3188 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3189 $self->close_directory($bat->{$d}, $p);
3190 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3191 print "\tD+\t$d/\n" unless $::_q;
3192 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3193 delete $bat->{$d};
3197 sub open_or_add_dir {
3198 my ($self, $full_path, $baton) = @_;
3199 my $t = $self->{types}->{$full_path};
3200 if (!defined $t) {
3201 die "$full_path not known in r$self->{r} or we have a bug!\n";
3204 no warnings 'once';
3205 # SVN::Node::none and SVN::Node::file are used only once,
3206 # so we're shutting up Perl's warnings about them.
3207 if ($t == $SVN::Node::none) {
3208 return $self->add_directory($full_path, $baton,
3209 undef, -1, $self->{pool});
3210 } elsif ($t == $SVN::Node::dir) {
3211 return $self->open_directory($full_path, $baton,
3212 $self->{r}, $self->{pool});
3213 } # no warnings 'once'
3214 print STDERR "$full_path already exists in repository at ",
3215 "r$self->{r} and it is not a directory (",
3216 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3217 } # no warnings 'once'
3218 exit 1;
3221 sub ensure_path {
3222 my ($self, $path) = @_;
3223 my $bat = $self->{bat};
3224 my $repo_path = $self->repo_path($path);
3225 return $bat->{''} unless (length $repo_path);
3226 my @p = split m#/+#, $repo_path;
3227 my $c = shift @p;
3228 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3229 while (@p) {
3230 my $c0 = $c;
3231 $c .= '/' . shift @p;
3232 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3234 return $bat->{$c};
3237 sub A {
3238 my ($self, $m) = @_;
3239 my ($dir, $file) = split_path($m->{file_b});
3240 my $pbat = $self->ensure_path($dir);
3241 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3242 undef, -1);
3243 print "\tA\t$m->{file_b}\n" unless $::_q;
3244 $self->chg_file($fbat, $m);
3245 $self->close_file($fbat,undef,$self->{pool});
3248 sub C {
3249 my ($self, $m) = @_;
3250 my ($dir, $file) = split_path($m->{file_b});
3251 my $pbat = $self->ensure_path($dir);
3252 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3253 $self->url_path($m->{file_a}), $self->{r});
3254 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3255 $self->chg_file($fbat, $m);
3256 $self->close_file($fbat,undef,$self->{pool});
3259 sub delete_entry {
3260 my ($self, $path, $pbat) = @_;
3261 my $rpath = $self->repo_path($path);
3262 my ($dir, $file) = split_path($rpath);
3263 $self->{rm}->{$dir} = 1;
3264 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3267 sub R {
3268 my ($self, $m) = @_;
3269 my ($dir, $file) = split_path($m->{file_b});
3270 my $pbat = $self->ensure_path($dir);
3271 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3272 $self->url_path($m->{file_a}), $self->{r});
3273 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3274 $self->chg_file($fbat, $m);
3275 $self->close_file($fbat,undef,$self->{pool});
3277 ($dir, $file) = split_path($m->{file_a});
3278 $pbat = $self->ensure_path($dir);
3279 $self->delete_entry($m->{file_a}, $pbat);
3282 sub M {
3283 my ($self, $m) = @_;
3284 my ($dir, $file) = split_path($m->{file_b});
3285 my $pbat = $self->ensure_path($dir);
3286 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3287 $pbat,$self->{r},$self->{pool});
3288 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3289 $self->chg_file($fbat, $m);
3290 $self->close_file($fbat,undef,$self->{pool});
3293 sub T { shift->M(@_) }
3295 sub change_file_prop {
3296 my ($self, $fbat, $pname, $pval) = @_;
3297 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3300 sub chg_file {
3301 my ($self, $fbat, $m) = @_;
3302 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3303 $self->change_file_prop($fbat,'svn:executable','*');
3304 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3305 $self->change_file_prop($fbat,'svn:executable',undef);
3307 my $fh = IO::File->new_tmpfile or croak $!;
3308 if ($m->{mode_b} =~ /^120/) {
3309 print $fh 'link ' or croak $!;
3310 $self->change_file_prop($fbat,'svn:special','*');
3311 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3312 $self->change_file_prop($fbat,'svn:special',undef);
3314 defined(my $pid = fork) or croak $!;
3315 if (!$pid) {
3316 open STDOUT, '>&', $fh or croak $!;
3317 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3319 waitpid $pid, 0;
3320 croak $? if $?;
3321 $fh->flush == 0 or croak $!;
3322 seek $fh, 0, 0 or croak $!;
3324 my $exp = Git::SVN::Util::md5sum($fh);
3325 seek $fh, 0, 0 or croak $!;
3327 my $pool = SVN::Pool->new;
3328 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3329 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3330 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3331 $pool->clear;
3333 close $fh or croak $!;
3336 sub D {
3337 my ($self, $m) = @_;
3338 my ($dir, $file) = split_path($m->{file_b});
3339 my $pbat = $self->ensure_path($dir);
3340 print "\tD\t$m->{file_b}\n" unless $::_q;
3341 $self->delete_entry($m->{file_b}, $pbat);
3344 sub close_edit {
3345 my ($self) = @_;
3346 my ($p,$bat) = ($self->{pool}, $self->{bat});
3347 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3348 next if $_ eq '';
3349 $self->close_directory($bat->{$_}, $p);
3351 $self->close_directory($bat->{''}, $p);
3352 $self->SUPER::close_edit($p);
3353 $p->clear;
3356 sub abort_edit {
3357 my ($self) = @_;
3358 $self->SUPER::abort_edit($self->{pool});
3361 sub DESTROY {
3362 my $self = shift;
3363 $self->SUPER::DESTROY(@_);
3364 $self->{pool}->clear;
3367 # this drives the editor
3368 sub apply_diff {
3369 my ($self) = @_;
3370 my $mods = $self->{mods};
3371 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3372 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3373 my $f = $m->{chg};
3374 if (defined $o{$f}) {
3375 $self->$f($m);
3376 } else {
3377 fatal("Invalid change type: $f");
3380 $self->rmdirs if $_rmdir;
3381 if (@$mods == 0) {
3382 $self->abort_edit;
3383 } else {
3384 $self->close_edit;
3386 return scalar @$mods;
3389 package Git::SVN::Ra;
3390 use vars qw/@ISA $config_dir $_log_window_size/;
3391 use strict;
3392 use warnings;
3393 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3395 BEGIN {
3396 # enforce temporary pool usage for some simple functions
3397 no strict 'refs';
3398 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3399 my $SUPER = "SUPER::$f";
3400 *$f = sub {
3401 my $self = shift;
3402 my $pool = SVN::Pool->new;
3403 my @ret = $self->$SUPER(@_,$pool);
3404 $pool->clear;
3405 wantarray ? @ret : $ret[0];
3410 sub _auth_providers () {
3412 SVN::Client::get_simple_provider(),
3413 SVN::Client::get_ssl_server_trust_file_provider(),
3414 SVN::Client::get_simple_prompt_provider(
3415 \&Git::SVN::Prompt::simple, 2),
3416 SVN::Client::get_ssl_client_cert_file_provider(),
3417 SVN::Client::get_ssl_client_cert_prompt_provider(
3418 \&Git::SVN::Prompt::ssl_client_cert, 2),
3419 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3420 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3421 SVN::Client::get_username_provider(),
3422 SVN::Client::get_ssl_server_trust_prompt_provider(
3423 \&Git::SVN::Prompt::ssl_server_trust),
3424 SVN::Client::get_username_prompt_provider(
3425 \&Git::SVN::Prompt::username, 2)
3429 sub escape_uri_only {
3430 my ($uri) = @_;
3431 my @tmp;
3432 foreach (split m{/}, $uri) {
3433 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3434 push @tmp, $_;
3436 join('/', @tmp);
3439 sub escape_url {
3440 my ($url) = @_;
3441 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3442 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3443 $url = "$scheme://$domain$uri";
3445 $url;
3448 sub new {
3449 my ($class, $url) = @_;
3450 $url =~ s!/+$!!;
3451 return $RA if ($RA && $RA->{url} eq $url);
3453 SVN::_Core::svn_config_ensure($config_dir, undef);
3454 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3455 my $config = SVN::Core::config_get_config($config_dir);
3456 $RA = undef;
3457 my $dont_store_passwords = 1;
3458 my $conf_t = ${$config}{'config'};
3460 no warnings 'once';
3461 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3462 # produces warnings that variables are used only once.
3463 # I had not found the better way to shut them up, so
3464 # the warnings of type 'once' are disabled in this block.
3465 if (SVN::_Core::svn_config_get_bool($conf_t,
3466 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3467 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3468 1) == 0) {
3469 SVN::_Core::svn_auth_set_parameter($baton,
3470 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3471 bless (\$dont_store_passwords, "_p_void"));
3473 if (SVN::_Core::svn_config_get_bool($conf_t,
3474 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3475 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3476 1) == 0) {
3477 $Git::SVN::Prompt::_no_auth_cache = 1;
3479 } # no warnings 'once'
3480 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3481 config => $config,
3482 pool => SVN::Pool->new,
3483 auth_provider_callbacks => $callbacks);
3484 $self->{url} = $url;
3485 $self->{svn_path} = $url;
3486 $self->{repos_root} = $self->get_repos_root;
3487 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3488 $self->{cache} = { check_path => { r => 0, data => {} },
3489 get_dir => { r => 0, data => {} } };
3490 $RA = bless $self, $class;
3493 sub check_path {
3494 my ($self, $path, $r) = @_;
3495 my $cache = $self->{cache}->{check_path};
3496 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3497 return $cache->{data}->{$path};
3499 my $pool = SVN::Pool->new;
3500 my $t = $self->SUPER::check_path($path, $r, $pool);
3501 $pool->clear;
3502 if ($r != $cache->{r}) {
3503 %{$cache->{data}} = ();
3504 $cache->{r} = $r;
3506 $cache->{data}->{$path} = $t;
3509 sub get_dir {
3510 my ($self, $dir, $r) = @_;
3511 my $cache = $self->{cache}->{get_dir};
3512 if ($r == $cache->{r}) {
3513 if (my $x = $cache->{data}->{$dir}) {
3514 return wantarray ? @$x : $x->[0];
3517 my $pool = SVN::Pool->new;
3518 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3519 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3520 $pool->clear;
3521 if ($r != $cache->{r}) {
3522 %{$cache->{data}} = ();
3523 $cache->{r} = $r;
3525 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3526 wantarray ? (\%dirents, $r, $props) : \%dirents;
3529 sub DESTROY {
3530 # do not call the real DESTROY since we store ourselves in $RA
3533 sub get_log {
3534 my ($self, @args) = @_;
3535 my $pool = SVN::Pool->new;
3536 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3537 my $ret = $self->SUPER::get_log(@args, $pool);
3538 $pool->clear;
3539 $ret;
3542 sub trees_match {
3543 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3544 my $ctx = SVN::Client->new(auth => _auth_providers);
3545 my $out = IO::File->new_tmpfile;
3547 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3548 # $ctx->diff(), so we'll create a default one
3549 my $pool = SVN::Pool->new_default_sub;
3551 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3552 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3553 $out->flush;
3554 my $ret = (($out->stat)[7] == 0);
3555 close $out or croak $!;
3557 $ret;
3560 sub get_commit_editor {
3561 my ($self, $log, $cb, $pool) = @_;
3562 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3563 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3566 sub gs_do_update {
3567 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3568 my $new = ($rev_a == $rev_b);
3569 my $path = $gs->{path};
3571 if ($new && -e $gs->{index}) {
3572 unlink $gs->{index} or die
3573 "Couldn't unlink index: $gs->{index}: $!\n";
3575 my $pool = SVN::Pool->new;
3576 $editor->set_path_strip($path);
3577 my (@pc) = split m#/#, $path;
3578 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3579 1, $editor, $pool);
3580 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3582 # Since we can't rely on svn_ra_reparent being available, we'll
3583 # just have to do some magic with set_path to make it so
3584 # we only want a partial path.
3585 my $sp = '';
3586 my $final = join('/', @pc);
3587 while (@pc) {
3588 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3589 $sp .= '/' if length $sp;
3590 $sp .= shift @pc;
3592 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3594 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3596 $reporter->finish_report($pool);
3597 $pool->clear;
3598 $editor->{git_commit_ok};
3601 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3602 # svn_ra_reparent didn't work before 1.4)
3603 sub gs_do_switch {
3604 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3605 my $path = $gs->{path};
3606 my $pool = SVN::Pool->new;
3608 my $full_url = $self->{url};
3609 my $old_url = $full_url;
3610 $full_url .= '/' . escape_uri_only($path) if length $path;
3611 my ($ra, $reparented);
3612 if ($old_url ne $full_url) {
3613 if ($old_url !~ m#^svn(\+ssh)?://#) {
3614 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3615 $pool);
3616 $self->{url} = $full_url;
3617 $reparented = 1;
3618 } else {
3619 $_[0] = undef;
3620 $self = undef;
3621 $RA = undef;
3622 $ra = Git::SVN::Ra->new($full_url);
3623 $ra_invalid = 1;
3626 $ra ||= $self;
3627 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3628 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3629 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3630 $reporter->finish_report($pool);
3632 if ($reparented) {
3633 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3634 $self->{url} = $old_url;
3637 $pool->clear;
3638 $editor->{git_commit_ok};
3641 sub longest_common_path {
3642 my ($gsv, $globs) = @_;
3643 my %common;
3644 my $common_max = scalar @$gsv;
3646 foreach my $gs (@$gsv) {
3647 my @tmp = split m#/#, $gs->{path};
3648 my $p = '';
3649 foreach (@tmp) {
3650 $p .= length($p) ? "/$_" : $_;
3651 $common{$p} ||= 0;
3652 $common{$p}++;
3655 $globs ||= [];
3656 $common_max += scalar @$globs;
3657 foreach my $glob (@$globs) {
3658 my @tmp = split m#/#, $glob->{path}->{left};
3659 my $p = '';
3660 foreach (@tmp) {
3661 $p .= length($p) ? "/$_" : $_;
3662 $common{$p} ||= 0;
3663 $common{$p}++;
3667 my $longest_path = '';
3668 foreach (sort {length $b <=> length $a} keys %common) {
3669 if ($common{$_} == $common_max) {
3670 $longest_path = $_;
3671 last;
3674 $longest_path;
3677 sub gs_fetch_loop_common {
3678 my ($self, $base, $head, $gsv, $globs) = @_;
3679 return if ($base > $head);
3680 my $inc = $_log_window_size;
3681 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3682 my $longest_path = longest_common_path($gsv, $globs);
3683 my $ra_url = $self->{url};
3684 while (1) {
3685 my %revs;
3686 my $err;
3687 my $err_handler = $SVN::Error::handler;
3688 $SVN::Error::handler = sub {
3689 ($err) = @_;
3690 skip_unknown_revs($err);
3692 sub _cb {
3693 my ($paths, $r, $author, $date, $log) = @_;
3694 [ dup_changed_paths($paths),
3695 { author => $author, date => $date, log => $log } ];
3697 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3698 sub { $revs{$_[1]} = _cb(@_) });
3699 if ($err && $max >= $head) {
3700 print STDERR "Path '$longest_path' ",
3701 "was probably deleted:\n",
3702 $err->expanded_message,
3703 "\nWill attempt to follow ",
3704 "revisions r$min .. r$max ",
3705 "committed before the deletion\n";
3706 my $hi = $max;
3707 while (--$hi >= $min) {
3708 my $ok;
3709 $self->get_log([$longest_path], $min, $hi,
3710 0, 1, 1, sub {
3711 $ok ||= $_[1];
3712 $revs{$_[1]} = _cb(@_) });
3713 if ($ok) {
3714 print STDERR "r$min .. r$ok OK\n";
3715 last;
3719 $SVN::Error::handler = $err_handler;
3721 my %exists = map { $_->{path} => $_ } @$gsv;
3722 foreach my $r (sort {$a <=> $b} keys %revs) {
3723 my ($paths, $logged) = @{$revs{$r}};
3725 foreach my $gs ($self->match_globs(\%exists, $paths,
3726 $globs, $r)) {
3727 if ($gs->rev_db_max >= $r) {
3728 next;
3730 next unless $gs->match_paths($paths, $r);
3731 $gs->{logged_rev_props} = $logged;
3732 if (my $last_commit = $gs->last_commit) {
3733 $gs->assert_index_clean($last_commit);
3735 my $log_entry = $gs->do_fetch($paths, $r);
3736 if ($log_entry) {
3737 $gs->do_git_commit($log_entry);
3740 foreach my $g (@$globs) {
3741 my $k = "svn-remote.$g->{remote}." .
3742 "$g->{t}-maxRev";
3743 Git::SVN::tmp_config($k, $r);
3745 if ($ra_invalid) {
3746 $_[0] = undef;
3747 $self = undef;
3748 $RA = undef;
3749 $self = Git::SVN::Ra->new($ra_url);
3750 $ra_invalid = undef;
3753 # pre-fill the .rev_db since it'll eventually get filled in
3754 # with '0' x40 if something new gets committed
3755 foreach my $gs (@$gsv) {
3756 next if defined $gs->rev_db_get($max);
3757 $gs->rev_db_set($max, 0 x40);
3759 foreach my $g (@$globs) {
3760 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3761 Git::SVN::tmp_config($k, $max);
3763 last if $max >= $head;
3764 $min = $max + 1;
3765 $max += $inc;
3766 $max = $head if ($max > $head);
3770 sub match_globs {
3771 my ($self, $exists, $paths, $globs, $r) = @_;
3773 sub get_dir_check {
3774 my ($self, $exists, $g, $r) = @_;
3775 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3776 return unless scalar @x == 3;
3777 my $dirents = $x[0];
3778 foreach my $de (keys %$dirents) {
3779 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3780 my $p = $g->{path}->full_path($de);
3781 next if $exists->{$p};
3782 next if (length $g->{path}->{right} &&
3783 ($self->check_path($p, $r) !=
3784 $SVN::Node::dir));
3785 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3786 $g->{ref}->full_path($de), 1);
3789 foreach my $g (@$globs) {
3790 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3791 if ($path->{action} =~ /^[AR]$/) {
3792 get_dir_check($self, $exists, $g, $r);
3795 foreach (keys %$paths) {
3796 if (/$g->{path}->{left_regex}/ &&
3797 !/$g->{path}->{regex}/) {
3798 next if $paths->{$_}->{action} !~ /^[AR]$/;
3799 get_dir_check($self, $exists, $g, $r);
3801 next unless /$g->{path}->{regex}/;
3802 my $p = $1;
3803 my $pathname = $g->{path}->full_path($p);
3804 next if $exists->{$pathname};
3805 next if ($self->check_path($pathname, $r) !=
3806 $SVN::Node::dir);
3807 $exists->{$pathname} = Git::SVN->init(
3808 $self->{url}, $pathname, undef,
3809 $g->{ref}->full_path($p), 1);
3811 my $c = '';
3812 foreach (split m#/#, $g->{path}->{left}) {
3813 $c .= "/$_";
3814 next unless ($paths->{$c} &&
3815 ($paths->{$c}->{action} =~ /^[AR]$/));
3816 get_dir_check($self, $exists, $g, $r);
3819 values %$exists;
3822 sub minimize_url {
3823 my ($self) = @_;
3824 return $self->{url} if ($self->{url} eq $self->{repos_root});
3825 my $url = $self->{repos_root};
3826 my @components = split(m!/!, $self->{svn_path});
3827 my $c = '';
3828 do {
3829 $url .= "/$c" if length $c;
3830 eval { (ref $self)->new($url)->get_latest_revnum };
3831 } while ($@ && ($c = shift @components));
3832 $url;
3835 sub can_do_switch {
3836 my $self = shift;
3837 unless (defined $can_do_switch) {
3838 my $pool = SVN::Pool->new;
3839 my $rep = eval {
3840 $self->do_switch(1, '', 0, $self->{url},
3841 SVN::Delta::Editor->new, $pool);
3843 if ($@) {
3844 $can_do_switch = 0;
3845 } else {
3846 $rep->abort_report($pool);
3847 $can_do_switch = 1;
3849 $pool->clear;
3851 $can_do_switch;
3854 sub skip_unknown_revs {
3855 my ($err) = @_;
3856 my $errno = $err->apr_err();
3857 # Maybe the branch we're tracking didn't
3858 # exist when the repo started, so it's
3859 # not an error if it doesn't, just continue
3861 # Wonderfully consistent library, eh?
3862 # 160013 - svn:// and file://
3863 # 175002 - http(s)://
3864 # 175007 - http(s):// (this repo required authorization, too...)
3865 # More codes may be discovered later...
3866 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3867 my $err_key = $err->expanded_message;
3868 # revision numbers change every time, filter them out
3869 $err_key =~ s/\d+/\0/g;
3870 $err_key = "$errno\0$err_key";
3871 unless ($ignored_err{$err_key}) {
3872 warn "W: Ignoring error from SVN, path probably ",
3873 "does not exist: ($errno): ",
3874 $err->expanded_message,"\n";
3875 $ignored_err{$err_key} = 1;
3877 return;
3879 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3882 # svn_log_changed_path_t objects passed to get_log are likely to be
3883 # overwritten even if only the refs are copied to an external variable,
3884 # so we should dup the structures in their entirety. Using an externally
3885 # passed pool (instead of our temporary and quickly cleared pool in
3886 # Git::SVN::Ra) does not help matters at all...
3887 sub dup_changed_paths {
3888 my ($paths) = @_;
3889 return undef unless $paths;
3890 my %ret;
3891 foreach my $p (keys %$paths) {
3892 my $i = $paths->{$p};
3893 my %s = map { $_ => $i->$_ }
3894 qw/copyfrom_path copyfrom_rev action/;
3895 $ret{$p} = \%s;
3897 \%ret;
3900 package Git::SVN::Log;
3901 use strict;
3902 use warnings;
3903 use POSIX qw/strftime/;
3904 use constant commit_log_separator => ('-' x 72) . "\n";
3905 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3906 %rusers $show_commit $incremental/;
3907 my $l_fmt;
3909 sub cmt_showable {
3910 my ($c) = @_;
3911 return 1 if defined $c->{r};
3913 # big commit message got truncated by the 16k pretty buffer in rev-list
3914 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3915 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3916 @{$c->{l}} = ();
3917 my @log = command(qw/cat-file commit/, $c->{c});
3919 # shift off the headers
3920 shift @log while ($log[0] ne '');
3921 shift @log;
3923 # TODO: make $c->{l} not have a trailing newline in the future
3924 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3926 (undef, $c->{r}, undef) = ::extract_metadata(
3927 (grep(/^git-svn-id: /, @log))[-1]);
3929 return defined $c->{r};
3932 sub log_use_color {
3933 return 1 if $color;
3934 my ($dc, $dcvar);
3935 $dcvar = 'color.diff';
3936 $dc = `git-config --get $dcvar`;
3937 if ($dc eq '') {
3938 # nothing at all; fallback to "diff.color"
3939 $dcvar = 'diff.color';
3940 $dc = `git-config --get $dcvar`;
3942 chomp($dc);
3943 if ($dc eq 'auto') {
3944 my $pc;
3945 $pc = `git-config --get color.pager`;
3946 if ($pc eq '') {
3947 # does not have it -- fallback to pager.color
3948 $pc = `git-config --bool --get pager.color`;
3950 else {
3951 $pc = `git-config --bool --get color.pager`;
3952 if ($?) {
3953 $pc = 'false';
3956 chomp($pc);
3957 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3958 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3960 return 0;
3962 return 0 if $dc eq 'never';
3963 return 1 if $dc eq 'always';
3964 chomp($dc = `git-config --bool --get $dcvar`);
3965 return ($dc eq 'true');
3968 sub git_svn_log_cmd {
3969 my ($r_min, $r_max, @args) = @_;
3970 my $head = 'HEAD';
3971 my (@files, @log_opts);
3972 foreach my $x (@args) {
3973 if ($x eq '--' || @files) {
3974 push @files, $x;
3975 } else {
3976 if (::verify_ref("$x^0")) {
3977 $head = $x;
3978 } else {
3979 push @log_opts, $x;
3984 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3985 $gs ||= Git::SVN->_new;
3986 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3987 $gs->refname);
3988 push @cmd, '-r' unless $non_recursive;
3989 push @cmd, qw/--raw --name-status/ if $verbose;
3990 push @cmd, '--color' if log_use_color();
3991 push @cmd, @log_opts;
3992 if (defined $r_max && $r_max == $r_min) {
3993 push @cmd, '--max-count=1';
3994 if (my $c = $gs->rev_db_get($r_max)) {
3995 push @cmd, $c;
3997 } elsif (defined $r_max) {
3998 if ($r_max < $r_min) {
3999 ($r_min, $r_max) = ($r_max, $r_min);
4001 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4002 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4003 # If there are no commits in the range, both $c_max and $c_min
4004 # will be undefined. If there is at least 1 commit in the
4005 # range, both will be defined.
4006 return () if !defined $c_min || !defined $c_max;
4007 if ($c_min eq $c_max) {
4008 push @cmd, '--max-count=1', $c_min;
4009 } else {
4010 push @cmd, '--boundary', "$c_min..$c_max";
4013 return (@cmd, @files);
4016 # adapted from pager.c
4017 sub config_pager {
4018 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4019 if (!defined $pager) {
4020 $pager = 'less';
4021 } elsif (length $pager == 0 || $pager eq 'cat') {
4022 $pager = undef;
4026 sub run_pager {
4027 return unless -t *STDOUT && defined $pager;
4028 pipe my $rfd, my $wfd or return;
4029 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4030 if (!$pid) {
4031 open STDOUT, '>&', $wfd or
4032 ::fatal "Can't redirect to stdout: $!";
4033 return;
4035 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4036 $ENV{LESS} ||= 'FRSX';
4037 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4040 sub format_svn_date {
4041 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4044 sub parse_git_date {
4045 my ($t, $tz) = @_;
4046 # Date::Parse isn't in the standard Perl distro :(
4047 if ($tz =~ s/^\+//) {
4048 $t += tz_to_s_offset($tz);
4049 } elsif ($tz =~ s/^\-//) {
4050 $t -= tz_to_s_offset($tz);
4052 return $t;
4055 sub set_local_timezone {
4056 if (defined $TZ) {
4057 $ENV{TZ} = $TZ;
4058 } else {
4059 delete $ENV{TZ};
4063 sub tz_to_s_offset {
4064 my ($tz) = @_;
4065 $tz =~ s/(\d\d)$//;
4066 return ($1 * 60) + ($tz * 3600);
4069 sub get_author_info {
4070 my ($dest, $author, $t, $tz) = @_;
4071 $author =~ s/(?:^\s*|\s*$)//g;
4072 $dest->{a_raw} = $author;
4073 my $au;
4074 if ($::_authors) {
4075 $au = $rusers{$author} || undef;
4077 if (!$au) {
4078 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4080 $dest->{t} = $t;
4081 $dest->{tz} = $tz;
4082 $dest->{a} = $au;
4083 $dest->{t_utc} = parse_git_date($t, $tz);
4086 sub process_commit {
4087 my ($c, $r_min, $r_max, $defer) = @_;
4088 if (defined $r_min && defined $r_max) {
4089 if ($r_min == $c->{r} && $r_min == $r_max) {
4090 show_commit($c);
4091 return 0;
4093 return 1 if $r_min == $r_max;
4094 if ($r_min < $r_max) {
4095 # we need to reverse the print order
4096 return 0 if (defined $limit && --$limit < 0);
4097 push @$defer, $c;
4098 return 1;
4100 if ($r_min != $r_max) {
4101 return 1 if ($r_min < $c->{r});
4102 return 1 if ($r_max > $c->{r});
4105 return 0 if (defined $limit && --$limit < 0);
4106 show_commit($c);
4107 return 1;
4110 sub show_commit {
4111 my $c = shift;
4112 if ($oneline) {
4113 my $x = "\n";
4114 if (my $l = $c->{l}) {
4115 while ($l->[0] =~ /^\s*$/) { shift @$l }
4116 $x = $l->[0];
4118 $l_fmt ||= 'A' . length($c->{r});
4119 print 'r',pack($l_fmt, $c->{r}),' | ';
4120 print "$c->{c} | " if $show_commit;
4121 print $x;
4122 } else {
4123 show_commit_normal($c);
4127 sub show_commit_changed_paths {
4128 my ($c) = @_;
4129 return unless $c->{changed};
4130 print "Changed paths:\n", @{$c->{changed}};
4133 sub show_commit_normal {
4134 my ($c) = @_;
4135 print commit_log_separator, "r$c->{r} | ";
4136 print "$c->{c} | " if $show_commit;
4137 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4138 my $nr_line = 0;
4140 if (my $l = $c->{l}) {
4141 while ($l->[$#$l] eq "\n" && $#$l > 0
4142 && $l->[($#$l - 1)] eq "\n") {
4143 pop @$l;
4145 $nr_line = scalar @$l;
4146 if (!$nr_line) {
4147 print "1 line\n\n\n";
4148 } else {
4149 if ($nr_line == 1) {
4150 $nr_line = '1 line';
4151 } else {
4152 $nr_line .= ' lines';
4154 print $nr_line, "\n";
4155 show_commit_changed_paths($c);
4156 print "\n";
4157 print $_ foreach @$l;
4159 } else {
4160 print "1 line\n";
4161 show_commit_changed_paths($c);
4162 print "\n";
4165 foreach my $x (qw/raw stat diff/) {
4166 if ($c->{$x}) {
4167 print "\n";
4168 print $_ foreach @{$c->{$x}}
4173 sub cmd_show_log {
4174 my (@args) = @_;
4175 my ($r_min, $r_max);
4176 my $r_last = -1; # prevent dupes
4177 set_local_timezone();
4178 if (defined $::_revision) {
4179 if ($::_revision =~ /^(\d+):(\d+)$/) {
4180 ($r_min, $r_max) = ($1, $2);
4181 } elsif ($::_revision =~ /^\d+$/) {
4182 $r_min = $r_max = $::_revision;
4183 } else {
4184 ::fatal "-r$::_revision is not supported, use ",
4185 "standard 'git log' arguments instead";
4189 config_pager();
4190 @args = git_svn_log_cmd($r_min, $r_max, @args);
4191 if (!@args) {
4192 print commit_log_separator unless $incremental || $oneline;
4193 return;
4195 my $log = command_output_pipe(@args);
4196 run_pager();
4197 my (@k, $c, $d, $stat);
4198 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4199 while (<$log>) {
4200 if (/^${esc_color}commit -?($::sha1_short)/o) {
4201 my $cmt = $1;
4202 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4203 $r_last = $c->{r};
4204 process_commit($c, $r_min, $r_max, \@k) or
4205 goto out;
4207 $d = undef;
4208 $c = { c => $cmt };
4209 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4210 get_author_info($c, $1, $2, $3);
4211 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4212 # ignore
4213 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4214 push @{$c->{raw}}, $_;
4215 } elsif (/^${esc_color}[ACRMDT]\t/) {
4216 # we could add $SVN->{svn_path} here, but that requires
4217 # remote access at the moment (repo_path_split)...
4218 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4219 push @{$c->{changed}}, $_;
4220 } elsif (/^${esc_color}diff /o) {
4221 $d = 1;
4222 push @{$c->{diff}}, $_;
4223 } elsif ($d) {
4224 push @{$c->{diff}}, $_;
4225 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4226 $esc_color*[\+\-]*$esc_color$/x) {
4227 $stat = 1;
4228 push @{$c->{stat}}, $_;
4229 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4230 push @{$c->{stat}}, $_;
4231 $stat = undef;
4232 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4233 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4234 } elsif (s/^${esc_color} //o) {
4235 push @{$c->{l}}, $_;
4238 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4239 $r_last = $c->{r};
4240 process_commit($c, $r_min, $r_max, \@k);
4242 if (@k) {
4243 ($r_min, $r_max) = ($r_max, $r_min);
4244 process_commit($_, $r_min, $r_max) foreach reverse @k;
4246 out:
4247 close $log;
4248 print commit_log_separator unless $incremental || $oneline;
4251 package Git::SVN::Migration;
4252 # these version numbers do NOT correspond to actual version numbers
4253 # of git nor git-svn. They are just relative.
4255 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4257 # v1 layout: .git/$id/info/url, refs/remotes/$id
4259 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4261 # v3 layout: .git/svn/$id, refs/remotes/$id
4262 # - info/url may remain for backwards compatibility
4263 # - this is what we migrate up to this layout automatically,
4264 # - this will be used by git svn init on single branches
4265 # v3.1 layout (auto migrated):
4266 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4267 # for backwards compatibility
4269 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4270 # - this is only created for newly multi-init-ed
4271 # repositories. Similar in spirit to the
4272 # --use-separate-remotes option in git-clone (now default)
4273 # - we do not automatically migrate to this (following
4274 # the example set by core git)
4275 use strict;
4276 use warnings;
4277 use Carp qw/croak/;
4278 use File::Path qw/mkpath/;
4279 use File::Basename qw/dirname basename/;
4280 use vars qw/$_minimize/;
4282 sub migrate_from_v0 {
4283 my $git_dir = $ENV{GIT_DIR};
4284 return undef unless -d $git_dir;
4285 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4286 my $migrated = 0;
4287 while (<$fh>) {
4288 chomp;
4289 my ($id, $orig_ref) = ($_, $_);
4290 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4291 next unless -f "$git_dir/$id/info/url";
4292 my $new_ref = "refs/remotes/$id";
4293 if (::verify_ref("$new_ref^0")) {
4294 print STDERR "W: $orig_ref is probably an old ",
4295 "branch used by an ancient version of ",
4296 "git-svn.\n",
4297 "However, $new_ref also exists.\n",
4298 "We will not be able ",
4299 "to use this branch until this ",
4300 "ambiguity is resolved.\n";
4301 next;
4303 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4304 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4305 command_noisy('update-ref', $new_ref, $orig_ref);
4306 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4307 $migrated++;
4309 command_close_pipe($fh, $ctx);
4310 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4311 $migrated;
4314 sub migrate_from_v1 {
4315 my $git_dir = $ENV{GIT_DIR};
4316 my $migrated = 0;
4317 return $migrated unless -d $git_dir;
4318 my $svn_dir = "$git_dir/svn";
4320 # just in case somebody used 'svn' as their $id at some point...
4321 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4323 print STDERR "Migrating from a git-svn v1 layout...\n";
4324 mkpath([$svn_dir]);
4325 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4326 "$svn_dir\n\t(required for this version ",
4327 "($::VERSION) of git-svn) does not. exist\n";
4328 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4329 while (<$fh>) {
4330 my $x = $_;
4331 next unless $x =~ s#^refs/remotes/##;
4332 chomp $x;
4333 next unless -f "$git_dir/$x/info/url";
4334 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4335 next unless $u;
4336 my $dn = dirname("$git_dir/svn/$x");
4337 mkpath([$dn]) unless -d $dn;
4338 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4339 mkpath(["$git_dir/svn/svn"]);
4340 print STDERR " - $git_dir/$x/info => ",
4341 "$git_dir/svn/$x/info\n";
4342 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4343 croak "$!: $x";
4344 # don't worry too much about these, they probably
4345 # don't exist with repos this old (save for index,
4346 # and we can easily regenerate that)
4347 foreach my $f (qw/unhandled.log index .rev_db/) {
4348 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4350 } else {
4351 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4352 rename "$git_dir/$x", "$git_dir/svn/$x" or
4353 croak "$!: $x";
4355 $migrated++;
4357 command_close_pipe($fh, $ctx);
4358 print STDERR "Done migrating from a git-svn v1 layout\n";
4359 $migrated;
4362 sub read_old_urls {
4363 my ($l_map, $pfx, $path) = @_;
4364 my @dir;
4365 foreach (<$path/*>) {
4366 if (-r "$_/info/url") {
4367 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4368 my $ref_id = $pfx . basename $_;
4369 my $url = ::file_to_s("$_/info/url");
4370 $l_map->{$ref_id} = $url;
4371 } elsif (-d $_) {
4372 push @dir, $_;
4375 foreach (@dir) {
4376 my $x = $_;
4377 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4378 read_old_urls($l_map, $x, $_);
4382 sub migrate_from_v2 {
4383 my @cfg = command(qw/config -l/);
4384 return if grep /^svn-remote\..+\.url=/, @cfg;
4385 my %l_map;
4386 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4387 my $migrated = 0;
4389 foreach my $ref_id (sort keys %l_map) {
4390 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4391 if ($@) {
4392 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4394 $migrated++;
4396 $migrated;
4399 sub minimize_connections {
4400 my $r = Git::SVN::read_all_remotes();
4401 my $new_urls = {};
4402 my $root_repos = {};
4403 foreach my $repo_id (keys %$r) {
4404 my $url = $r->{$repo_id}->{url} or next;
4405 my $fetch = $r->{$repo_id}->{fetch} or next;
4406 my $ra = Git::SVN::Ra->new($url);
4408 # skip existing cases where we already connect to the root
4409 if (($ra->{url} eq $ra->{repos_root}) ||
4410 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4411 $repo_id)) {
4412 $root_repos->{$ra->{url}} = $repo_id;
4413 next;
4416 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4417 my $root_path = $ra->{url};
4418 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4419 foreach my $path (keys %$fetch) {
4420 my $ref_id = $fetch->{$path};
4421 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4423 # make sure we can read when connecting to
4424 # a higher level of a repository
4425 my ($last_rev, undef) = $gs->last_rev_commit;
4426 if (!defined $last_rev) {
4427 $last_rev = eval {
4428 $root_ra->get_latest_revnum;
4430 next if $@;
4432 my $new = $root_path;
4433 $new .= length $path ? "/$path" : '';
4434 eval {
4435 $root_ra->get_log([$new], $last_rev, $last_rev,
4436 0, 0, 1, sub { });
4438 next if $@;
4439 $new_urls->{$ra->{repos_root}}->{$new} =
4440 { ref_id => $ref_id,
4441 old_repo_id => $repo_id,
4442 old_path => $path };
4446 my @emptied;
4447 foreach my $url (keys %$new_urls) {
4448 # see if we can re-use an existing [svn-remote "repo_id"]
4449 # instead of creating a(n ugly) new section:
4450 my $repo_id = $root_repos->{$url} ||
4451 Git::SVN::sanitize_remote_name($url);
4453 my $fetch = $new_urls->{$url};
4454 foreach my $path (keys %$fetch) {
4455 my $x = $fetch->{$path};
4456 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4457 my $pfx = "svn-remote.$x->{old_repo_id}";
4459 my $old_fetch = quotemeta("$x->{old_path}:".
4460 "refs/remotes/$x->{ref_id}");
4461 command_noisy(qw/config --unset/,
4462 "$pfx.fetch", '^'. $old_fetch . '$');
4463 delete $r->{$x->{old_repo_id}}->
4464 {fetch}->{$x->{old_path}};
4465 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4466 command_noisy(qw/config --unset/,
4467 "$pfx.url");
4468 push @emptied, $x->{old_repo_id}
4472 if (@emptied) {
4473 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4474 "$ENV{GIT_DIR}/config";
4475 print STDERR <<EOF;
4476 The following [svn-remote] sections in your config file ($file) are empty
4477 and can be safely removed:
4479 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4483 sub migration_check {
4484 migrate_from_v0();
4485 migrate_from_v1();
4486 migrate_from_v2();
4487 minimize_connections() if $_minimize;
4490 package Git::IndexInfo;
4491 use strict;
4492 use warnings;
4493 use Git qw/command_input_pipe command_close_pipe/;
4495 sub new {
4496 my ($class) = @_;
4497 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4498 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4501 sub remove {
4502 my ($self, $path) = @_;
4503 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4504 return ++$self->{nr};
4506 undef;
4509 sub update {
4510 my ($self, $mode, $hash, $path) = @_;
4511 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4512 return ++$self->{nr};
4514 undef;
4517 sub DESTROY {
4518 my ($self) = @_;
4519 command_close_pipe($self->{gui}, $self->{ctx});
4522 package Git::SVN::GlobSpec;
4523 use strict;
4524 use warnings;
4526 sub new {
4527 my ($class, $glob) = @_;
4528 my $re = $glob;
4529 $re =~ s!/+$!!g; # no need for trailing slashes
4530 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4531 my ($left, $right) = ($1, $2);
4532 if ($nr > 1) {
4533 die "Only one '*' wildcard expansion ",
4534 "is supported (got $nr): '$glob'\n";
4535 } elsif ($nr == 0) {
4536 die "One '*' is needed for glob: '$glob'\n";
4538 $re = quotemeta($left) . $re . quotemeta($right);
4539 if (length $left && !($left =~ s!/+$!!g)) {
4540 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4542 if (length $right && !($right =~ s!^/+!!g)) {
4543 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4545 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4546 bless { left => $left, right => $right, left_regex => $left_re,
4547 regex => qr/$re/, glob => $glob }, $class;
4550 sub full_path {
4551 my ($self, $path) = @_;
4552 return (length $self->{left} ? "$self->{left}/" : '') .
4553 $path . (length $self->{right} ? "/$self->{right}" : '');
4556 __END__
4558 Data structures:
4561 $remotes = { # returned by read_all_remotes()
4562 'svn' => {
4563 # svn-remote.svn.url=https://svn.musicpd.org
4564 url => 'https://svn.musicpd.org',
4565 # svn-remote.svn.fetch=mpd/trunk:trunk
4566 fetch => {
4567 'mpd/trunk' => 'trunk',
4569 # svn-remote.svn.tags=mpd/tags/*:tags/*
4570 tags => {
4571 path => {
4572 left => 'mpd/tags',
4573 right => '',
4574 regex => qr!mpd/tags/([^/]+)$!,
4575 glob => 'tags/*',
4577 ref => {
4578 left => 'tags',
4579 right => '',
4580 regex => qr!tags/([^/]+)$!,
4581 glob => 'tags/*',
4587 $log_entry hashref as returned by libsvn_log_entry()
4589 log => 'whitespace-formatted log entry
4590 ', # trailing newline is preserved
4591 revision => '8', # integer
4592 date => '2004-02-24T17:01:44.108345Z', # commit date
4593 author => 'committer name'
4597 # this is generated by generate_diff();
4598 @mods = array of diff-index line hashes, each element represents one line
4599 of diff-index output
4601 diff-index line ($m hash)
4603 mode_a => first column of diff-index output, no leading ':',
4604 mode_b => second column of diff-index output,
4605 sha1_b => sha1sum of the final blob,
4606 chg => change type [MCRADT],
4607 file_a => original file name of a file (iff chg is 'C' or 'R')
4608 file_b => new/current file name of a file (any chg)
4612 # retval of read_url_paths{,_all}();
4613 $l_map = {
4614 # repository root url
4615 'https://svn.musicpd.org' => {
4616 # repository path # GIT_SVN_ID
4617 'mpd/trunk' => 'trunk',
4618 'mpd/tags/0.11.5' => 'tags/0.11.5',
4622 Notes:
4623 I don't trust the each() function on unless I created %hash myself
4624 because the internal iterator may not have started at base.