git-svn info: implement info command
[git/gitweb.git] / git-svn.perl
blobfd1036104550c6d500a9ee64498c06558fcca9ff
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, $_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 { } ],
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 my $result = "Path: $path\n";
777 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
778 $result .= "URL: " . $full_url . "\n";
780 my $repos_root = $gs->ra->{repos_root};
781 Git::SVN::remove_username($repos_root);
782 $result .= "Repository Root: $repos_root\n";
783 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
784 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
786 $result .= "Node Kind: " .
787 ($file_type eq "dir" ? "directory" : "file") . "\n";
789 my $schedule = $diff_status eq "A"
790 ? "add"
791 : ($diff_status eq "D" ? "delete" : "normal");
792 $result .= "Schedule: $schedule\n";
794 if ($diff_status eq "A") {
795 print $result, "\n";
796 return;
799 my ($lc_author, $lc_rev, $lc_date_utc);
800 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
801 my $log = command_output_pipe(@args);
802 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
803 while (<$log>) {
804 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
805 $lc_author = $1;
806 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
807 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
808 (undef, $lc_rev, undef) = ::extract_metadata($1);
811 close $log;
813 Git::SVN::Log::set_local_timezone();
815 $result .= "Last Changed Author: $lc_author\n";
816 $result .= "Last Changed Rev: $lc_rev\n";
817 $result .= "Last Changed Date: " .
818 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
820 if ($file_type ne "dir") {
821 my $text_last_updated_date =
822 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
823 $result .=
824 "Text Last Updated: " .
825 Git::SVN::Log::format_svn_date($text_last_updated_date) .
826 "\n";
827 my $checksum;
828 if ($diff_status eq "D") {
829 my ($fh, $ctx) =
830 command_output_pipe(qw(cat-file blob), "HEAD:$path");
831 if ($file_type eq "link") {
832 my $file_name = <$fh>;
833 $checksum = Git::SVN::Util::md5sum("link $file_name");
834 } else {
835 $checksum = Git::SVN::Util::md5sum($fh);
837 command_close_pipe($fh, $ctx);
838 } elsif ($file_type eq "link") {
839 my $file_name =
840 command(qw(cat-file blob), "HEAD:$path");
841 $checksum =
842 Git::SVN::Util::md5sum("link " . $file_name);
843 } else {
844 open FILE, "<", $path or die $!;
845 $checksum = Git::SVN::Util::md5sum(\*FILE);
846 close FILE or die $!;
848 $result .= "Checksum: " . $checksum . "\n";
851 print $result, "\n";
854 ########################### utility functions #########################
856 sub rebase_cmd {
857 my @cmd = qw/rebase/;
858 push @cmd, '-v' if $_verbose;
859 push @cmd, qw/--merge/ if $_merge;
860 push @cmd, "--strategy=$_strategy" if $_strategy;
861 @cmd;
864 sub post_fetch_checkout {
865 return if $_no_checkout;
866 my $gs = $Git::SVN::_head or return;
867 return if verify_ref('refs/heads/master^0');
869 my $valid_head = verify_ref('HEAD^0');
870 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
871 return if ($valid_head || !verify_ref('HEAD^0'));
873 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
874 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
875 return if -f $index;
877 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
878 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
879 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
880 print STDERR "Checked out HEAD:\n ",
881 $gs->full_url, " r", $gs->last_rev, "\n";
884 sub complete_svn_url {
885 my ($url, $path) = @_;
886 $path =~ s#/+$##;
887 if ($path !~ m#^[a-z\+]+://#) {
888 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
889 fatal("E: '$path' is not a complete URL ",
890 "and a separate URL is not specified");
892 return ($url, $path);
894 return ($path, '');
897 sub complete_url_ls_init {
898 my ($ra, $repo_path, $switch, $pfx) = @_;
899 unless ($repo_path) {
900 print STDERR "W: $switch not specified\n";
901 return;
903 $repo_path =~ s#/+$##;
904 if ($repo_path =~ m#^[a-z\+]+://#) {
905 $ra = Git::SVN::Ra->new($repo_path);
906 $repo_path = '';
907 } else {
908 $repo_path =~ s#^/+##;
909 unless ($ra) {
910 fatal("E: '$repo_path' is not a complete URL ",
911 "and a separate URL is not specified");
914 my $url = $ra->{url};
915 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
916 my $k = "svn-remote.$gs->{repo_id}.url";
917 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
918 if ($orig_url && ($orig_url ne $gs->{url})) {
919 die "$k already set: $orig_url\n",
920 "wanted to set to: $gs->{url}\n";
922 command_oneline('config', $k, $gs->{url}) unless $orig_url;
923 my $remote_path = "$ra->{svn_path}/$repo_path/*";
924 $remote_path =~ s#/+#/#g;
925 $remote_path =~ s#^/##g;
926 my ($n) = ($switch =~ /^--(\w+)/);
927 if (length $pfx && $pfx !~ m#/$#) {
928 die "--prefix='$pfx' must have a trailing slash '/'\n";
930 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
931 "$remote_path:refs/remotes/$pfx*");
934 sub verify_ref {
935 my ($ref) = @_;
936 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
937 { STDERR => 0 }); };
940 sub get_tree_from_treeish {
941 my ($treeish) = @_;
942 # $treeish can be a symbolic ref, too:
943 my $type = command_oneline(qw/cat-file -t/, $treeish);
944 my $expected;
945 while ($type eq 'tag') {
946 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
948 if ($type eq 'commit') {
949 $expected = (grep /^tree /, command(qw/cat-file commit/,
950 $treeish))[0];
951 ($expected) = ($expected =~ /^tree ($sha1)$/o);
952 die "Unable to get tree from $treeish\n" unless $expected;
953 } elsif ($type eq 'tree') {
954 $expected = $treeish;
955 } else {
956 die "$treeish is a $type, expected tree, tag or commit\n";
958 return $expected;
961 sub get_commit_entry {
962 my ($treeish) = shift;
963 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
964 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
965 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
966 open my $log_fh, '>', $commit_editmsg or croak $!;
968 my $type = command_oneline(qw/cat-file -t/, $treeish);
969 if ($type eq 'commit' || $type eq 'tag') {
970 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
971 $type, $treeish);
972 my $in_msg = 0;
973 while (<$msg_fh>) {
974 if (!$in_msg) {
975 $in_msg = 1 if (/^\s*$/);
976 } elsif (/^git-svn-id: /) {
977 # skip this for now, we regenerate the
978 # correct one on re-fetch anyways
979 # TODO: set *:merge properties or like...
980 } else {
981 print $log_fh $_ or croak $!;
984 command_close_pipe($msg_fh, $ctx);
986 close $log_fh or croak $!;
988 if ($_edit || ($type eq 'tree')) {
989 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
990 # TODO: strip out spaces, comments, like git-commit.sh
991 system($editor, $commit_editmsg);
993 rename $commit_editmsg, $commit_msg or croak $!;
994 open $log_fh, '<', $commit_msg or croak $!;
995 { local $/; chomp($log_entry{log} = <$log_fh>); }
996 close $log_fh or croak $!;
997 unlink $commit_msg;
998 \%log_entry;
1001 sub s_to_file {
1002 my ($str, $file, $mode) = @_;
1003 open my $fd,'>',$file or croak $!;
1004 print $fd $str,"\n" or croak $!;
1005 close $fd or croak $!;
1006 chmod ($mode &~ umask, $file) if (defined $mode);
1009 sub file_to_s {
1010 my $file = shift;
1011 open my $fd,'<',$file or croak "$!: file: $file\n";
1012 local $/;
1013 my $ret = <$fd>;
1014 close $fd or croak $!;
1015 $ret =~ s/\s*$//s;
1016 return $ret;
1019 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1020 sub load_authors {
1021 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1022 my $log = $cmd eq 'log';
1023 while (<$authors>) {
1024 chomp;
1025 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1026 my ($user, $name, $email) = ($1, $2, $3);
1027 if ($log) {
1028 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1029 } else {
1030 $users{$user} = [$name, $email];
1033 close $authors or croak $!;
1036 # convert GetOpt::Long specs for use by git-config
1037 sub read_repo_config {
1038 return unless -d $ENV{GIT_DIR};
1039 my $opts = shift;
1040 my @config_only;
1041 foreach my $o (keys %$opts) {
1042 # if we have mixedCase and a long option-only, then
1043 # it's a config-only variable that we don't need for
1044 # the command-line.
1045 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1046 my $v = $opts->{$o};
1047 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1048 $key =~ s/-//g;
1049 my $arg = 'git-config';
1050 $arg .= ' --int' if ($o =~ /[:=]i$/);
1051 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1052 if (ref $v eq 'ARRAY') {
1053 chomp(my @tmp = `$arg --get-all svn.$key`);
1054 @$v = @tmp if @tmp;
1055 } else {
1056 chomp(my $tmp = `$arg --get svn.$key`);
1057 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1058 $$v = $tmp;
1062 delete @$opts{@config_only} if @config_only;
1065 sub extract_metadata {
1066 my $id = shift or return (undef, undef, undef);
1067 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1068 \s([a-f\d\-]+)$/x);
1069 if (!defined $rev || !$uuid || !$url) {
1070 # some of the original repositories I made had
1071 # identifiers like this:
1072 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1074 return ($url, $rev, $uuid);
1077 sub cmt_metadata {
1078 return extract_metadata((grep(/^git-svn-id: /,
1079 command(qw/cat-file commit/, shift)))[-1]);
1082 sub working_head_info {
1083 my ($head, $refs) = @_;
1084 my @args = ('log', '--no-color', '--first-parent');
1085 my ($fh, $ctx) = command_output_pipe(@args, $head);
1086 my $hash;
1087 my %max;
1088 while (<$fh>) {
1089 if ( m{^commit ($::sha1)$} ) {
1090 unshift @$refs, $hash if $hash and $refs;
1091 $hash = $1;
1092 next;
1094 next unless s{^\s*(git-svn-id:)}{$1};
1095 my ($url, $rev, $uuid) = extract_metadata($_);
1096 if (defined $url && defined $rev) {
1097 next if $max{$url} and $max{$url} < $rev;
1098 if (my $gs = Git::SVN->find_by_url($url)) {
1099 my $c = $gs->rev_db_get($rev);
1100 if ($c && $c eq $hash) {
1101 close $fh; # break the pipe
1102 return ($url, $rev, $uuid, $gs);
1103 } else {
1104 $max{$url} ||= $gs->rev_db_max;
1109 command_close_pipe($fh, $ctx);
1110 (undef, undef, undef, undef);
1113 sub read_commit_parents {
1114 my ($parents, $c) = @_;
1115 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1116 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1117 @{$parents->{$c}} = split(/ /, $p);
1120 sub linearize_history {
1121 my ($gs, $refs) = @_;
1122 my %parents;
1123 foreach my $c (@$refs) {
1124 read_commit_parents(\%parents, $c);
1127 my @linear_refs;
1128 my %skip = ();
1129 my $last_svn_commit = $gs->last_commit;
1130 foreach my $c (reverse @$refs) {
1131 next if $c eq $last_svn_commit;
1132 last if $skip{$c};
1134 unshift @linear_refs, $c;
1135 $skip{$c} = 1;
1137 # we only want the first parent to diff against for linear
1138 # history, we save the rest to inject when we finalize the
1139 # svn commit
1140 my $fp_a = verify_ref("$c~1");
1141 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1142 if (!$fp_a || !$fp_b) {
1143 die "Commit $c\n",
1144 "has no parent commit, and therefore ",
1145 "nothing to diff against.\n",
1146 "You should be working from a repository ",
1147 "originally created by git-svn\n";
1149 if ($fp_a ne $fp_b) {
1150 die "$c~1 = $fp_a, however parsing commit $c ",
1151 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1154 foreach my $p (@{$parents{$c}}) {
1155 $skip{$p} = 1;
1158 (\@linear_refs, \%parents);
1161 sub find_file_type_and_diff_status {
1162 my ($path) = @_;
1163 return ('dir', '') if $path eq '.';
1165 my $diff_output =
1166 command_oneline(qw(diff --cached --name-status --), $path) || "";
1167 my $diff_status = (split(' ', $diff_output))[0] || "";
1169 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1171 return (undef, undef) if !$diff_status && !$ls_tree;
1173 if ($diff_status eq "A") {
1174 return ("link", $diff_status) if -l $path;
1175 return ("dir", $diff_status) if -d $path;
1176 return ("file", $diff_status);
1179 my $mode = (split(' ', $ls_tree))[0] || "";
1181 return ("link", $diff_status) if $mode eq "120000";
1182 return ("dir", $diff_status) if $mode eq "040000";
1183 return ("file", $diff_status);
1186 package Git::SVN::Util;
1187 use strict;
1188 use warnings;
1189 use Digest::MD5;
1191 sub md5sum {
1192 my $arg = shift;
1193 my $ref = ref $arg;
1194 my $md5 = Digest::MD5->new();
1195 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1196 $md5->addfile($arg) or croak $!;
1197 } elsif ($ref eq 'SCALAR') {
1198 $md5->add($$arg) or croak $!;
1199 } elsif (!$ref) {
1200 $md5->add($arg) or croak $!;
1201 } else {
1202 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1204 return $md5->hexdigest();
1207 package Git::SVN;
1208 use strict;
1209 use warnings;
1210 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1211 $_repack $_repack_flags $_use_svm_props $_head
1212 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1213 use Carp qw/croak/;
1214 use File::Path qw/mkpath/;
1215 use File::Copy qw/copy/;
1216 use IPC::Open3;
1218 my $_repack_nr;
1219 # properties that we do not log:
1220 my %SKIP_PROP;
1221 BEGIN {
1222 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1223 svn:special svn:executable
1224 svn:entry:committed-rev
1225 svn:entry:last-author
1226 svn:entry:uuid
1227 svn:entry:committed-date/;
1229 # some options are read globally, but can be overridden locally
1230 # per [svn-remote "..."] section. Command-line options will *NOT*
1231 # override options set in an [svn-remote "..."] section
1232 no strict 'refs';
1233 for my $option (qw/follow_parent no_metadata use_svm_props
1234 use_svnsync_props/) {
1235 my $key = $option;
1236 $key =~ tr/_//d;
1237 my $prop = "-$option";
1238 *$option = sub {
1239 my ($self) = @_;
1240 return $self->{$prop} if exists $self->{$prop};
1241 my $k = "svn-remote.$self->{repo_id}.$key";
1242 eval { command_oneline(qw/config --get/, $k) };
1243 if ($@) {
1244 $self->{$prop} = ${"Git::SVN::_$option"};
1245 } else {
1246 my $v = command_oneline(qw/config --bool/,$k);
1247 $self->{$prop} = $v eq 'false' ? 0 : 1;
1249 return $self->{$prop};
1254 my %LOCKFILES;
1255 END { unlink keys %LOCKFILES if %LOCKFILES }
1257 sub resolve_local_globs {
1258 my ($url, $fetch, $glob_spec) = @_;
1259 return unless defined $glob_spec;
1260 my $ref = $glob_spec->{ref};
1261 my $path = $glob_spec->{path};
1262 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1263 next unless m#^refs/remotes/$ref->{regex}$#;
1264 my $p = $1;
1265 my $pathname = desanitize_refname($path->full_path($p));
1266 my $refname = desanitize_refname($ref->full_path($p));
1267 if (my $existing = $fetch->{$pathname}) {
1268 if ($existing ne $refname) {
1269 die "Refspec conflict:\n",
1270 "existing: refs/remotes/$existing\n",
1271 " globbed: refs/remotes/$refname\n";
1273 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1274 $u =~ s!^\Q$url\E(/|$)!! or die
1275 "refs/remotes/$refname: '$url' not found in '$u'\n";
1276 if ($pathname ne $u) {
1277 warn "W: Refspec glob conflict ",
1278 "(ref: refs/remotes/$refname):\n",
1279 "expected path: $pathname\n",
1280 " real path: $u\n",
1281 "Continuing ahead with $u\n";
1282 next;
1284 } else {
1285 $fetch->{$pathname} = $refname;
1290 sub parse_revision_argument {
1291 my ($base, $head) = @_;
1292 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1293 return ($base, $head);
1295 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1296 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1297 return ($head, $head) if ($::_revision eq 'HEAD');
1298 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1299 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1300 die "revision argument: $::_revision not understood by git-svn\n";
1303 sub fetch_all {
1304 my ($repo_id, $remotes) = @_;
1305 if (ref $repo_id) {
1306 my $gs = $repo_id;
1307 $repo_id = undef;
1308 $repo_id = $gs->{repo_id};
1310 $remotes ||= read_all_remotes();
1311 my $remote = $remotes->{$repo_id} or
1312 die "[svn-remote \"$repo_id\"] unknown\n";
1313 my $fetch = $remote->{fetch};
1314 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1315 my (@gs, @globs);
1316 my $ra = Git::SVN::Ra->new($url);
1317 my $uuid = $ra->get_uuid;
1318 my $head = $ra->get_latest_revnum;
1319 my $base = defined $fetch ? $head : 0;
1321 # read the max revs for wildcard expansion (branches/*, tags/*)
1322 foreach my $t (qw/branches tags/) {
1323 defined $remote->{$t} or next;
1324 push @globs, $remote->{$t};
1325 my $max_rev = eval { tmp_config(qw/--int --get/,
1326 "svn-remote.$repo_id.${t}-maxRev") };
1327 if (defined $max_rev && ($max_rev < $base)) {
1328 $base = $max_rev;
1329 } elsif (!defined $max_rev) {
1330 $base = 0;
1334 if ($fetch) {
1335 foreach my $p (sort keys %$fetch) {
1336 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1337 my $lr = $gs->rev_db_max;
1338 if (defined $lr) {
1339 $base = $lr if ($lr < $base);
1341 push @gs, $gs;
1345 ($base, $head) = parse_revision_argument($base, $head);
1346 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1349 sub read_all_remotes {
1350 my $r = {};
1351 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1352 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1353 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1354 $local_ref =~ s{^/}{};
1355 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1356 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1357 $r->{$1}->{url} = $2;
1358 } elsif (m!^(.+)\.(branches|tags)=
1359 (.*):refs/remotes/(.+)\s*$/!x) {
1360 my ($p, $g) = ($3, $4);
1361 my $rs = $r->{$1}->{$2} = {
1362 t => $2,
1363 remote => $1,
1364 path => Git::SVN::GlobSpec->new($p),
1365 ref => Git::SVN::GlobSpec->new($g) };
1366 if (length($rs->{ref}->{right}) != 0) {
1367 die "The '*' glob character must be the last ",
1368 "character of '$g'\n";
1375 sub init_vars {
1376 if (defined $_repack) {
1377 $_repack = 1000 if ($_repack <= 0);
1378 $_repack_nr = $_repack;
1379 $_repack_flags ||= '-d';
1383 sub verify_remotes_sanity {
1384 return unless -d $ENV{GIT_DIR};
1385 my %seen;
1386 foreach (command(qw/config -l/)) {
1387 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1388 if ($seen{$1}) {
1389 die "Remote ref refs/remote/$1 is tracked by",
1390 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1391 "Please resolve this ambiguity in ",
1392 "your git configuration file before ",
1393 "continuing\n";
1395 $seen{$1} = $_;
1400 # we allow more chars than remotes2config.sh...
1401 sub sanitize_remote_name {
1402 my ($name) = @_;
1403 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1404 $name;
1407 sub find_existing_remote {
1408 my ($url, $remotes) = @_;
1409 return undef if $no_reuse_existing;
1410 my $existing;
1411 foreach my $repo_id (keys %$remotes) {
1412 my $u = $remotes->{$repo_id}->{url} or next;
1413 next if $u ne $url;
1414 $existing = $repo_id;
1415 last;
1417 $existing;
1420 sub init_remote_config {
1421 my ($self, $url, $no_write) = @_;
1422 $url =~ s!/+$!!; # strip trailing slash
1423 my $r = read_all_remotes();
1424 my $existing = find_existing_remote($url, $r);
1425 if ($existing) {
1426 unless ($no_write) {
1427 print STDERR "Using existing ",
1428 "[svn-remote \"$existing\"]\n";
1430 $self->{repo_id} = $existing;
1431 } elsif ($_minimize_url) {
1432 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1433 $existing = find_existing_remote($min_url, $r);
1434 if ($existing) {
1435 unless ($no_write) {
1436 print STDERR "Using existing ",
1437 "[svn-remote \"$existing\"]\n";
1439 $self->{repo_id} = $existing;
1441 if ($min_url ne $url) {
1442 unless ($no_write) {
1443 print STDERR "Using higher level of URL: ",
1444 "$url => $min_url\n";
1446 my $old_path = $self->{path};
1447 $self->{path} = $url;
1448 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1449 if (length $old_path) {
1450 $self->{path} .= "/$old_path";
1452 $url = $min_url;
1455 my $orig_url;
1456 if (!$existing) {
1457 # verify that we aren't overwriting anything:
1458 $orig_url = eval {
1459 command_oneline('config', '--get',
1460 "svn-remote.$self->{repo_id}.url")
1462 if ($orig_url && ($orig_url ne $url)) {
1463 die "svn-remote.$self->{repo_id}.url already set: ",
1464 "$orig_url\nwanted to set to: $url\n";
1467 my ($xrepo_id, $xpath) = find_ref($self->refname);
1468 if (defined $xpath) {
1469 die "svn-remote.$xrepo_id.fetch already set to track ",
1470 "$xpath:refs/remotes/", $self->refname, "\n";
1472 unless ($no_write) {
1473 command_noisy('config',
1474 "svn-remote.$self->{repo_id}.url", $url);
1475 $self->{path} =~ s{^/}{};
1476 command_noisy('config', '--add',
1477 "svn-remote.$self->{repo_id}.fetch",
1478 "$self->{path}:".$self->refname);
1480 $self->{url} = $url;
1483 sub find_by_url { # repos_root and, path are optional
1484 my ($class, $full_url, $repos_root, $path) = @_;
1486 return undef unless defined $full_url;
1487 remove_username($full_url);
1488 remove_username($repos_root) if defined $repos_root;
1489 my $remotes = read_all_remotes();
1490 if (defined $full_url && defined $repos_root && !defined $path) {
1491 $path = $full_url;
1492 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1494 foreach my $repo_id (keys %$remotes) {
1495 my $u = $remotes->{$repo_id}->{url} or next;
1496 remove_username($u);
1497 next if defined $repos_root && $repos_root ne $u;
1499 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1500 foreach (qw/branches tags/) {
1501 resolve_local_globs($u, $fetch,
1502 $remotes->{$repo_id}->{$_});
1504 my $p = $path;
1505 unless (defined $p) {
1506 $p = $full_url;
1507 $p =~ s#^\Q$u\E(?:/|$)## or next;
1509 foreach my $f (keys %$fetch) {
1510 next if $f ne $p;
1511 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1514 undef;
1517 sub init {
1518 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1519 my $self = _new($class, $repo_id, $ref_id, $path);
1520 if (defined $url) {
1521 $self->init_remote_config($url, $no_write);
1523 $self;
1526 sub find_ref {
1527 my ($ref_id) = @_;
1528 foreach (command(qw/config -l/)) {
1529 next unless m!^svn-remote\.(.+)\.fetch=
1530 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1531 my ($repo_id, $path, $ref) = ($1, $2, $3);
1532 if ($ref eq $ref_id) {
1533 $path = '' if ($path =~ m#^\./?#);
1534 return ($repo_id, $path);
1537 (undef, undef, undef);
1540 sub new {
1541 my ($class, $ref_id, $repo_id, $path) = @_;
1542 if (defined $ref_id && !defined $repo_id && !defined $path) {
1543 ($repo_id, $path) = find_ref($ref_id);
1544 if (!defined $repo_id) {
1545 die "Could not find a \"svn-remote.*.fetch\" key ",
1546 "in the repository configuration matching: ",
1547 "refs/remotes/$ref_id\n";
1550 my $self = _new($class, $repo_id, $ref_id, $path);
1551 if (!defined $self->{path} || !length $self->{path}) {
1552 my $fetch = command_oneline('config', '--get',
1553 "svn-remote.$repo_id.fetch",
1554 ":refs/remotes/$ref_id\$") or
1555 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1556 "\":refs/remotes/$ref_id\$\" in config\n";
1557 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1559 $self->{url} = command_oneline('config', '--get',
1560 "svn-remote.$repo_id.url") or
1561 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1562 $self->rebuild;
1563 $self;
1566 sub refname {
1567 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1569 # It cannot end with a slash /, we'll throw up on this because
1570 # SVN can't have directories with a slash in their name, either:
1571 if ($refname =~ m{/$}) {
1572 die "ref: '$refname' ends with a trailing slash, this is ",
1573 "not permitted by git nor Subversion\n";
1576 # It cannot have ASCII control character space, tilde ~, caret ^,
1577 # colon :, question-mark ?, asterisk *, space, or open bracket [
1578 # anywhere.
1580 # Additionally, % must be escaped because it is used for escaping
1581 # and we want our escaped refname to be reversible
1582 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1584 # no slash-separated component can begin with a dot .
1585 # /.* becomes /%2E*
1586 $refname =~ s{/\.}{/%2E}g;
1588 # It cannot have two consecutive dots .. anywhere
1589 # .. becomes %2E%2E
1590 $refname =~ s{\.\.}{%2E%2E}g;
1592 return $refname;
1595 sub desanitize_refname {
1596 my ($refname) = @_;
1597 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1598 return $refname;
1601 sub svm_uuid {
1602 my ($self) = @_;
1603 return $self->{svm}->{uuid} if $self->svm;
1604 $self->ra;
1605 unless ($self->{svm}) {
1606 die "SVM UUID not cached, and reading remotely failed\n";
1608 $self->{svm}->{uuid};
1611 sub svm {
1612 my ($self) = @_;
1613 return $self->{svm} if $self->{svm};
1614 my $svm;
1615 # see if we have it in our config, first:
1616 eval {
1617 my $section = "svn-remote.$self->{repo_id}";
1618 $svm = {
1619 source => tmp_config('--get', "$section.svm-source"),
1620 uuid => tmp_config('--get', "$section.svm-uuid"),
1621 replace => tmp_config('--get', "$section.svm-replace"),
1624 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1625 $self->{svm} = $svm;
1627 $self->{svm};
1630 sub _set_svm_vars {
1631 my ($self, $ra) = @_;
1632 return $ra if $self->svm;
1634 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1635 "(svm:source, svm:uuid) ",
1636 "from the following URLs:\n" );
1637 sub read_svm_props {
1638 my ($self, $ra, $path, $r) = @_;
1639 my $props = ($ra->get_dir($path, $r))[2];
1640 my $src = $props->{'svm:source'};
1641 my $uuid = $props->{'svm:uuid'};
1642 return undef if (!$src || !$uuid);
1644 chomp($src, $uuid);
1646 $uuid =~ m{^[0-9a-f\-]{30,}$}
1647 or die "doesn't look right - svm:uuid is '$uuid'\n";
1649 # the '!' is used to mark the repos_root!/relative/path
1650 $src =~ s{/?!/?}{/};
1651 $src =~ s{/+$}{}; # no trailing slashes please
1652 # username is of no interest
1653 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1655 my $replace = $ra->{url};
1656 $replace .= "/$path" if length $path;
1658 my $section = "svn-remote.$self->{repo_id}";
1659 tmp_config("$section.svm-source", $src);
1660 tmp_config("$section.svm-replace", $replace);
1661 tmp_config("$section.svm-uuid", $uuid);
1662 $self->{svm} = {
1663 source => $src,
1664 uuid => $uuid,
1665 replace => $replace
1669 my $r = $ra->get_latest_revnum;
1670 my $path = $self->{path};
1671 my %tried;
1672 while (length $path) {
1673 unless ($tried{"$self->{url}/$path"}) {
1674 return $ra if $self->read_svm_props($ra, $path, $r);
1675 $tried{"$self->{url}/$path"} = 1;
1677 $path =~ s#/?[^/]+$##;
1679 die "Path: '$path' should be ''\n" if $path ne '';
1680 return $ra if $self->read_svm_props($ra, $path, $r);
1681 $tried{"$self->{url}/$path"} = 1;
1683 if ($ra->{repos_root} eq $self->{url}) {
1684 die @err, (map { " $_\n" } keys %tried), "\n";
1687 # nope, make sure we're connected to the repository root:
1688 my $ok;
1689 my @tried_b;
1690 $path = $ra->{svn_path};
1691 $ra = Git::SVN::Ra->new($ra->{repos_root});
1692 while (length $path) {
1693 unless ($tried{"$ra->{url}/$path"}) {
1694 $ok = $self->read_svm_props($ra, $path, $r);
1695 last if $ok;
1696 $tried{"$ra->{url}/$path"} = 1;
1698 $path =~ s#/?[^/]+$##;
1700 die "Path: '$path' should be ''\n" if $path ne '';
1701 $ok ||= $self->read_svm_props($ra, $path, $r);
1702 $tried{"$ra->{url}/$path"} = 1;
1703 if (!$ok) {
1704 die @err, (map { " $_\n" } keys %tried), "\n";
1706 Git::SVN::Ra->new($self->{url});
1709 sub svnsync {
1710 my ($self) = @_;
1711 return $self->{svnsync} if $self->{svnsync};
1713 if ($self->no_metadata) {
1714 die "Can't have both 'noMetadata' and ",
1715 "'useSvnsyncProps' options set!\n";
1717 if ($self->rewrite_root) {
1718 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1719 "options set!\n";
1722 my $svnsync;
1723 # see if we have it in our config, first:
1724 eval {
1725 my $section = "svn-remote.$self->{repo_id}";
1726 $svnsync = {
1727 url => tmp_config('--get', "$section.svnsync-url"),
1728 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1731 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1732 return $self->{svnsync} = $svnsync;
1735 my $err = "useSvnsyncProps set, but failed to read " .
1736 "svnsync property: svn:sync-from-";
1737 my $rp = $self->ra->rev_proplist(0);
1739 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1740 $url =~ m{^[a-z\+]+://} or
1741 die "doesn't look right - svn:sync-from-url is '$url'\n";
1743 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1744 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1745 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1747 my $section = "svn-remote.$self->{repo_id}";
1748 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1749 tmp_config('--add', "$section.svnsync-url", $url);
1750 return $self->{svnsync} = { url => $url, uuid => $uuid };
1753 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1754 # remote lookup (useful for 'git svn log').
1755 sub ra_uuid {
1756 my ($self) = @_;
1757 unless ($self->{ra_uuid}) {
1758 my $key = "svn-remote.$self->{repo_id}.uuid";
1759 my $uuid = eval { tmp_config('--get', $key) };
1760 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1761 $self->{ra_uuid} = $uuid;
1762 } else {
1763 die "ra_uuid called without URL\n" unless $self->{url};
1764 $self->{ra_uuid} = $self->ra->get_uuid;
1765 tmp_config('--add', $key, $self->{ra_uuid});
1768 $self->{ra_uuid};
1771 sub ra {
1772 my ($self) = shift;
1773 my $ra = Git::SVN::Ra->new($self->{url});
1774 if ($self->use_svm_props && !$self->{svm}) {
1775 if ($self->no_metadata) {
1776 die "Can't have both 'noMetadata' and ",
1777 "'useSvmProps' options set!\n";
1778 } elsif ($self->use_svnsync_props) {
1779 die "Can't have both 'useSvnsyncProps' and ",
1780 "'useSvmProps' options set!\n";
1782 $ra = $self->_set_svm_vars($ra);
1783 $self->{-want_revprops} = 1;
1785 $ra;
1788 sub rel_path {
1789 my ($self) = @_;
1790 my $repos_root = $self->ra->{repos_root};
1791 return $self->{path} if ($self->{url} eq $repos_root);
1792 my $url = $self->{url} .
1793 (length $self->{path} ? "/$self->{path}" : $self->{path});
1794 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1795 $url;
1798 # prop_walk(PATH, REV, SUB)
1799 # -------------------------
1800 # Recursively traverse PATH at revision REV and invoke SUB for each
1801 # directory that contains a SVN property. SUB will be invoked as
1802 # follows: &SUB(gs, path, props); where `gs' is this instance of
1803 # Git::SVN, `path' the path to the directory where the properties
1804 # `props' were found. The `path' will be relative to point of checkout,
1805 # that is, if url://repo/trunk is the current Git branch, and that
1806 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1807 # as `path' (note the trailing `/').
1808 sub prop_walk {
1809 my ($self, $path, $rev, $sub) = @_;
1811 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1812 $path =~ s#^/*#/#g;
1813 my $p = $path;
1814 # Strip the irrelevant part of the path.
1815 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1816 # Ensure the path is terminated by a `/'.
1817 $p =~ s#/*$#/#;
1819 # The properties contain all the internal SVN stuff nobody
1820 # (usually) cares about.
1821 my $interesting_props = 0;
1822 foreach (keys %{$props}) {
1823 # If it doesn't start with `svn:', it must be a
1824 # user-defined property.
1825 ++$interesting_props and next if $_ !~ /^svn:/;
1826 # FIXME: Fragile, if SVN adds new public properties,
1827 # this needs to be updated.
1828 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1829 |eol-style|mime-type
1830 |externals|needs-lock)$/x;
1832 &$sub($self, $p, $props) if $interesting_props;
1834 foreach (sort keys %$dirent) {
1835 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1836 $self->prop_walk($path . '/' . $_, $rev, $sub);
1840 sub last_rev { ($_[0]->last_rev_commit)[0] }
1841 sub last_commit { ($_[0]->last_rev_commit)[1] }
1843 # returns the newest SVN revision number and newest commit SHA1
1844 sub last_rev_commit {
1845 my ($self) = @_;
1846 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1847 return ($self->{last_rev}, $self->{last_commit});
1849 my $c = ::verify_ref($self->refname.'^0');
1850 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1851 my $rev = (::cmt_metadata($c))[1];
1852 if (defined $rev) {
1853 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1854 return ($rev, $c);
1857 my $db_path = $self->db_path;
1858 unless (-e $db_path) {
1859 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1860 return (undef, undef);
1862 my $offset = -41; # from tail
1863 my $rl;
1864 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1865 sysseek($fh, $offset, 2); # don't care for errors
1866 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1867 chomp $rl;
1868 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1869 $offset -= 41;
1870 sysseek($fh, $offset, 2); # don't care for errors
1871 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1872 chomp $rl;
1874 if ($c && $c ne $rl) {
1875 die "$db_path and ", $self->refname,
1876 " inconsistent!:\n$c != $rl\n";
1878 my $rev = sysseek($fh, 0, 1) or croak $!;
1879 $rev = ($rev - 41) / 41;
1880 close $fh or croak $!;
1881 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1882 return ($rev, $c);
1885 sub get_fetch_range {
1886 my ($self, $min, $max) = @_;
1887 $max ||= $self->ra->get_latest_revnum;
1888 $min ||= $self->rev_db_max;
1889 (++$min, $max);
1892 sub tmp_config {
1893 my (@args) = @_;
1894 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1895 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1896 if (! -f $config && -f $old_def_config) {
1897 rename $old_def_config, $config or
1898 die "Failed rename $old_def_config => $config: $!\n";
1900 my $old_config = $ENV{GIT_CONFIG};
1901 $ENV{GIT_CONFIG} = $config;
1902 $@ = undef;
1903 my @ret = eval {
1904 unless (-f $config) {
1905 mkfile($config);
1906 open my $fh, '>', $config or
1907 die "Can't open $config: $!\n";
1908 print $fh "; This file is used internally by ",
1909 "git-svn\n" or die
1910 "Couldn't write to $config: $!\n";
1911 print $fh "; You should not have to edit it\n" or
1912 die "Couldn't write to $config: $!\n";
1913 close $fh or die "Couldn't close $config: $!\n";
1915 command('config', @args);
1917 my $err = $@;
1918 if (defined $old_config) {
1919 $ENV{GIT_CONFIG} = $old_config;
1920 } else {
1921 delete $ENV{GIT_CONFIG};
1923 die $err if $err;
1924 wantarray ? @ret : $ret[0];
1927 sub tmp_index_do {
1928 my ($self, $sub) = @_;
1929 my $old_index = $ENV{GIT_INDEX_FILE};
1930 $ENV{GIT_INDEX_FILE} = $self->{index};
1931 $@ = undef;
1932 my @ret = eval {
1933 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1934 mkpath([$dir]) unless -d $dir;
1935 &$sub;
1937 my $err = $@;
1938 if (defined $old_index) {
1939 $ENV{GIT_INDEX_FILE} = $old_index;
1940 } else {
1941 delete $ENV{GIT_INDEX_FILE};
1943 die $err if $err;
1944 wantarray ? @ret : $ret[0];
1947 sub assert_index_clean {
1948 my ($self, $treeish) = @_;
1950 $self->tmp_index_do(sub {
1951 command_noisy('read-tree', $treeish) unless -e $self->{index};
1952 my $x = command_oneline('write-tree');
1953 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1954 /^tree ($::sha1)/mo);
1955 return if $y eq $x;
1957 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1958 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1959 command_noisy('read-tree', $treeish);
1960 $x = command_oneline('write-tree');
1961 if ($y ne $x) {
1962 ::fatal "trees ($treeish) $y != $x\n",
1963 "Something is seriously wrong...";
1968 sub get_commit_parents {
1969 my ($self, $log_entry) = @_;
1970 my (%seen, @ret, @tmp);
1971 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1972 if (my $ip = $self->{inject_parents}) {
1973 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1974 push @tmp, $commit;
1977 if (my $cur = ::verify_ref($self->refname.'^0')) {
1978 push @tmp, $cur;
1980 if (my $ipd = $self->{inject_parents_dcommit}) {
1981 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1982 push @tmp, @$commit;
1985 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1986 while (my $p = shift @tmp) {
1987 next if $seen{$p};
1988 $seen{$p} = 1;
1989 push @ret, $p;
1990 # MAXPARENT is defined to 16 in commit-tree.c:
1991 last if @ret >= 16;
1993 if (@tmp) {
1994 die "r$log_entry->{revision}: No room for parents:\n\t",
1995 join("\n\t", @tmp), "\n";
1997 @ret;
2000 sub rewrite_root {
2001 my ($self) = @_;
2002 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2003 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2004 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2005 if ($rwr) {
2006 $rwr =~ s#/+$##;
2007 if ($rwr !~ m#^[a-z\+]+://#) {
2008 die "$rwr is not a valid URL (key: $k)\n";
2011 $self->{-rewrite_root} = $rwr;
2014 sub metadata_url {
2015 my ($self) = @_;
2016 ($self->rewrite_root || $self->{url}) .
2017 (length $self->{path} ? '/' . $self->{path} : '');
2020 sub full_url {
2021 my ($self) = @_;
2022 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2025 sub do_git_commit {
2026 my ($self, $log_entry) = @_;
2027 my $lr = $self->last_rev;
2028 if (defined $lr && $lr >= $log_entry->{revision}) {
2029 die "Last fetched revision of ", $self->refname,
2030 " was r$lr, but we are about to fetch: ",
2031 "r$log_entry->{revision}!\n";
2033 if (my $c = $self->rev_db_get($log_entry->{revision})) {
2034 croak "$log_entry->{revision} = $c already exists! ",
2035 "Why are we refetching it?\n";
2037 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
2038 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
2039 $log_entry->{email};
2040 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2042 my $tree = $log_entry->{tree};
2043 if (!defined $tree) {
2044 $tree = $self->tmp_index_do(sub {
2045 command_oneline('write-tree') });
2047 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2049 my @exec = ('git-commit-tree', $tree);
2050 foreach ($self->get_commit_parents($log_entry)) {
2051 push @exec, '-p', $_;
2053 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2054 or croak $!;
2055 print $msg_fh $log_entry->{log} or croak $!;
2056 unless ($self->no_metadata) {
2057 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2058 or croak $!;
2060 $msg_fh->flush == 0 or croak $!;
2061 close $msg_fh or croak $!;
2062 chomp(my $commit = do { local $/; <$out_fh> });
2063 close $out_fh or croak $!;
2064 waitpid $pid, 0;
2065 croak $? if $?;
2066 if ($commit !~ /^$::sha1$/o) {
2067 die "Failed to commit, invalid sha1: $commit\n";
2070 $self->rev_db_set($log_entry->{revision}, $commit, 1);
2072 $self->{last_rev} = $log_entry->{revision};
2073 $self->{last_commit} = $commit;
2074 print "r$log_entry->{revision}";
2075 if (defined $log_entry->{svm_revision}) {
2076 print " (\@$log_entry->{svm_revision})";
2077 $self->rev_db_set($log_entry->{svm_revision}, $commit,
2078 0, $self->svm_uuid);
2080 print " = $commit ($self->{ref_id})\n";
2081 if (defined $_repack && (--$_repack_nr == 0)) {
2082 $_repack_nr = $_repack;
2083 # repack doesn't use any arguments with spaces in them, does it?
2084 print "Running git repack $_repack_flags ...\n";
2085 command_noisy('repack', split(/\s+/, $_repack_flags));
2086 print "Done repacking\n";
2088 return $commit;
2091 sub match_paths {
2092 my ($self, $paths, $r) = @_;
2093 return 1 if $self->{path} eq '';
2094 if (my $path = $paths->{"/$self->{path}"}) {
2095 return ($path->{action} eq 'D') ? 0 : 1;
2097 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2098 if (grep /$self->{path_regex}/, keys %$paths) {
2099 return 1;
2101 my $c = '';
2102 foreach (split m#/#, $self->{path}) {
2103 $c .= "/$_";
2104 next unless ($paths->{$c} &&
2105 ($paths->{$c}->{action} =~ /^[AR]$/));
2106 if ($self->ra->check_path($self->{path}, $r) ==
2107 $SVN::Node::dir) {
2108 return 1;
2111 return 0;
2114 sub find_parent_branch {
2115 my ($self, $paths, $rev) = @_;
2116 return undef unless $self->follow_parent;
2117 unless (defined $paths) {
2118 my $err_handler = $SVN::Error::handler;
2119 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2120 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2121 $paths =
2122 Git::SVN::Ra::dup_changed_paths($_[0]) });
2123 $SVN::Error::handler = $err_handler;
2125 return undef unless defined $paths;
2127 # look for a parent from another branch:
2128 my @b_path_components = split m#/#, $self->rel_path;
2129 my @a_path_components;
2130 my $i;
2131 while (@b_path_components) {
2132 $i = $paths->{'/'.join('/', @b_path_components)};
2133 last if $i && defined $i->{copyfrom_path};
2134 unshift(@a_path_components, pop(@b_path_components));
2136 return undef unless defined $i && defined $i->{copyfrom_path};
2137 my $branch_from = $i->{copyfrom_path};
2138 if (@a_path_components) {
2139 print STDERR "branch_from: $branch_from => ";
2140 $branch_from .= '/'.join('/', @a_path_components);
2141 print STDERR $branch_from, "\n";
2143 my $r = $i->{copyfrom_rev};
2144 my $repos_root = $self->ra->{repos_root};
2145 my $url = $self->ra->{url};
2146 my $new_url = $repos_root . $branch_from;
2147 print STDERR "Found possible branch point: ",
2148 "$new_url => ", $self->full_url, ", $r\n";
2149 $branch_from =~ s#^/##;
2150 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2151 unless ($gs) {
2152 my $ref_id = $self->{ref_id};
2153 $ref_id =~ s/\@\d+$//;
2154 $ref_id .= "\@$r";
2155 # just grow a tail if we're not unique enough :x
2156 $ref_id .= '-' while find_ref($ref_id);
2157 print STDERR "Initializing parent: $ref_id\n";
2158 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
2160 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2161 if (!defined $r0 || !defined $parent) {
2162 my ($base, $head) = parse_revision_argument(0, $r);
2163 if ($base <= $r) {
2164 $gs->fetch($base, $r);
2166 ($r0, $parent) = $gs->last_rev_commit;
2168 if (defined $r0 && defined $parent) {
2169 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2170 my $ed;
2171 if ($self->ra->can_do_switch) {
2172 $self->assert_index_clean($parent);
2173 print STDERR "Following parent with do_switch\n";
2174 # do_switch works with svn/trunk >= r22312, but that
2175 # is not included with SVN 1.4.3 (the latest version
2176 # at the moment), so we can't rely on it
2177 $self->{last_commit} = $parent;
2178 $ed = SVN::Git::Fetcher->new($self);
2179 $gs->ra->gs_do_switch($r0, $rev, $gs,
2180 $self->full_url, $ed)
2181 or die "SVN connection failed somewhere...\n";
2182 } elsif ($self->ra->trees_match($new_url, $r0,
2183 $self->full_url, $rev)) {
2184 print STDERR "Trees match:\n",
2185 " $new_url\@$r0\n",
2186 " ${\$self->full_url}\@$rev\n",
2187 "Following parent with no changes\n";
2188 $self->tmp_index_do(sub {
2189 command_noisy('read-tree', $parent);
2191 $self->{last_commit} = $parent;
2192 } else {
2193 print STDERR "Following parent with do_update\n";
2194 $ed = SVN::Git::Fetcher->new($self);
2195 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2196 or die "SVN connection failed somewhere...\n";
2198 print STDERR "Successfully followed parent\n";
2199 return $self->make_log_entry($rev, [$parent], $ed);
2201 return undef;
2204 sub do_fetch {
2205 my ($self, $paths, $rev) = @_;
2206 my $ed;
2207 my ($last_rev, @parents);
2208 if (my $lc = $self->last_commit) {
2209 # we can have a branch that was deleted, then re-added
2210 # under the same name but copied from another path, in
2211 # which case we'll have multiple parents (we don't
2212 # want to break the original ref, nor lose copypath info):
2213 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2214 push @{$log_entry->{parents}}, $lc;
2215 return $log_entry;
2217 $ed = SVN::Git::Fetcher->new($self);
2218 $last_rev = $self->{last_rev};
2219 $ed->{c} = $lc;
2220 @parents = ($lc);
2221 } else {
2222 $last_rev = $rev;
2223 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2224 return $log_entry;
2226 $ed = SVN::Git::Fetcher->new($self);
2228 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2229 die "SVN connection failed somewhere...\n";
2231 $self->make_log_entry($rev, \@parents, $ed);
2234 sub get_untracked {
2235 my ($self, $ed) = @_;
2236 my @out;
2237 my $h = $ed->{empty};
2238 foreach (sort keys %$h) {
2239 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2240 push @out, " $act: " . uri_encode($_);
2241 warn "W: $act: $_\n";
2243 foreach my $t (qw/dir_prop file_prop/) {
2244 $h = $ed->{$t} or next;
2245 foreach my $path (sort keys %$h) {
2246 my $ppath = $path eq '' ? '.' : $path;
2247 foreach my $prop (sort keys %{$h->{$path}}) {
2248 next if $SKIP_PROP{$prop};
2249 my $v = $h->{$path}->{$prop};
2250 my $t_ppath_prop = "$t: " .
2251 uri_encode($ppath) . ' ' .
2252 uri_encode($prop);
2253 if (defined $v) {
2254 push @out, " +$t_ppath_prop " .
2255 uri_encode($v);
2256 } else {
2257 push @out, " -$t_ppath_prop";
2262 foreach my $t (qw/absent_file absent_directory/) {
2263 $h = $ed->{$t} or next;
2264 foreach my $parent (sort keys %$h) {
2265 foreach my $path (sort @{$h->{$parent}}) {
2266 push @out, " $t: " .
2267 uri_encode("$parent/$path");
2268 warn "W: $t: $parent/$path ",
2269 "Insufficient permissions?\n";
2273 \@out;
2276 sub parse_svn_date {
2277 my $date = shift || return '+0000 1970-01-01 00:00:00';
2278 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2279 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2280 croak "Unable to parse date: $date\n";
2281 "+0000 $Y-$m-$d $H:$M:$S";
2284 sub check_author {
2285 my ($author) = @_;
2286 if (!defined $author || length $author == 0) {
2287 $author = '(no author)';
2289 if (defined $::_authors && ! defined $::users{$author}) {
2290 die "Author: $author not defined in $::_authors file\n";
2292 $author;
2295 sub make_log_entry {
2296 my ($self, $rev, $parents, $ed) = @_;
2297 my $untracked = $self->get_untracked($ed);
2299 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2300 print $un "r$rev\n" or croak $!;
2301 print $un $_, "\n" foreach @$untracked;
2302 my %log_entry = ( parents => $parents || [], revision => $rev,
2303 log => '');
2305 my $headrev;
2306 my $logged = delete $self->{logged_rev_props};
2307 if (!$logged || $self->{-want_revprops}) {
2308 my $rp = $self->ra->rev_proplist($rev);
2309 foreach (sort keys %$rp) {
2310 my $v = $rp->{$_};
2311 if (/^svn:(author|date|log)$/) {
2312 $log_entry{$1} = $v;
2313 } elsif ($_ eq 'svm:headrev') {
2314 $headrev = $v;
2315 } else {
2316 print $un " rev_prop: ", uri_encode($_), ' ',
2317 uri_encode($v), "\n";
2320 } else {
2321 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2323 close $un or croak $!;
2325 $log_entry{date} = parse_svn_date($log_entry{date});
2326 $log_entry{log} .= "\n";
2327 my $author = $log_entry{author} = check_author($log_entry{author});
2328 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2329 : ($author, undef);
2330 if (defined $headrev && $self->use_svm_props) {
2331 if ($self->rewrite_root) {
2332 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2333 "options set!\n";
2335 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2336 # we don't want "SVM: initializing mirror for junk" ...
2337 return undef if $r == 0;
2338 my $svm = $self->svm;
2339 if ($uuid ne $svm->{uuid}) {
2340 die "UUID mismatch on SVM path:\n",
2341 "expected: $svm->{uuid}\n",
2342 " got: $uuid\n";
2344 my $full_url = $self->full_url;
2345 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2346 die "Failed to replace '$svm->{replace}' with ",
2347 "'$svm->{source}' in $full_url\n";
2348 # throw away username for storing in records
2349 remove_username($full_url);
2350 $log_entry{metadata} = "$full_url\@$r $uuid";
2351 $log_entry{svm_revision} = $r;
2352 $email ||= "$author\@$uuid"
2353 } elsif ($self->use_svnsync_props) {
2354 my $full_url = $self->svnsync->{url};
2355 $full_url .= "/$self->{path}" if length $self->{path};
2356 remove_username($full_url);
2357 my $uuid = $self->svnsync->{uuid};
2358 $log_entry{metadata} = "$full_url\@$rev $uuid";
2359 $email ||= "$author\@$uuid"
2360 } else {
2361 my $url = $self->metadata_url;
2362 remove_username($url);
2363 $log_entry{metadata} = "$url\@$rev " .
2364 $self->ra->get_uuid;
2365 $email ||= "$author\@" . $self->ra->get_uuid;
2367 $log_entry{name} = $name;
2368 $log_entry{email} = $email;
2369 \%log_entry;
2372 sub fetch {
2373 my ($self, $min_rev, $max_rev, @parents) = @_;
2374 my ($last_rev, $last_commit) = $self->last_rev_commit;
2375 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2376 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2379 sub set_tree_cb {
2380 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2381 $self->{inject_parents} = { $rev => $tree };
2382 $self->fetch(undef, undef);
2385 sub set_tree {
2386 my ($self, $tree) = (shift, shift);
2387 my $log_entry = ::get_commit_entry($tree);
2388 unless ($self->{last_rev}) {
2389 fatal("Must have an existing revision to commit");
2391 my %ed_opts = ( r => $self->{last_rev},
2392 log => $log_entry->{log},
2393 ra => $self->ra,
2394 tree_a => $self->{last_commit},
2395 tree_b => $tree,
2396 editor_cb => sub {
2397 $self->set_tree_cb($log_entry, $tree, @_) },
2398 svn_path => $self->{path} );
2399 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2400 print "No changes\nr$self->{last_rev} = $tree\n";
2404 sub rebuild {
2405 my ($self) = @_;
2406 my $db_path = $self->db_path;
2407 return if (-e $db_path && ! -z $db_path);
2408 return unless ::verify_ref($self->refname.'^0');
2409 if (-f $self->{db_root}) {
2410 rename $self->{db_root}, $db_path or die
2411 "rename $self->{db_root} => $db_path failed: $!\n";
2412 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2413 symlink $base, $self->{db_root} or die
2414 "symlink $base => $self->{db_root} failed: $!\n";
2415 return;
2417 print "Rebuilding $db_path ...\n";
2418 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2419 my $latest;
2420 my $full_url = $self->full_url;
2421 remove_username($full_url);
2422 my $svn_uuid;
2423 my $c;
2424 while (<$log>) {
2425 if ( m{^commit ($::sha1)$} ) {
2426 $c = $1;
2427 next;
2429 next unless s{^\s*(git-svn-id:)}{$1};
2430 my ($url, $rev, $uuid) = ::extract_metadata($_);
2431 remove_username($url);
2433 # ignore merges (from set-tree)
2434 next if (!defined $rev || !$uuid);
2436 # if we merged or otherwise started elsewhere, this is
2437 # how we break out of it
2438 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2439 ($full_url && $url && ($url ne $full_url))) {
2440 next;
2442 $latest ||= $rev;
2443 $svn_uuid ||= $uuid;
2445 $self->rev_db_set($rev, $c);
2446 print "r$rev = $c\n";
2448 command_close_pipe($log, $ctx);
2449 print "Done rebuilding $db_path\n";
2452 # rev_db:
2453 # Tie::File seems to be prone to offset errors if revisions get sparse,
2454 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2455 # one of my favorite modules is out :< Next up would be one of the DBM
2456 # modules, but I'm not sure which is most portable... So I'll just
2457 # go with something that's plain-text, but still capable of
2458 # being randomly accessed. So here's my ultra-simple fixed-width
2459 # database. All records are 40 characters + "\n", so it's easy to seek
2460 # to a revision: (41 * rev) is the byte offset.
2461 # A record of 40 0s denotes an empty revision.
2462 # And yes, it's still pretty fast (faster than Tie::File).
2463 # These files are disposable unless noMetadata or useSvmProps is set
2465 sub _rev_db_set {
2466 my ($fh, $rev, $commit) = @_;
2467 my $offset = $rev * 41;
2468 # assume that append is the common case:
2469 seek $fh, 0, 2 or croak $!;
2470 my $pos = tell $fh;
2471 if ($pos < $offset) {
2472 for (1 .. (($offset - $pos) / 41)) {
2473 print $fh (('0' x 40),"\n") or croak $!;
2476 seek $fh, $offset, 0 or croak $!;
2477 print $fh $commit,"\n" or croak $!;
2480 sub mkfile {
2481 my ($path) = @_;
2482 unless (-e $path) {
2483 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2484 mkpath([$dir]) unless -d $dir;
2485 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2486 close $fh or die "Couldn't close (create) $path: $!\n";
2490 sub rev_db_set {
2491 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2492 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2493 my $db = $self->db_path($uuid);
2494 my $db_lock = "$db.lock";
2495 my $sig;
2496 if ($update_ref) {
2497 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2498 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2500 mkfile($db);
2502 $LOCKFILES{$db_lock} = 1;
2503 my $sync;
2504 # both of these options make our .rev_db file very, very important
2505 # and we can't afford to lose it because rebuild() won't work
2506 if ($self->use_svm_props || $self->no_metadata) {
2507 $sync = 1;
2508 copy($db, $db_lock) or die "rev_db_set(@_): ",
2509 "Failed to copy: ",
2510 "$db => $db_lock ($!)\n";
2511 } else {
2512 rename $db, $db_lock or die "rev_db_set(@_): ",
2513 "Failed to rename: ",
2514 "$db => $db_lock ($!)\n";
2516 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2517 _rev_db_set($fh, $rev, $commit);
2518 if ($sync) {
2519 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2520 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2522 close $fh or croak $!;
2523 if ($update_ref) {
2524 $_head = $self;
2525 command_noisy('update-ref', '-m', "r$rev",
2526 $self->refname, $commit);
2528 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2529 "$db_lock => $db ($!)\n";
2530 delete $LOCKFILES{$db_lock};
2531 if ($update_ref) {
2532 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2533 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2534 kill $sig, $$ if defined $sig;
2538 sub rev_db_max {
2539 my ($self) = @_;
2540 $self->rebuild;
2541 my $db_path = $self->db_path;
2542 my @stat = stat $db_path or return 0;
2543 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2544 my $max = $stat[7] / 41;
2545 (($max > 0) ? $max - 1 : 0);
2548 sub rev_db_get {
2549 my ($self, $rev, $uuid) = @_;
2550 my $ret;
2551 my $offset = $rev * 41;
2552 my $db_path = $self->db_path($uuid);
2553 return undef unless -e $db_path;
2554 open my $fh, '<', $db_path or croak $!;
2555 if (sysseek($fh, $offset, 0) == $offset) {
2556 my $read = sysread($fh, $ret, 40);
2557 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2559 close $fh or croak $!;
2560 $ret;
2563 # Finds the first svn revision that exists on (if $eq_ok is true) or
2564 # before $rev for the current branch. It will not search any lower
2565 # than $min_rev. Returns the git commit hash and svn revision number
2566 # if found, else (undef, undef).
2567 sub find_rev_before {
2568 my ($self, $rev, $eq_ok, $min_rev) = @_;
2569 --$rev unless $eq_ok;
2570 $min_rev ||= 1;
2571 while ($rev >= $min_rev) {
2572 if (my $c = $self->rev_db_get($rev)) {
2573 return ($rev, $c);
2575 --$rev;
2577 return (undef, undef);
2580 # Finds the first svn revision that exists on (if $eq_ok is true) or
2581 # after $rev for the current branch. It will not search any higher
2582 # than $max_rev. Returns the git commit hash and svn revision number
2583 # if found, else (undef, undef).
2584 sub find_rev_after {
2585 my ($self, $rev, $eq_ok, $max_rev) = @_;
2586 ++$rev unless $eq_ok;
2587 $max_rev ||= $self->rev_db_max();
2588 while ($rev <= $max_rev) {
2589 if (my $c = $self->rev_db_get($rev)) {
2590 return ($rev, $c);
2592 ++$rev;
2594 return (undef, undef);
2597 sub _new {
2598 my ($class, $repo_id, $ref_id, $path) = @_;
2599 unless (defined $repo_id && length $repo_id) {
2600 $repo_id = $Git::SVN::default_repo_id;
2602 unless (defined $ref_id && length $ref_id) {
2603 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2605 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2606 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2607 $_[3] = $path = '' unless (defined $path);
2608 mkpath(["$ENV{GIT_DIR}/svn"]);
2609 bless {
2610 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2611 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2612 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2615 sub db_path {
2616 my ($self, $uuid) = @_;
2617 $uuid ||= $self->ra_uuid;
2618 "$self->{db_root}.$uuid";
2621 sub uri_encode {
2622 my ($f) = @_;
2623 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2627 sub remove_username {
2628 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2631 package Git::SVN::Prompt;
2632 use strict;
2633 use warnings;
2634 require SVN::Core;
2635 use vars qw/$_no_auth_cache $_username/;
2637 sub simple {
2638 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2639 $may_save = undef if $_no_auth_cache;
2640 $default_username = $_username if defined $_username;
2641 if (defined $default_username && length $default_username) {
2642 if (defined $realm && length $realm) {
2643 print STDERR "Authentication realm: $realm\n";
2644 STDERR->flush;
2646 $cred->username($default_username);
2647 } else {
2648 username($cred, $realm, $may_save, $pool);
2650 $cred->password(_read_password("Password for '" .
2651 $cred->username . "': ", $realm));
2652 $cred->may_save($may_save);
2653 $SVN::_Core::SVN_NO_ERROR;
2656 sub ssl_server_trust {
2657 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2658 $may_save = undef if $_no_auth_cache;
2659 print STDERR "Error validating server certificate for '$realm':\n";
2661 no warnings 'once';
2662 # All variables SVN::Auth::SSL::* are used only once,
2663 # so we're shutting up Perl warnings about this.
2664 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2665 print STDERR " - The certificate is not issued ",
2666 "by a trusted authority. Use the\n",
2667 " fingerprint to validate ",
2668 "the certificate manually!\n";
2670 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2671 print STDERR " - The certificate hostname ",
2672 "does not match.\n";
2674 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2675 print STDERR " - The certificate is not yet valid.\n";
2677 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2678 print STDERR " - The certificate has expired.\n";
2680 if ($failures & $SVN::Auth::SSL::OTHER) {
2681 print STDERR " - The certificate has ",
2682 "an unknown error.\n";
2684 } # no warnings 'once'
2685 printf STDERR
2686 "Certificate information:\n".
2687 " - Hostname: %s\n".
2688 " - Valid: from %s until %s\n".
2689 " - Issuer: %s\n".
2690 " - Fingerprint: %s\n",
2691 map $cert_info->$_, qw(hostname valid_from valid_until
2692 issuer_dname fingerprint);
2693 my $choice;
2694 prompt:
2695 print STDERR $may_save ?
2696 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2697 "(R)eject or accept (t)emporarily? ";
2698 STDERR->flush;
2699 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2700 if ($choice =~ /^t$/i) {
2701 $cred->may_save(undef);
2702 } elsif ($choice =~ /^r$/i) {
2703 return -1;
2704 } elsif ($may_save && $choice =~ /^p$/i) {
2705 $cred->may_save($may_save);
2706 } else {
2707 goto prompt;
2709 $cred->accepted_failures($failures);
2710 $SVN::_Core::SVN_NO_ERROR;
2713 sub ssl_client_cert {
2714 my ($cred, $realm, $may_save, $pool) = @_;
2715 $may_save = undef if $_no_auth_cache;
2716 print STDERR "Client certificate filename: ";
2717 STDERR->flush;
2718 chomp(my $filename = <STDIN>);
2719 $cred->cert_file($filename);
2720 $cred->may_save($may_save);
2721 $SVN::_Core::SVN_NO_ERROR;
2724 sub ssl_client_cert_pw {
2725 my ($cred, $realm, $may_save, $pool) = @_;
2726 $may_save = undef if $_no_auth_cache;
2727 $cred->password(_read_password("Password: ", $realm));
2728 $cred->may_save($may_save);
2729 $SVN::_Core::SVN_NO_ERROR;
2732 sub username {
2733 my ($cred, $realm, $may_save, $pool) = @_;
2734 $may_save = undef if $_no_auth_cache;
2735 if (defined $realm && length $realm) {
2736 print STDERR "Authentication realm: $realm\n";
2738 my $username;
2739 if (defined $_username) {
2740 $username = $_username;
2741 } else {
2742 print STDERR "Username: ";
2743 STDERR->flush;
2744 chomp($username = <STDIN>);
2746 $cred->username($username);
2747 $cred->may_save($may_save);
2748 $SVN::_Core::SVN_NO_ERROR;
2751 sub _read_password {
2752 my ($prompt, $realm) = @_;
2753 print STDERR $prompt;
2754 STDERR->flush;
2755 require Term::ReadKey;
2756 Term::ReadKey::ReadMode('noecho');
2757 my $password = '';
2758 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2759 last if $key =~ /[\012\015]/; # \n\r
2760 $password .= $key;
2762 Term::ReadKey::ReadMode('restore');
2763 print STDERR "\n";
2764 STDERR->flush;
2765 $password;
2768 package SVN::Git::Fetcher;
2769 use vars qw/@ISA/;
2770 use strict;
2771 use warnings;
2772 use Carp qw/croak/;
2773 use IO::File qw//;
2775 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2776 sub new {
2777 my ($class, $git_svn) = @_;
2778 my $self = SVN::Delta::Editor->new;
2779 bless $self, $class;
2780 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2781 $self->{empty} = {};
2782 $self->{dir_prop} = {};
2783 $self->{file_prop} = {};
2784 $self->{absent_dir} = {};
2785 $self->{absent_file} = {};
2786 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2787 $self;
2790 sub set_path_strip {
2791 my ($self, $path) = @_;
2792 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2795 sub open_root {
2796 { path => '' };
2799 sub open_directory {
2800 my ($self, $path, $pb, $rev) = @_;
2801 { path => $path };
2804 sub git_path {
2805 my ($self, $path) = @_;
2806 if ($self->{path_strip}) {
2807 $path =~ s!$self->{path_strip}!! or
2808 die "Failed to strip path '$path' ($self->{path_strip})\n";
2810 $path;
2813 sub delete_entry {
2814 my ($self, $path, $rev, $pb) = @_;
2816 my $gpath = $self->git_path($path);
2817 return undef if ($gpath eq '');
2819 # remove entire directories.
2820 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2821 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2822 -r --name-only -z/,
2823 $self->{c}, '--', $gpath);
2824 local $/ = "\0";
2825 while (<$ls>) {
2826 chomp;
2827 $self->{gii}->remove($_);
2828 print "\tD\t$_\n" unless $::_q;
2830 print "\tD\t$gpath/\n" unless $::_q;
2831 command_close_pipe($ls, $ctx);
2832 $self->{empty}->{$path} = 0
2833 } else {
2834 $self->{gii}->remove($gpath);
2835 print "\tD\t$gpath\n" unless $::_q;
2837 undef;
2840 sub open_file {
2841 my ($self, $path, $pb, $rev) = @_;
2842 my $gpath = $self->git_path($path);
2843 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2844 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2845 unless (defined $mode && defined $blob) {
2846 die "$path was not found in commit $self->{c} (r$rev)\n";
2848 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2849 pool => SVN::Pool->new, action => 'M' };
2852 sub add_file {
2853 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2854 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2855 delete $self->{empty}->{$dir};
2856 { path => $path, mode_a => 100644, mode_b => 100644,
2857 pool => SVN::Pool->new, action => 'A' };
2860 sub add_directory {
2861 my ($self, $path, $cp_path, $cp_rev) = @_;
2862 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2863 delete $self->{empty}->{$dir};
2864 $self->{empty}->{$path} = 1;
2865 { path => $path };
2868 sub change_dir_prop {
2869 my ($self, $db, $prop, $value) = @_;
2870 $self->{dir_prop}->{$db->{path}} ||= {};
2871 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2872 undef;
2875 sub absent_directory {
2876 my ($self, $path, $pb) = @_;
2877 $self->{absent_dir}->{$pb->{path}} ||= [];
2878 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2879 undef;
2882 sub absent_file {
2883 my ($self, $path, $pb) = @_;
2884 $self->{absent_file}->{$pb->{path}} ||= [];
2885 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2886 undef;
2889 sub change_file_prop {
2890 my ($self, $fb, $prop, $value) = @_;
2891 if ($prop eq 'svn:executable') {
2892 if ($fb->{mode_b} != 120000) {
2893 $fb->{mode_b} = defined $value ? 100755 : 100644;
2895 } elsif ($prop eq 'svn:special') {
2896 $fb->{mode_b} = defined $value ? 120000 : 100644;
2897 } else {
2898 $self->{file_prop}->{$fb->{path}} ||= {};
2899 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2901 undef;
2904 sub apply_textdelta {
2905 my ($self, $fb, $exp) = @_;
2906 my $fh = IO::File->new_tmpfile;
2907 $fh->autoflush(1);
2908 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2909 # (but $base does not,) so dup() it for reading in close_file
2910 open my $dup, '<&', $fh or croak $!;
2911 my $base = IO::File->new_tmpfile;
2912 $base->autoflush(1);
2913 if ($fb->{blob}) {
2914 defined (my $pid = fork) or croak $!;
2915 if (!$pid) {
2916 open STDOUT, '>&', $base or croak $!;
2917 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2918 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2920 waitpid $pid, 0;
2921 croak $? if $?;
2923 if (defined $exp) {
2924 seek $base, 0, 0 or croak $!;
2925 my $got = Git::SVN::Util::md5sum($base);
2926 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2927 "expected: $exp\n",
2928 " got: $got\n" if ($got ne $exp);
2931 seek $base, 0, 0 or croak $!;
2932 $fb->{fh} = $dup;
2933 $fb->{base} = $base;
2934 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2937 sub close_file {
2938 my ($self, $fb, $exp) = @_;
2939 my $hash;
2940 my $path = $self->git_path($fb->{path});
2941 if (my $fh = $fb->{fh}) {
2942 if (defined $exp) {
2943 seek($fh, 0, 0) or croak $!;
2944 my $got = Git::SVN::Util::md5sum($fh);
2945 if ($got ne $exp) {
2946 die "Checksum mismatch: $path\n",
2947 "expected: $exp\n got: $got\n";
2950 sysseek($fh, 0, 0) or croak $!;
2951 if ($fb->{mode_b} == 120000) {
2952 sysread($fh, my $buf, 5) == 5 or croak $!;
2953 $buf eq 'link ' or die "$path has mode 120000",
2954 "but is not a link\n";
2956 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2957 if (!$pid) {
2958 open STDIN, '<&', $fh or croak $!;
2959 exec qw/git-hash-object -w --stdin/ or croak $!;
2961 chomp($hash = do { local $/; <$out> });
2962 close $out or croak $!;
2963 close $fh or croak $!;
2964 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2965 close $fb->{base} or croak $!;
2966 } else {
2967 $hash = $fb->{blob} or die "no blob information\n";
2969 $fb->{pool}->clear;
2970 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2971 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2972 undef;
2975 sub abort_edit {
2976 my $self = shift;
2977 $self->{nr} = $self->{gii}->{nr};
2978 delete $self->{gii};
2979 $self->SUPER::abort_edit(@_);
2982 sub close_edit {
2983 my $self = shift;
2984 $self->{git_commit_ok} = 1;
2985 $self->{nr} = $self->{gii}->{nr};
2986 delete $self->{gii};
2987 $self->SUPER::close_edit(@_);
2990 package SVN::Git::Editor;
2991 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2992 use strict;
2993 use warnings;
2994 use Carp qw/croak/;
2995 use IO::File;
2997 sub new {
2998 my ($class, $opts) = @_;
2999 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3000 die "$_ required!\n" unless (defined $opts->{$_});
3003 my $pool = SVN::Pool->new;
3004 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3005 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3006 $opts->{r}, $mods);
3008 # $opts->{ra} functions should not be used after this:
3009 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3010 $opts->{editor_cb}, $pool);
3011 my $self = SVN::Delta::Editor->new(@ce, $pool);
3012 bless $self, $class;
3013 foreach (qw/svn_path r tree_a tree_b/) {
3014 $self->{$_} = $opts->{$_};
3016 $self->{url} = $opts->{ra}->{url};
3017 $self->{mods} = $mods;
3018 $self->{types} = $types;
3019 $self->{pool} = $pool;
3020 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3021 $self->{rm} = { };
3022 $self->{path_prefix} = length $self->{svn_path} ?
3023 "$self->{svn_path}/" : '';
3024 return $self;
3027 sub generate_diff {
3028 my ($tree_a, $tree_b) = @_;
3029 my @diff_tree = qw(diff-tree -z -r);
3030 if ($_cp_similarity) {
3031 push @diff_tree, "-C$_cp_similarity";
3032 } else {
3033 push @diff_tree, '-C';
3035 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3036 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3037 push @diff_tree, $tree_a, $tree_b;
3038 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3039 local $/ = "\0";
3040 my $state = 'meta';
3041 my @mods;
3042 while (<$diff_fh>) {
3043 chomp $_; # this gets rid of the trailing "\0"
3044 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3045 $::sha1\s($::sha1)\s
3046 ([MTCRAD])\d*$/xo) {
3047 push @mods, { mode_a => $1, mode_b => $2,
3048 sha1_b => $3, chg => $4 };
3049 if ($4 =~ /^(?:C|R)$/) {
3050 $state = 'file_a';
3051 } else {
3052 $state = 'file_b';
3054 } elsif ($state eq 'file_a') {
3055 my $x = $mods[$#mods] or croak "Empty array\n";
3056 if ($x->{chg} !~ /^(?:C|R)$/) {
3057 croak "Error parsing $_, $x->{chg}\n";
3059 $x->{file_a} = $_;
3060 $state = 'file_b';
3061 } elsif ($state eq 'file_b') {
3062 my $x = $mods[$#mods] or croak "Empty array\n";
3063 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3064 croak "Error parsing $_, $x->{chg}\n";
3066 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3067 croak "Error parsing $_, $x->{chg}\n";
3069 $x->{file_b} = $_;
3070 $state = 'meta';
3071 } else {
3072 croak "Error parsing $_\n";
3075 command_close_pipe($diff_fh, $ctx);
3076 \@mods;
3079 sub check_diff_paths {
3080 my ($ra, $pfx, $rev, $mods) = @_;
3081 my %types;
3082 $pfx .= '/' if length $pfx;
3084 sub type_diff_paths {
3085 my ($ra, $types, $path, $rev) = @_;
3086 my @p = split m#/+#, $path;
3087 my $c = shift @p;
3088 unless (defined $types->{$c}) {
3089 $types->{$c} = $ra->check_path($c, $rev);
3091 while (@p) {
3092 $c .= '/' . shift @p;
3093 next if defined $types->{$c};
3094 $types->{$c} = $ra->check_path($c, $rev);
3098 foreach my $m (@$mods) {
3099 foreach my $f (qw/file_a file_b/) {
3100 next unless defined $m->{$f};
3101 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3102 if (length $pfx.$dir && ! defined $types{$dir}) {
3103 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3107 \%types;
3110 sub split_path {
3111 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3114 sub repo_path {
3115 my ($self, $path) = @_;
3116 $self->{path_prefix}.(defined $path ? $path : '');
3119 sub url_path {
3120 my ($self, $path) = @_;
3121 if ($self->{url} =~ m#^https?://#) {
3122 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3124 $self->{url} . '/' . $self->repo_path($path);
3127 sub rmdirs {
3128 my ($self) = @_;
3129 my $rm = $self->{rm};
3130 delete $rm->{''}; # we never delete the url we're tracking
3131 return unless %$rm;
3133 foreach (keys %$rm) {
3134 my @d = split m#/#, $_;
3135 my $c = shift @d;
3136 $rm->{$c} = 1;
3137 while (@d) {
3138 $c .= '/' . shift @d;
3139 $rm->{$c} = 1;
3142 delete $rm->{$self->{svn_path}};
3143 delete $rm->{''}; # we never delete the url we're tracking
3144 return unless %$rm;
3146 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3147 $self->{tree_b});
3148 local $/ = "\0";
3149 while (<$fh>) {
3150 chomp;
3151 my @dn = split m#/#, $_;
3152 while (pop @dn) {
3153 delete $rm->{join '/', @dn};
3155 unless (%$rm) {
3156 close $fh;
3157 return;
3160 command_close_pipe($fh, $ctx);
3162 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3163 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3164 $self->close_directory($bat->{$d}, $p);
3165 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3166 print "\tD+\t$d/\n" unless $::_q;
3167 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3168 delete $bat->{$d};
3172 sub open_or_add_dir {
3173 my ($self, $full_path, $baton) = @_;
3174 my $t = $self->{types}->{$full_path};
3175 if (!defined $t) {
3176 die "$full_path not known in r$self->{r} or we have a bug!\n";
3179 no warnings 'once';
3180 # SVN::Node::none and SVN::Node::file are used only once,
3181 # so we're shutting up Perl's warnings about them.
3182 if ($t == $SVN::Node::none) {
3183 return $self->add_directory($full_path, $baton,
3184 undef, -1, $self->{pool});
3185 } elsif ($t == $SVN::Node::dir) {
3186 return $self->open_directory($full_path, $baton,
3187 $self->{r}, $self->{pool});
3188 } # no warnings 'once'
3189 print STDERR "$full_path already exists in repository at ",
3190 "r$self->{r} and it is not a directory (",
3191 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3192 } # no warnings 'once'
3193 exit 1;
3196 sub ensure_path {
3197 my ($self, $path) = @_;
3198 my $bat = $self->{bat};
3199 my $repo_path = $self->repo_path($path);
3200 return $bat->{''} unless (length $repo_path);
3201 my @p = split m#/+#, $repo_path;
3202 my $c = shift @p;
3203 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3204 while (@p) {
3205 my $c0 = $c;
3206 $c .= '/' . shift @p;
3207 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3209 return $bat->{$c};
3212 sub A {
3213 my ($self, $m) = @_;
3214 my ($dir, $file) = split_path($m->{file_b});
3215 my $pbat = $self->ensure_path($dir);
3216 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3217 undef, -1);
3218 print "\tA\t$m->{file_b}\n" unless $::_q;
3219 $self->chg_file($fbat, $m);
3220 $self->close_file($fbat,undef,$self->{pool});
3223 sub C {
3224 my ($self, $m) = @_;
3225 my ($dir, $file) = split_path($m->{file_b});
3226 my $pbat = $self->ensure_path($dir);
3227 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3228 $self->url_path($m->{file_a}), $self->{r});
3229 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3230 $self->chg_file($fbat, $m);
3231 $self->close_file($fbat,undef,$self->{pool});
3234 sub delete_entry {
3235 my ($self, $path, $pbat) = @_;
3236 my $rpath = $self->repo_path($path);
3237 my ($dir, $file) = split_path($rpath);
3238 $self->{rm}->{$dir} = 1;
3239 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3242 sub R {
3243 my ($self, $m) = @_;
3244 my ($dir, $file) = split_path($m->{file_b});
3245 my $pbat = $self->ensure_path($dir);
3246 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3247 $self->url_path($m->{file_a}), $self->{r});
3248 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3249 $self->chg_file($fbat, $m);
3250 $self->close_file($fbat,undef,$self->{pool});
3252 ($dir, $file) = split_path($m->{file_a});
3253 $pbat = $self->ensure_path($dir);
3254 $self->delete_entry($m->{file_a}, $pbat);
3257 sub M {
3258 my ($self, $m) = @_;
3259 my ($dir, $file) = split_path($m->{file_b});
3260 my $pbat = $self->ensure_path($dir);
3261 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3262 $pbat,$self->{r},$self->{pool});
3263 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3264 $self->chg_file($fbat, $m);
3265 $self->close_file($fbat,undef,$self->{pool});
3268 sub T { shift->M(@_) }
3270 sub change_file_prop {
3271 my ($self, $fbat, $pname, $pval) = @_;
3272 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3275 sub chg_file {
3276 my ($self, $fbat, $m) = @_;
3277 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3278 $self->change_file_prop($fbat,'svn:executable','*');
3279 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3280 $self->change_file_prop($fbat,'svn:executable',undef);
3282 my $fh = IO::File->new_tmpfile or croak $!;
3283 if ($m->{mode_b} =~ /^120/) {
3284 print $fh 'link ' or croak $!;
3285 $self->change_file_prop($fbat,'svn:special','*');
3286 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3287 $self->change_file_prop($fbat,'svn:special',undef);
3289 defined(my $pid = fork) or croak $!;
3290 if (!$pid) {
3291 open STDOUT, '>&', $fh or croak $!;
3292 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3294 waitpid $pid, 0;
3295 croak $? if $?;
3296 $fh->flush == 0 or croak $!;
3297 seek $fh, 0, 0 or croak $!;
3299 my $exp = Git::SVN::Util::md5sum($fh);
3300 seek $fh, 0, 0 or croak $!;
3302 my $pool = SVN::Pool->new;
3303 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3304 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3305 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3306 $pool->clear;
3308 close $fh or croak $!;
3311 sub D {
3312 my ($self, $m) = @_;
3313 my ($dir, $file) = split_path($m->{file_b});
3314 my $pbat = $self->ensure_path($dir);
3315 print "\tD\t$m->{file_b}\n" unless $::_q;
3316 $self->delete_entry($m->{file_b}, $pbat);
3319 sub close_edit {
3320 my ($self) = @_;
3321 my ($p,$bat) = ($self->{pool}, $self->{bat});
3322 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3323 next if $_ eq '';
3324 $self->close_directory($bat->{$_}, $p);
3326 $self->close_directory($bat->{''}, $p);
3327 $self->SUPER::close_edit($p);
3328 $p->clear;
3331 sub abort_edit {
3332 my ($self) = @_;
3333 $self->SUPER::abort_edit($self->{pool});
3336 sub DESTROY {
3337 my $self = shift;
3338 $self->SUPER::DESTROY(@_);
3339 $self->{pool}->clear;
3342 # this drives the editor
3343 sub apply_diff {
3344 my ($self) = @_;
3345 my $mods = $self->{mods};
3346 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3347 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3348 my $f = $m->{chg};
3349 if (defined $o{$f}) {
3350 $self->$f($m);
3351 } else {
3352 fatal("Invalid change type: $f");
3355 $self->rmdirs if $_rmdir;
3356 if (@$mods == 0) {
3357 $self->abort_edit;
3358 } else {
3359 $self->close_edit;
3361 return scalar @$mods;
3364 package Git::SVN::Ra;
3365 use vars qw/@ISA $config_dir $_log_window_size/;
3366 use strict;
3367 use warnings;
3368 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3370 BEGIN {
3371 # enforce temporary pool usage for some simple functions
3372 no strict 'refs';
3373 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3374 my $SUPER = "SUPER::$f";
3375 *$f = sub {
3376 my $self = shift;
3377 my $pool = SVN::Pool->new;
3378 my @ret = $self->$SUPER(@_,$pool);
3379 $pool->clear;
3380 wantarray ? @ret : $ret[0];
3385 sub _auth_providers () {
3387 SVN::Client::get_simple_provider(),
3388 SVN::Client::get_ssl_server_trust_file_provider(),
3389 SVN::Client::get_simple_prompt_provider(
3390 \&Git::SVN::Prompt::simple, 2),
3391 SVN::Client::get_ssl_client_cert_file_provider(),
3392 SVN::Client::get_ssl_client_cert_prompt_provider(
3393 \&Git::SVN::Prompt::ssl_client_cert, 2),
3394 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3395 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3396 SVN::Client::get_username_provider(),
3397 SVN::Client::get_ssl_server_trust_prompt_provider(
3398 \&Git::SVN::Prompt::ssl_server_trust),
3399 SVN::Client::get_username_prompt_provider(
3400 \&Git::SVN::Prompt::username, 2)
3404 sub escape_uri_only {
3405 my ($uri) = @_;
3406 my @tmp;
3407 foreach (split m{/}, $uri) {
3408 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3409 push @tmp, $_;
3411 join('/', @tmp);
3414 sub escape_url {
3415 my ($url) = @_;
3416 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3417 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3418 $url = "$scheme://$domain$uri";
3420 $url;
3423 sub new {
3424 my ($class, $url) = @_;
3425 $url =~ s!/+$!!;
3426 return $RA if ($RA && $RA->{url} eq $url);
3428 SVN::_Core::svn_config_ensure($config_dir, undef);
3429 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3430 my $config = SVN::Core::config_get_config($config_dir);
3431 $RA = undef;
3432 my $dont_store_passwords = 1;
3433 my $conf_t = ${$config}{'config'};
3435 no warnings 'once';
3436 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3437 # produces warnings that variables are used only once.
3438 # I had not found the better way to shut them up, so
3439 # the warnings of type 'once' are disabled in this block.
3440 if (SVN::_Core::svn_config_get_bool($conf_t,
3441 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3442 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3443 1) == 0) {
3444 SVN::_Core::svn_auth_set_parameter($baton,
3445 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3446 bless (\$dont_store_passwords, "_p_void"));
3448 if (SVN::_Core::svn_config_get_bool($conf_t,
3449 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3450 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3451 1) == 0) {
3452 $Git::SVN::Prompt::_no_auth_cache = 1;
3454 } # no warnings 'once'
3455 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3456 config => $config,
3457 pool => SVN::Pool->new,
3458 auth_provider_callbacks => $callbacks);
3459 $self->{url} = $url;
3460 $self->{svn_path} = $url;
3461 $self->{repos_root} = $self->get_repos_root;
3462 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3463 $self->{cache} = { check_path => { r => 0, data => {} },
3464 get_dir => { r => 0, data => {} } };
3465 $RA = bless $self, $class;
3468 sub check_path {
3469 my ($self, $path, $r) = @_;
3470 my $cache = $self->{cache}->{check_path};
3471 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3472 return $cache->{data}->{$path};
3474 my $pool = SVN::Pool->new;
3475 my $t = $self->SUPER::check_path($path, $r, $pool);
3476 $pool->clear;
3477 if ($r != $cache->{r}) {
3478 %{$cache->{data}} = ();
3479 $cache->{r} = $r;
3481 $cache->{data}->{$path} = $t;
3484 sub get_dir {
3485 my ($self, $dir, $r) = @_;
3486 my $cache = $self->{cache}->{get_dir};
3487 if ($r == $cache->{r}) {
3488 if (my $x = $cache->{data}->{$dir}) {
3489 return wantarray ? @$x : $x->[0];
3492 my $pool = SVN::Pool->new;
3493 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3494 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3495 $pool->clear;
3496 if ($r != $cache->{r}) {
3497 %{$cache->{data}} = ();
3498 $cache->{r} = $r;
3500 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3501 wantarray ? (\%dirents, $r, $props) : \%dirents;
3504 sub DESTROY {
3505 # do not call the real DESTROY since we store ourselves in $RA
3508 sub get_log {
3509 my ($self, @args) = @_;
3510 my $pool = SVN::Pool->new;
3511 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3512 my $ret = $self->SUPER::get_log(@args, $pool);
3513 $pool->clear;
3514 $ret;
3517 sub trees_match {
3518 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3519 my $ctx = SVN::Client->new(auth => _auth_providers);
3520 my $out = IO::File->new_tmpfile;
3522 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3523 # $ctx->diff(), so we'll create a default one
3524 my $pool = SVN::Pool->new_default_sub;
3526 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3527 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3528 $out->flush;
3529 my $ret = (($out->stat)[7] == 0);
3530 close $out or croak $!;
3532 $ret;
3535 sub get_commit_editor {
3536 my ($self, $log, $cb, $pool) = @_;
3537 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3538 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3541 sub gs_do_update {
3542 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3543 my $new = ($rev_a == $rev_b);
3544 my $path = $gs->{path};
3546 if ($new && -e $gs->{index}) {
3547 unlink $gs->{index} or die
3548 "Couldn't unlink index: $gs->{index}: $!\n";
3550 my $pool = SVN::Pool->new;
3551 $editor->set_path_strip($path);
3552 my (@pc) = split m#/#, $path;
3553 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3554 1, $editor, $pool);
3555 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3557 # Since we can't rely on svn_ra_reparent being available, we'll
3558 # just have to do some magic with set_path to make it so
3559 # we only want a partial path.
3560 my $sp = '';
3561 my $final = join('/', @pc);
3562 while (@pc) {
3563 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3564 $sp .= '/' if length $sp;
3565 $sp .= shift @pc;
3567 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3569 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3571 $reporter->finish_report($pool);
3572 $pool->clear;
3573 $editor->{git_commit_ok};
3576 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3577 # svn_ra_reparent didn't work before 1.4)
3578 sub gs_do_switch {
3579 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3580 my $path = $gs->{path};
3581 my $pool = SVN::Pool->new;
3583 my $full_url = $self->{url};
3584 my $old_url = $full_url;
3585 $full_url .= '/' . escape_uri_only($path) if length $path;
3586 my ($ra, $reparented);
3587 if ($old_url ne $full_url) {
3588 if ($old_url !~ m#^svn(\+ssh)?://#) {
3589 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3590 $pool);
3591 $self->{url} = $full_url;
3592 $reparented = 1;
3593 } else {
3594 $_[0] = undef;
3595 $self = undef;
3596 $RA = undef;
3597 $ra = Git::SVN::Ra->new($full_url);
3598 $ra_invalid = 1;
3601 $ra ||= $self;
3602 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3603 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3604 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3605 $reporter->finish_report($pool);
3607 if ($reparented) {
3608 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3609 $self->{url} = $old_url;
3612 $pool->clear;
3613 $editor->{git_commit_ok};
3616 sub longest_common_path {
3617 my ($gsv, $globs) = @_;
3618 my %common;
3619 my $common_max = scalar @$gsv;
3621 foreach my $gs (@$gsv) {
3622 my @tmp = split m#/#, $gs->{path};
3623 my $p = '';
3624 foreach (@tmp) {
3625 $p .= length($p) ? "/$_" : $_;
3626 $common{$p} ||= 0;
3627 $common{$p}++;
3630 $globs ||= [];
3631 $common_max += scalar @$globs;
3632 foreach my $glob (@$globs) {
3633 my @tmp = split m#/#, $glob->{path}->{left};
3634 my $p = '';
3635 foreach (@tmp) {
3636 $p .= length($p) ? "/$_" : $_;
3637 $common{$p} ||= 0;
3638 $common{$p}++;
3642 my $longest_path = '';
3643 foreach (sort {length $b <=> length $a} keys %common) {
3644 if ($common{$_} == $common_max) {
3645 $longest_path = $_;
3646 last;
3649 $longest_path;
3652 sub gs_fetch_loop_common {
3653 my ($self, $base, $head, $gsv, $globs) = @_;
3654 return if ($base > $head);
3655 my $inc = $_log_window_size;
3656 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3657 my $longest_path = longest_common_path($gsv, $globs);
3658 my $ra_url = $self->{url};
3659 while (1) {
3660 my %revs;
3661 my $err;
3662 my $err_handler = $SVN::Error::handler;
3663 $SVN::Error::handler = sub {
3664 ($err) = @_;
3665 skip_unknown_revs($err);
3667 sub _cb {
3668 my ($paths, $r, $author, $date, $log) = @_;
3669 [ dup_changed_paths($paths),
3670 { author => $author, date => $date, log => $log } ];
3672 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3673 sub { $revs{$_[1]} = _cb(@_) });
3674 if ($err && $max >= $head) {
3675 print STDERR "Path '$longest_path' ",
3676 "was probably deleted:\n",
3677 $err->expanded_message,
3678 "\nWill attempt to follow ",
3679 "revisions r$min .. r$max ",
3680 "committed before the deletion\n";
3681 my $hi = $max;
3682 while (--$hi >= $min) {
3683 my $ok;
3684 $self->get_log([$longest_path], $min, $hi,
3685 0, 1, 1, sub {
3686 $ok ||= $_[1];
3687 $revs{$_[1]} = _cb(@_) });
3688 if ($ok) {
3689 print STDERR "r$min .. r$ok OK\n";
3690 last;
3694 $SVN::Error::handler = $err_handler;
3696 my %exists = map { $_->{path} => $_ } @$gsv;
3697 foreach my $r (sort {$a <=> $b} keys %revs) {
3698 my ($paths, $logged) = @{$revs{$r}};
3700 foreach my $gs ($self->match_globs(\%exists, $paths,
3701 $globs, $r)) {
3702 if ($gs->rev_db_max >= $r) {
3703 next;
3705 next unless $gs->match_paths($paths, $r);
3706 $gs->{logged_rev_props} = $logged;
3707 if (my $last_commit = $gs->last_commit) {
3708 $gs->assert_index_clean($last_commit);
3710 my $log_entry = $gs->do_fetch($paths, $r);
3711 if ($log_entry) {
3712 $gs->do_git_commit($log_entry);
3715 foreach my $g (@$globs) {
3716 my $k = "svn-remote.$g->{remote}." .
3717 "$g->{t}-maxRev";
3718 Git::SVN::tmp_config($k, $r);
3720 if ($ra_invalid) {
3721 $_[0] = undef;
3722 $self = undef;
3723 $RA = undef;
3724 $self = Git::SVN::Ra->new($ra_url);
3725 $ra_invalid = undef;
3728 # pre-fill the .rev_db since it'll eventually get filled in
3729 # with '0' x40 if something new gets committed
3730 foreach my $gs (@$gsv) {
3731 next if defined $gs->rev_db_get($max);
3732 $gs->rev_db_set($max, 0 x40);
3734 foreach my $g (@$globs) {
3735 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3736 Git::SVN::tmp_config($k, $max);
3738 last if $max >= $head;
3739 $min = $max + 1;
3740 $max += $inc;
3741 $max = $head if ($max > $head);
3745 sub match_globs {
3746 my ($self, $exists, $paths, $globs, $r) = @_;
3748 sub get_dir_check {
3749 my ($self, $exists, $g, $r) = @_;
3750 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3751 return unless scalar @x == 3;
3752 my $dirents = $x[0];
3753 foreach my $de (keys %$dirents) {
3754 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3755 my $p = $g->{path}->full_path($de);
3756 next if $exists->{$p};
3757 next if (length $g->{path}->{right} &&
3758 ($self->check_path($p, $r) !=
3759 $SVN::Node::dir));
3760 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3761 $g->{ref}->full_path($de), 1);
3764 foreach my $g (@$globs) {
3765 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3766 if ($path->{action} =~ /^[AR]$/) {
3767 get_dir_check($self, $exists, $g, $r);
3770 foreach (keys %$paths) {
3771 if (/$g->{path}->{left_regex}/ &&
3772 !/$g->{path}->{regex}/) {
3773 next if $paths->{$_}->{action} !~ /^[AR]$/;
3774 get_dir_check($self, $exists, $g, $r);
3776 next unless /$g->{path}->{regex}/;
3777 my $p = $1;
3778 my $pathname = $g->{path}->full_path($p);
3779 next if $exists->{$pathname};
3780 next if ($self->check_path($pathname, $r) !=
3781 $SVN::Node::dir);
3782 $exists->{$pathname} = Git::SVN->init(
3783 $self->{url}, $pathname, undef,
3784 $g->{ref}->full_path($p), 1);
3786 my $c = '';
3787 foreach (split m#/#, $g->{path}->{left}) {
3788 $c .= "/$_";
3789 next unless ($paths->{$c} &&
3790 ($paths->{$c}->{action} =~ /^[AR]$/));
3791 get_dir_check($self, $exists, $g, $r);
3794 values %$exists;
3797 sub minimize_url {
3798 my ($self) = @_;
3799 return $self->{url} if ($self->{url} eq $self->{repos_root});
3800 my $url = $self->{repos_root};
3801 my @components = split(m!/!, $self->{svn_path});
3802 my $c = '';
3803 do {
3804 $url .= "/$c" if length $c;
3805 eval { (ref $self)->new($url)->get_latest_revnum };
3806 } while ($@ && ($c = shift @components));
3807 $url;
3810 sub can_do_switch {
3811 my $self = shift;
3812 unless (defined $can_do_switch) {
3813 my $pool = SVN::Pool->new;
3814 my $rep = eval {
3815 $self->do_switch(1, '', 0, $self->{url},
3816 SVN::Delta::Editor->new, $pool);
3818 if ($@) {
3819 $can_do_switch = 0;
3820 } else {
3821 $rep->abort_report($pool);
3822 $can_do_switch = 1;
3824 $pool->clear;
3826 $can_do_switch;
3829 sub skip_unknown_revs {
3830 my ($err) = @_;
3831 my $errno = $err->apr_err();
3832 # Maybe the branch we're tracking didn't
3833 # exist when the repo started, so it's
3834 # not an error if it doesn't, just continue
3836 # Wonderfully consistent library, eh?
3837 # 160013 - svn:// and file://
3838 # 175002 - http(s)://
3839 # 175007 - http(s):// (this repo required authorization, too...)
3840 # More codes may be discovered later...
3841 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3842 my $err_key = $err->expanded_message;
3843 # revision numbers change every time, filter them out
3844 $err_key =~ s/\d+/\0/g;
3845 $err_key = "$errno\0$err_key";
3846 unless ($ignored_err{$err_key}) {
3847 warn "W: Ignoring error from SVN, path probably ",
3848 "does not exist: ($errno): ",
3849 $err->expanded_message,"\n";
3850 $ignored_err{$err_key} = 1;
3852 return;
3854 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3857 # svn_log_changed_path_t objects passed to get_log are likely to be
3858 # overwritten even if only the refs are copied to an external variable,
3859 # so we should dup the structures in their entirety. Using an externally
3860 # passed pool (instead of our temporary and quickly cleared pool in
3861 # Git::SVN::Ra) does not help matters at all...
3862 sub dup_changed_paths {
3863 my ($paths) = @_;
3864 return undef unless $paths;
3865 my %ret;
3866 foreach my $p (keys %$paths) {
3867 my $i = $paths->{$p};
3868 my %s = map { $_ => $i->$_ }
3869 qw/copyfrom_path copyfrom_rev action/;
3870 $ret{$p} = \%s;
3872 \%ret;
3875 package Git::SVN::Log;
3876 use strict;
3877 use warnings;
3878 use POSIX qw/strftime/;
3879 use constant commit_log_separator => ('-' x 72) . "\n";
3880 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3881 %rusers $show_commit $incremental/;
3882 my $l_fmt;
3884 sub cmt_showable {
3885 my ($c) = @_;
3886 return 1 if defined $c->{r};
3888 # big commit message got truncated by the 16k pretty buffer in rev-list
3889 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3890 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3891 @{$c->{l}} = ();
3892 my @log = command(qw/cat-file commit/, $c->{c});
3894 # shift off the headers
3895 shift @log while ($log[0] ne '');
3896 shift @log;
3898 # TODO: make $c->{l} not have a trailing newline in the future
3899 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3901 (undef, $c->{r}, undef) = ::extract_metadata(
3902 (grep(/^git-svn-id: /, @log))[-1]);
3904 return defined $c->{r};
3907 sub log_use_color {
3908 return 1 if $color;
3909 my ($dc, $dcvar);
3910 $dcvar = 'color.diff';
3911 $dc = `git-config --get $dcvar`;
3912 if ($dc eq '') {
3913 # nothing at all; fallback to "diff.color"
3914 $dcvar = 'diff.color';
3915 $dc = `git-config --get $dcvar`;
3917 chomp($dc);
3918 if ($dc eq 'auto') {
3919 my $pc;
3920 $pc = `git-config --get color.pager`;
3921 if ($pc eq '') {
3922 # does not have it -- fallback to pager.color
3923 $pc = `git-config --bool --get pager.color`;
3925 else {
3926 $pc = `git-config --bool --get color.pager`;
3927 if ($?) {
3928 $pc = 'false';
3931 chomp($pc);
3932 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3933 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3935 return 0;
3937 return 0 if $dc eq 'never';
3938 return 1 if $dc eq 'always';
3939 chomp($dc = `git-config --bool --get $dcvar`);
3940 return ($dc eq 'true');
3943 sub git_svn_log_cmd {
3944 my ($r_min, $r_max, @args) = @_;
3945 my $head = 'HEAD';
3946 my (@files, @log_opts);
3947 foreach my $x (@args) {
3948 if ($x eq '--' || @files) {
3949 push @files, $x;
3950 } else {
3951 if (::verify_ref("$x^0")) {
3952 $head = $x;
3953 } else {
3954 push @log_opts, $x;
3959 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3960 $gs ||= Git::SVN->_new;
3961 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3962 $gs->refname);
3963 push @cmd, '-r' unless $non_recursive;
3964 push @cmd, qw/--raw --name-status/ if $verbose;
3965 push @cmd, '--color' if log_use_color();
3966 push @cmd, @log_opts;
3967 if (defined $r_max && $r_max == $r_min) {
3968 push @cmd, '--max-count=1';
3969 if (my $c = $gs->rev_db_get($r_max)) {
3970 push @cmd, $c;
3972 } elsif (defined $r_max) {
3973 if ($r_max < $r_min) {
3974 ($r_min, $r_max) = ($r_max, $r_min);
3976 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
3977 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
3978 # If there are no commits in the range, both $c_max and $c_min
3979 # will be undefined. If there is at least 1 commit in the
3980 # range, both will be defined.
3981 return () if !defined $c_min || !defined $c_max;
3982 if ($c_min eq $c_max) {
3983 push @cmd, '--max-count=1', $c_min;
3984 } else {
3985 push @cmd, '--boundary', "$c_min..$c_max";
3988 return (@cmd, @files);
3991 # adapted from pager.c
3992 sub config_pager {
3993 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3994 if (!defined $pager) {
3995 $pager = 'less';
3996 } elsif (length $pager == 0 || $pager eq 'cat') {
3997 $pager = undef;
4001 sub run_pager {
4002 return unless -t *STDOUT && defined $pager;
4003 pipe my $rfd, my $wfd or return;
4004 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4005 if (!$pid) {
4006 open STDOUT, '>&', $wfd or
4007 ::fatal "Can't redirect to stdout: $!";
4008 return;
4010 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4011 $ENV{LESS} ||= 'FRSX';
4012 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4015 sub format_svn_date {
4016 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4019 sub parse_git_date {
4020 my ($t, $tz) = @_;
4021 # Date::Parse isn't in the standard Perl distro :(
4022 if ($tz =~ s/^\+//) {
4023 $t += tz_to_s_offset($tz);
4024 } elsif ($tz =~ s/^\-//) {
4025 $t -= tz_to_s_offset($tz);
4027 return $t;
4030 sub set_local_timezone {
4031 if (defined $TZ) {
4032 $ENV{TZ} = $TZ;
4033 } else {
4034 delete $ENV{TZ};
4038 sub tz_to_s_offset {
4039 my ($tz) = @_;
4040 $tz =~ s/(\d\d)$//;
4041 return ($1 * 60) + ($tz * 3600);
4044 sub get_author_info {
4045 my ($dest, $author, $t, $tz) = @_;
4046 $author =~ s/(?:^\s*|\s*$)//g;
4047 $dest->{a_raw} = $author;
4048 my $au;
4049 if ($::_authors) {
4050 $au = $rusers{$author} || undef;
4052 if (!$au) {
4053 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4055 $dest->{t} = $t;
4056 $dest->{tz} = $tz;
4057 $dest->{a} = $au;
4058 $dest->{t_utc} = parse_git_date($t, $tz);
4061 sub process_commit {
4062 my ($c, $r_min, $r_max, $defer) = @_;
4063 if (defined $r_min && defined $r_max) {
4064 if ($r_min == $c->{r} && $r_min == $r_max) {
4065 show_commit($c);
4066 return 0;
4068 return 1 if $r_min == $r_max;
4069 if ($r_min < $r_max) {
4070 # we need to reverse the print order
4071 return 0 if (defined $limit && --$limit < 0);
4072 push @$defer, $c;
4073 return 1;
4075 if ($r_min != $r_max) {
4076 return 1 if ($r_min < $c->{r});
4077 return 1 if ($r_max > $c->{r});
4080 return 0 if (defined $limit && --$limit < 0);
4081 show_commit($c);
4082 return 1;
4085 sub show_commit {
4086 my $c = shift;
4087 if ($oneline) {
4088 my $x = "\n";
4089 if (my $l = $c->{l}) {
4090 while ($l->[0] =~ /^\s*$/) { shift @$l }
4091 $x = $l->[0];
4093 $l_fmt ||= 'A' . length($c->{r});
4094 print 'r',pack($l_fmt, $c->{r}),' | ';
4095 print "$c->{c} | " if $show_commit;
4096 print $x;
4097 } else {
4098 show_commit_normal($c);
4102 sub show_commit_changed_paths {
4103 my ($c) = @_;
4104 return unless $c->{changed};
4105 print "Changed paths:\n", @{$c->{changed}};
4108 sub show_commit_normal {
4109 my ($c) = @_;
4110 print commit_log_separator, "r$c->{r} | ";
4111 print "$c->{c} | " if $show_commit;
4112 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4113 my $nr_line = 0;
4115 if (my $l = $c->{l}) {
4116 while ($l->[$#$l] eq "\n" && $#$l > 0
4117 && $l->[($#$l - 1)] eq "\n") {
4118 pop @$l;
4120 $nr_line = scalar @$l;
4121 if (!$nr_line) {
4122 print "1 line\n\n\n";
4123 } else {
4124 if ($nr_line == 1) {
4125 $nr_line = '1 line';
4126 } else {
4127 $nr_line .= ' lines';
4129 print $nr_line, "\n";
4130 show_commit_changed_paths($c);
4131 print "\n";
4132 print $_ foreach @$l;
4134 } else {
4135 print "1 line\n";
4136 show_commit_changed_paths($c);
4137 print "\n";
4140 foreach my $x (qw/raw stat diff/) {
4141 if ($c->{$x}) {
4142 print "\n";
4143 print $_ foreach @{$c->{$x}}
4148 sub cmd_show_log {
4149 my (@args) = @_;
4150 my ($r_min, $r_max);
4151 my $r_last = -1; # prevent dupes
4152 set_local_timezone();
4153 if (defined $::_revision) {
4154 if ($::_revision =~ /^(\d+):(\d+)$/) {
4155 ($r_min, $r_max) = ($1, $2);
4156 } elsif ($::_revision =~ /^\d+$/) {
4157 $r_min = $r_max = $::_revision;
4158 } else {
4159 ::fatal "-r$::_revision is not supported, use ",
4160 "standard 'git log' arguments instead";
4164 config_pager();
4165 @args = git_svn_log_cmd($r_min, $r_max, @args);
4166 if (!@args) {
4167 print commit_log_separator unless $incremental || $oneline;
4168 return;
4170 my $log = command_output_pipe(@args);
4171 run_pager();
4172 my (@k, $c, $d, $stat);
4173 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4174 while (<$log>) {
4175 if (/^${esc_color}commit -?($::sha1_short)/o) {
4176 my $cmt = $1;
4177 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4178 $r_last = $c->{r};
4179 process_commit($c, $r_min, $r_max, \@k) or
4180 goto out;
4182 $d = undef;
4183 $c = { c => $cmt };
4184 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4185 get_author_info($c, $1, $2, $3);
4186 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4187 # ignore
4188 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4189 push @{$c->{raw}}, $_;
4190 } elsif (/^${esc_color}[ACRMDT]\t/) {
4191 # we could add $SVN->{svn_path} here, but that requires
4192 # remote access at the moment (repo_path_split)...
4193 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4194 push @{$c->{changed}}, $_;
4195 } elsif (/^${esc_color}diff /o) {
4196 $d = 1;
4197 push @{$c->{diff}}, $_;
4198 } elsif ($d) {
4199 push @{$c->{diff}}, $_;
4200 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4201 $esc_color*[\+\-]*$esc_color$/x) {
4202 $stat = 1;
4203 push @{$c->{stat}}, $_;
4204 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4205 push @{$c->{stat}}, $_;
4206 $stat = undef;
4207 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4208 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4209 } elsif (s/^${esc_color} //o) {
4210 push @{$c->{l}}, $_;
4213 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4214 $r_last = $c->{r};
4215 process_commit($c, $r_min, $r_max, \@k);
4217 if (@k) {
4218 ($r_min, $r_max) = ($r_max, $r_min);
4219 process_commit($_, $r_min, $r_max) foreach reverse @k;
4221 out:
4222 close $log;
4223 print commit_log_separator unless $incremental || $oneline;
4226 package Git::SVN::Migration;
4227 # these version numbers do NOT correspond to actual version numbers
4228 # of git nor git-svn. They are just relative.
4230 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4232 # v1 layout: .git/$id/info/url, refs/remotes/$id
4234 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4236 # v3 layout: .git/svn/$id, refs/remotes/$id
4237 # - info/url may remain for backwards compatibility
4238 # - this is what we migrate up to this layout automatically,
4239 # - this will be used by git svn init on single branches
4240 # v3.1 layout (auto migrated):
4241 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4242 # for backwards compatibility
4244 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4245 # - this is only created for newly multi-init-ed
4246 # repositories. Similar in spirit to the
4247 # --use-separate-remotes option in git-clone (now default)
4248 # - we do not automatically migrate to this (following
4249 # the example set by core git)
4250 use strict;
4251 use warnings;
4252 use Carp qw/croak/;
4253 use File::Path qw/mkpath/;
4254 use File::Basename qw/dirname basename/;
4255 use vars qw/$_minimize/;
4257 sub migrate_from_v0 {
4258 my $git_dir = $ENV{GIT_DIR};
4259 return undef unless -d $git_dir;
4260 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4261 my $migrated = 0;
4262 while (<$fh>) {
4263 chomp;
4264 my ($id, $orig_ref) = ($_, $_);
4265 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4266 next unless -f "$git_dir/$id/info/url";
4267 my $new_ref = "refs/remotes/$id";
4268 if (::verify_ref("$new_ref^0")) {
4269 print STDERR "W: $orig_ref is probably an old ",
4270 "branch used by an ancient version of ",
4271 "git-svn.\n",
4272 "However, $new_ref also exists.\n",
4273 "We will not be able ",
4274 "to use this branch until this ",
4275 "ambiguity is resolved.\n";
4276 next;
4278 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4279 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4280 command_noisy('update-ref', $new_ref, $orig_ref);
4281 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4282 $migrated++;
4284 command_close_pipe($fh, $ctx);
4285 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4286 $migrated;
4289 sub migrate_from_v1 {
4290 my $git_dir = $ENV{GIT_DIR};
4291 my $migrated = 0;
4292 return $migrated unless -d $git_dir;
4293 my $svn_dir = "$git_dir/svn";
4295 # just in case somebody used 'svn' as their $id at some point...
4296 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4298 print STDERR "Migrating from a git-svn v1 layout...\n";
4299 mkpath([$svn_dir]);
4300 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4301 "$svn_dir\n\t(required for this version ",
4302 "($::VERSION) of git-svn) does not. exist\n";
4303 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4304 while (<$fh>) {
4305 my $x = $_;
4306 next unless $x =~ s#^refs/remotes/##;
4307 chomp $x;
4308 next unless -f "$git_dir/$x/info/url";
4309 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4310 next unless $u;
4311 my $dn = dirname("$git_dir/svn/$x");
4312 mkpath([$dn]) unless -d $dn;
4313 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4314 mkpath(["$git_dir/svn/svn"]);
4315 print STDERR " - $git_dir/$x/info => ",
4316 "$git_dir/svn/$x/info\n";
4317 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4318 croak "$!: $x";
4319 # don't worry too much about these, they probably
4320 # don't exist with repos this old (save for index,
4321 # and we can easily regenerate that)
4322 foreach my $f (qw/unhandled.log index .rev_db/) {
4323 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4325 } else {
4326 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4327 rename "$git_dir/$x", "$git_dir/svn/$x" or
4328 croak "$!: $x";
4330 $migrated++;
4332 command_close_pipe($fh, $ctx);
4333 print STDERR "Done migrating from a git-svn v1 layout\n";
4334 $migrated;
4337 sub read_old_urls {
4338 my ($l_map, $pfx, $path) = @_;
4339 my @dir;
4340 foreach (<$path/*>) {
4341 if (-r "$_/info/url") {
4342 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4343 my $ref_id = $pfx . basename $_;
4344 my $url = ::file_to_s("$_/info/url");
4345 $l_map->{$ref_id} = $url;
4346 } elsif (-d $_) {
4347 push @dir, $_;
4350 foreach (@dir) {
4351 my $x = $_;
4352 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4353 read_old_urls($l_map, $x, $_);
4357 sub migrate_from_v2 {
4358 my @cfg = command(qw/config -l/);
4359 return if grep /^svn-remote\..+\.url=/, @cfg;
4360 my %l_map;
4361 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4362 my $migrated = 0;
4364 foreach my $ref_id (sort keys %l_map) {
4365 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4366 if ($@) {
4367 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4369 $migrated++;
4371 $migrated;
4374 sub minimize_connections {
4375 my $r = Git::SVN::read_all_remotes();
4376 my $new_urls = {};
4377 my $root_repos = {};
4378 foreach my $repo_id (keys %$r) {
4379 my $url = $r->{$repo_id}->{url} or next;
4380 my $fetch = $r->{$repo_id}->{fetch} or next;
4381 my $ra = Git::SVN::Ra->new($url);
4383 # skip existing cases where we already connect to the root
4384 if (($ra->{url} eq $ra->{repos_root}) ||
4385 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4386 $repo_id)) {
4387 $root_repos->{$ra->{url}} = $repo_id;
4388 next;
4391 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4392 my $root_path = $ra->{url};
4393 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4394 foreach my $path (keys %$fetch) {
4395 my $ref_id = $fetch->{$path};
4396 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4398 # make sure we can read when connecting to
4399 # a higher level of a repository
4400 my ($last_rev, undef) = $gs->last_rev_commit;
4401 if (!defined $last_rev) {
4402 $last_rev = eval {
4403 $root_ra->get_latest_revnum;
4405 next if $@;
4407 my $new = $root_path;
4408 $new .= length $path ? "/$path" : '';
4409 eval {
4410 $root_ra->get_log([$new], $last_rev, $last_rev,
4411 0, 0, 1, sub { });
4413 next if $@;
4414 $new_urls->{$ra->{repos_root}}->{$new} =
4415 { ref_id => $ref_id,
4416 old_repo_id => $repo_id,
4417 old_path => $path };
4421 my @emptied;
4422 foreach my $url (keys %$new_urls) {
4423 # see if we can re-use an existing [svn-remote "repo_id"]
4424 # instead of creating a(n ugly) new section:
4425 my $repo_id = $root_repos->{$url} ||
4426 Git::SVN::sanitize_remote_name($url);
4428 my $fetch = $new_urls->{$url};
4429 foreach my $path (keys %$fetch) {
4430 my $x = $fetch->{$path};
4431 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4432 my $pfx = "svn-remote.$x->{old_repo_id}";
4434 my $old_fetch = quotemeta("$x->{old_path}:".
4435 "refs/remotes/$x->{ref_id}");
4436 command_noisy(qw/config --unset/,
4437 "$pfx.fetch", '^'. $old_fetch . '$');
4438 delete $r->{$x->{old_repo_id}}->
4439 {fetch}->{$x->{old_path}};
4440 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4441 command_noisy(qw/config --unset/,
4442 "$pfx.url");
4443 push @emptied, $x->{old_repo_id}
4447 if (@emptied) {
4448 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4449 "$ENV{GIT_DIR}/config";
4450 print STDERR <<EOF;
4451 The following [svn-remote] sections in your config file ($file) are empty
4452 and can be safely removed:
4454 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4458 sub migration_check {
4459 migrate_from_v0();
4460 migrate_from_v1();
4461 migrate_from_v2();
4462 minimize_connections() if $_minimize;
4465 package Git::IndexInfo;
4466 use strict;
4467 use warnings;
4468 use Git qw/command_input_pipe command_close_pipe/;
4470 sub new {
4471 my ($class) = @_;
4472 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4473 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4476 sub remove {
4477 my ($self, $path) = @_;
4478 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4479 return ++$self->{nr};
4481 undef;
4484 sub update {
4485 my ($self, $mode, $hash, $path) = @_;
4486 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4487 return ++$self->{nr};
4489 undef;
4492 sub DESTROY {
4493 my ($self) = @_;
4494 command_close_pipe($self->{gui}, $self->{ctx});
4497 package Git::SVN::GlobSpec;
4498 use strict;
4499 use warnings;
4501 sub new {
4502 my ($class, $glob) = @_;
4503 my $re = $glob;
4504 $re =~ s!/+$!!g; # no need for trailing slashes
4505 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4506 my ($left, $right) = ($1, $2);
4507 if ($nr > 1) {
4508 die "Only one '*' wildcard expansion ",
4509 "is supported (got $nr): '$glob'\n";
4510 } elsif ($nr == 0) {
4511 die "One '*' is needed for glob: '$glob'\n";
4513 $re = quotemeta($left) . $re . quotemeta($right);
4514 if (length $left && !($left =~ s!/+$!!g)) {
4515 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4517 if (length $right && !($right =~ s!^/+!!g)) {
4518 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4520 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4521 bless { left => $left, right => $right, left_regex => $left_re,
4522 regex => qr/$re/, glob => $glob }, $class;
4525 sub full_path {
4526 my ($self, $path) = @_;
4527 return (length $self->{left} ? "$self->{left}/" : '') .
4528 $path . (length $self->{right} ? "/$self->{right}" : '');
4531 __END__
4533 Data structures:
4536 $remotes = { # returned by read_all_remotes()
4537 'svn' => {
4538 # svn-remote.svn.url=https://svn.musicpd.org
4539 url => 'https://svn.musicpd.org',
4540 # svn-remote.svn.fetch=mpd/trunk:trunk
4541 fetch => {
4542 'mpd/trunk' => 'trunk',
4544 # svn-remote.svn.tags=mpd/tags/*:tags/*
4545 tags => {
4546 path => {
4547 left => 'mpd/tags',
4548 right => '',
4549 regex => qr!mpd/tags/([^/]+)$!,
4550 glob => 'tags/*',
4552 ref => {
4553 left => 'tags',
4554 right => '',
4555 regex => qr!tags/([^/]+)$!,
4556 glob => 'tags/*',
4562 $log_entry hashref as returned by libsvn_log_entry()
4564 log => 'whitespace-formatted log entry
4565 ', # trailing newline is preserved
4566 revision => '8', # integer
4567 date => '2004-02-24T17:01:44.108345Z', # commit date
4568 author => 'committer name'
4572 # this is generated by generate_diff();
4573 @mods = array of diff-index line hashes, each element represents one line
4574 of diff-index output
4576 diff-index line ($m hash)
4578 mode_a => first column of diff-index output, no leading ':',
4579 mode_b => second column of diff-index output,
4580 sha1_b => sha1sum of the final blob,
4581 chg => change type [MCRADT],
4582 file_a => original file name of a file (iff chg is 'C' or 'R')
4583 file_b => new/current file name of a file (any chg)
4587 # retval of read_url_paths{,_all}();
4588 $l_map = {
4589 # repository root url
4590 'https://svn.musicpd.org' => {
4591 # repository path # GIT_SVN_ID
4592 'mpd/trunk' => 'trunk',
4593 'mpd/tags/0.11.5' => 'tags/0.11.5',
4597 Notes:
4598 I don't trust the each() function on unless I created %hash myself
4599 because the internal iterator may not have started at base.