git-svn: add git svn propget
[alt-git.git] / git-svn.perl
blobe97eba21fda31a64a3a6a4009a2d875e8cfd7aaf
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 @_; 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)\n";
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 __PACKAGE__) {
53 *{"${package}::$_"} = \&{"Git::$_"};
58 my ($SVN);
60 $sha1 = qr/[a-f\d]{40}/;
61 $sha1_short = qr/[a-f\d]{4,40}/;
62 my ($_stdin, $_help, $_edit,
63 $_message, $_file,
64 $_template, $_shared,
65 $_version, $_fetch_all, $_no_rebase,
66 $_merge, $_strategy, $_dry_run, $_local,
67 $_prefix, $_no_checkout, $_verbose);
68 $Git::SVN::_follow_parent = 1;
69 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
70 'config-dir=s' => \$Git::SVN::Ra::config_dir,
71 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
72 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
73 'authors-file|A=s' => \$_authors,
74 'repack:i' => \$Git::SVN::_repack,
75 'noMetadata' => \$Git::SVN::_no_metadata,
76 'useSvmProps' => \$Git::SVN::_use_svm_props,
77 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
78 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
79 'no-checkout' => \$_no_checkout,
80 'quiet|q' => \$_q,
81 'repack-flags|repack-args|repack-opts=s' =>
82 \$Git::SVN::_repack_flags,
83 %remote_opts );
85 my ($_trunk, $_tags, $_branches, $_stdlayout);
86 my %icv;
87 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
88 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
89 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
90 'stdlayout|s' => \$_stdlayout,
91 'minimize-url|m' => \$Git::SVN::_minimize_url,
92 'no-metadata' => sub { $icv{noMetadata} = 1 },
93 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
94 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
95 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
96 %remote_opts );
97 my %cmt_opts = ( 'edit|e' => \$_edit,
98 'rmdir' => \$SVN::Git::Editor::_rmdir,
99 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
100 'l=i' => \$SVN::Git::Editor::_rename_limit,
101 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
104 my %cmd = (
105 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
106 { 'revision|r=s' => \$_revision,
107 'fetch-all|all' => \$_fetch_all,
108 %fc_opts } ],
109 clone => [ \&cmd_clone, "Initialize and fetch revisions",
110 { 'revision|r=s' => \$_revision,
111 %fc_opts, %init_opts } ],
112 init => [ \&cmd_init, "Initialize a repo for tracking" .
113 " (requires URL argument)",
114 \%init_opts ],
115 'multi-init' => [ \&cmd_multi_init,
116 "Deprecated alias for ".
117 "'$0 init -T<trunk> -b<branches> -t<tags>'",
118 \%init_opts ],
119 dcommit => [ \&cmd_dcommit,
120 'Commit several diffs to merge with upstream',
121 { 'merge|m|M' => \$_merge,
122 'strategy|s=s' => \$_strategy,
123 'verbose|v' => \$_verbose,
124 'dry-run|n' => \$_dry_run,
125 'fetch-all|all' => \$_fetch_all,
126 'no-rebase' => \$_no_rebase,
127 %cmt_opts, %fc_opts } ],
128 'set-tree' => [ \&cmd_set_tree,
129 "Set an SVN repository to a git tree-ish",
130 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
131 'create-ignore' => [ \&cmd_create_ignore,
132 'Create a .gitignore per svn:ignore',
133 { 'revision|r=i' => \$_revision
134 } ],
135 'propget' => [ \&cmd_propget,
136 'Print the value of a property on a file or directory',
137 { 'revision|r=i' => \$_revision } ],
138 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
139 { 'revision|r=i' => \$_revision
140 } ],
141 'multi-fetch' => [ \&cmd_multi_fetch,
142 "Deprecated alias for $0 fetch --all",
143 { 'revision|r=s' => \$_revision, %fc_opts } ],
144 'migrate' => [ sub { },
145 # no-op, we automatically run this anyways,
146 'Migrate configuration/metadata/layout from
147 previous versions of git-svn',
148 { 'minimize' => \$Git::SVN::Migration::_minimize,
149 %remote_opts } ],
150 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
151 { 'limit=i' => \$Git::SVN::Log::limit,
152 'revision|r=s' => \$_revision,
153 'verbose|v' => \$Git::SVN::Log::verbose,
154 'incremental' => \$Git::SVN::Log::incremental,
155 'oneline' => \$Git::SVN::Log::oneline,
156 'show-commit' => \$Git::SVN::Log::show_commit,
157 'non-recursive' => \$Git::SVN::Log::non_recursive,
158 'authors-file|A=s' => \$_authors,
159 'color' => \$Git::SVN::Log::color,
160 'pager=s' => \$Git::SVN::Log::pager
161 } ],
162 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
163 {} ],
164 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
165 { 'merge|m|M' => \$_merge,
166 'verbose|v' => \$_verbose,
167 'strategy|s=s' => \$_strategy,
168 'local|l' => \$_local,
169 'fetch-all|all' => \$_fetch_all,
170 %fc_opts } ],
171 'commit-diff' => [ \&cmd_commit_diff,
172 'Commit a diff between two trees',
173 { 'message|m=s' => \$_message,
174 'file|F=s' => \$_file,
175 'revision|r=s' => \$_revision,
176 %cmt_opts } ],
179 my $cmd;
180 for (my $i = 0; $i < @ARGV; $i++) {
181 if (defined $cmd{$ARGV[$i]}) {
182 $cmd = $ARGV[$i];
183 splice @ARGV, $i, 1;
184 last;
188 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
190 read_repo_config(\%opts);
191 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
192 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
193 'minimize-connections' => \$Git::SVN::Migration::_minimize,
194 'id|i=s' => \$Git::SVN::default_ref_id,
195 'svn-remote|remote|R=s' => sub {
196 $Git::SVN::no_reuse_existing = 1;
197 $Git::SVN::default_repo_id = $_[1] });
198 exit 1 if (!$rv && $cmd && $cmd ne 'log');
200 usage(0) if $_help;
201 version() if $_version;
202 usage(1) unless defined $cmd;
203 load_authors() if $_authors;
205 # make sure we're always running
206 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
207 unless (-d $ENV{GIT_DIR}) {
208 if ($git_dir_user_set) {
209 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
210 "but it is not a directory\n";
212 my $git_dir = delete $ENV{GIT_DIR};
213 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
214 unless (length $cdup) {
215 die "Already at toplevel, but $git_dir ",
216 "not found '$cdup'\n";
218 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
219 unless (-d $git_dir) {
220 die "$git_dir still not found after going to ",
221 "'$cdup'\n";
223 $ENV{GIT_DIR} = $git_dir;
226 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
227 Git::SVN::Migration::migration_check();
229 Git::SVN::init_vars();
230 eval {
231 Git::SVN::verify_remotes_sanity();
232 $cmd{$cmd}->[0]->(@ARGV);
234 fatal $@ if $@;
235 post_fetch_checkout();
236 exit 0;
238 ####################### primary functions ######################
239 sub usage {
240 my $exit = shift || 0;
241 my $fd = $exit ? \*STDERR : \*STDOUT;
242 print $fd <<"";
243 git-svn - bidirectional operations between a single Subversion tree and git
244 Usage: $0 <command> [options] [arguments]\n
246 print $fd "Available commands:\n" unless $cmd;
248 foreach (sort keys %cmd) {
249 next if $cmd && $cmd ne $_;
250 next if /^multi-/; # don't show deprecated commands
251 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
252 foreach (keys %{$cmd{$_}->[2]}) {
253 # mixed-case options are for .git/config only
254 next if /[A-Z]/ && /^[a-z]+$/i;
255 # prints out arguments as they should be passed:
256 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
257 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
258 "--$_" : "-$_" }
259 split /\|/,$_)," $x\n";
262 print $fd <<"";
263 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
264 arbitrary identifier if you're tracking multiple SVN branches/repositories in
265 one git repository and want to keep them separate. See git-svn(1) for more
266 information.
268 exit $exit;
271 sub version {
272 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
273 exit 0;
276 sub do_git_init_db {
277 unless (-d $ENV{GIT_DIR}) {
278 my @init_db = ('init');
279 push @init_db, "--template=$_template" if defined $_template;
280 if (defined $_shared) {
281 if ($_shared =~ /[a-z]/) {
282 push @init_db, "--shared=$_shared";
283 } else {
284 push @init_db, "--shared";
287 command_noisy(@init_db);
289 my $set;
290 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
291 foreach my $i (keys %icv) {
292 die "'$set' and '$i' cannot both be set\n" if $set;
293 next unless defined $icv{$i};
294 command_noisy('config', "$pfx.$i", $icv{$i});
295 $set = $i;
299 sub init_subdir {
300 my $repo_path = shift or return;
301 mkpath([$repo_path]) unless -d $repo_path;
302 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
303 $ENV{GIT_DIR} = '.git';
306 sub cmd_clone {
307 my ($url, $path) = @_;
308 if (!defined $path &&
309 (defined $_trunk || defined $_branches || defined $_tags ||
310 defined $_stdlayout) &&
311 $url !~ m#^[a-z\+]+://#) {
312 $path = $url;
314 $path = basename($url) if !defined $path || !length $path;
315 cmd_init($url, $path);
316 Git::SVN::fetch_all($Git::SVN::default_repo_id);
319 sub cmd_init {
320 if (defined $_stdlayout) {
321 $_trunk = 'trunk' if (!defined $_trunk);
322 $_tags = 'tags' if (!defined $_tags);
323 $_branches = 'branches' if (!defined $_branches);
325 if (defined $_trunk || defined $_branches || defined $_tags) {
326 return cmd_multi_init(@_);
328 my $url = shift or die "SVN repository location required ",
329 "as a command-line argument\n";
330 init_subdir(@_);
331 do_git_init_db();
333 Git::SVN->init($url);
336 sub cmd_fetch {
337 if (grep /^\d+=./, @_) {
338 die "'<rev>=<commit>' fetch arguments are ",
339 "no longer supported.\n";
341 my ($remote) = @_;
342 if (@_ > 1) {
343 die "Usage: $0 fetch [--all] [svn-remote]\n";
345 $remote ||= $Git::SVN::default_repo_id;
346 if ($_fetch_all) {
347 cmd_multi_fetch();
348 } else {
349 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
353 sub cmd_set_tree {
354 my (@commits) = @_;
355 if ($_stdin || !@commits) {
356 print "Reading from stdin...\n";
357 @commits = ();
358 while (<STDIN>) {
359 if (/\b($sha1_short)\b/o) {
360 unshift @commits, $1;
364 my @revs;
365 foreach my $c (@commits) {
366 my @tmp = command('rev-parse',$c);
367 if (scalar @tmp == 1) {
368 push @revs, $tmp[0];
369 } elsif (scalar @tmp > 1) {
370 push @revs, reverse(command('rev-list',@tmp));
371 } else {
372 fatal "Failed to rev-parse $c\n";
375 my $gs = Git::SVN->new;
376 my ($r_last, $cmt_last) = $gs->last_rev_commit;
377 $gs->fetch;
378 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
379 fatal "There are new revisions that were fetched ",
380 "and need to be merged (or acknowledged) ",
381 "before committing.\nlast rev: $r_last\n",
382 " current: $gs->{last_rev}\n";
384 $gs->set_tree($_) foreach @revs;
385 print "Done committing ",scalar @revs," revisions to SVN\n";
388 sub cmd_dcommit {
389 my $head = shift;
390 $head ||= 'HEAD';
391 my @refs;
392 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
393 print "Committing to $url ...\n";
394 unless ($gs) {
395 die "Unable to determine upstream SVN information from ",
396 "$head history\n";
398 my $last_rev;
399 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
400 if ($_no_rebase && scalar(@$linear_refs) > 1) {
401 warn "Attempting to commit more than one change while ",
402 "--no-rebase is enabled.\n",
403 "If these changes depend on each other, re-running ",
404 "without --no-rebase will be required."
406 foreach my $d (@$linear_refs) {
407 unless (defined $last_rev) {
408 (undef, $last_rev, undef) = cmt_metadata("$d~1");
409 unless (defined $last_rev) {
410 fatal "Unable to extract revision information ",
411 "from commit $d~1\n";
414 if ($_dry_run) {
415 print "diff-tree $d~1 $d\n";
416 } else {
417 my $cmt_rev;
418 my %ed_opts = ( r => $last_rev,
419 log => get_commit_entry($d)->{log},
420 ra => Git::SVN::Ra->new($gs->full_url),
421 tree_a => "$d~1",
422 tree_b => $d,
423 editor_cb => sub {
424 print "Committed r$_[0]\n";
425 $cmt_rev = $_[0];
427 svn_path => '');
428 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
429 print "No changes\n$d~1 == $d\n";
430 } elsif ($parents->{$d} && @{$parents->{$d}}) {
431 $gs->{inject_parents_dcommit}->{$cmt_rev} =
432 $parents->{$d};
434 $_fetch_all ? $gs->fetch_all : $gs->fetch;
435 next if $_no_rebase;
437 # we always want to rebase against the current HEAD,
438 # not any head that was passed to us
439 my @diff = command('diff-tree', 'HEAD',
440 $gs->refname, '--');
441 my @finish;
442 if (@diff) {
443 @finish = rebase_cmd();
444 print STDERR "W: HEAD and ", $gs->refname,
445 " differ, using @finish:\n",
446 "@diff";
447 } else {
448 print "No changes between current HEAD and ",
449 $gs->refname,
450 "\nResetting to the latest ",
451 $gs->refname, "\n";
452 @finish = qw/reset --mixed/;
454 command_noisy(@finish, $gs->refname);
455 $last_rev = $cmt_rev;
460 sub cmd_find_rev {
461 my $revision_or_hash = shift;
462 my $result;
463 if ($revision_or_hash =~ /^r\d+$/) {
464 my $head = shift;
465 $head ||= 'HEAD';
466 my @refs;
467 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
468 unless ($gs) {
469 die "Unable to determine upstream SVN information from ",
470 "$head history\n";
472 my $desired_revision = substr($revision_or_hash, 1);
473 $result = $gs->rev_db_get($desired_revision);
474 } else {
475 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
476 $result = $rev;
478 print "$result\n" if $result;
481 sub cmd_rebase {
482 command_noisy(qw/update-index --refresh/);
483 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
484 unless ($gs) {
485 die "Unable to determine upstream SVN information from ",
486 "working tree history\n";
488 if (command(qw/diff-index HEAD --/)) {
489 print STDERR "Cannot rebase with uncommited changes:\n";
490 command_noisy('status');
491 exit 1;
493 unless ($_local) {
494 $_fetch_all ? $gs->fetch_all : $gs->fetch;
496 command_noisy(rebase_cmd(), $gs->refname);
499 sub cmd_show_ignore {
500 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
501 $gs ||= Git::SVN->new;
502 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
503 $gs->prop_walk($gs->{path}, $r, sub {
504 my ($gs, $path, $props) = @_;
505 print STDOUT "\n# $path\n";
506 my $s = $props->{'svn:ignore'} or return;
507 $s =~ s/[\r\n]+/\n/g;
508 chomp $s;
509 $s =~ s#^#$path#gm;
510 print STDOUT "$s\n";
514 sub cmd_create_ignore {
515 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
516 $gs ||= Git::SVN->new;
517 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
518 $gs->prop_walk($gs->{path}, $r, sub {
519 my ($gs, $path, $props) = @_;
520 # $path is of the form /path/to/dir/
521 my $ignore = '.' . $path . '.gitignore';
522 my $s = $props->{'svn:ignore'} or return;
523 open(GITIGNORE, '>', $ignore)
524 or fatal("Failed to open `$ignore' for writing: $!\n");
525 $s =~ s/[\r\n]+/\n/g;
526 chomp $s;
527 # Prefix all patterns so that the ignore doesn't apply
528 # to sub-directories.
529 $s =~ s#^#/#gm;
530 print GITIGNORE "$s\n";
531 close(GITIGNORE)
532 or fatal("Failed to close `$ignore': $!\n");
533 command_noisy('add', $ignore);
537 # get_svnprops(PATH)
538 # ------------------
539 # Helper for cmd_propget below.
540 sub get_svnprops {
541 my $path = shift;
542 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
543 $gs ||= Git::SVN->new;
545 # prefix THE PATH by the sub-directory from which the user
546 # invoked us.
547 $path = $cmd_dir_prefix . $path;
548 fatal("No such file or directory: $path\n") unless -e $path;
549 my $is_dir = -d $path ? 1 : 0;
550 $path = $gs->{path} . '/' . $path;
552 # canonicalize the path (otherwise libsvn will abort or fail to
553 # find the file)
554 # File::Spec->canonpath doesn't collapse x/../y into y (for a
555 # good reason), so let's do this manually.
556 $path =~ s#/+#/#g;
557 $path =~ s#/\.(?:/|$)#/#g;
558 $path =~ s#/[^/]+/\.\.##g;
559 $path =~ s#/$##g;
561 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
562 my $props;
563 if ($is_dir) {
564 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
566 else {
567 (undef, $props) = $gs->ra->get_file($path, $r, undef);
569 return $props;
572 # cmd_propget (PROP, PATH)
573 # ------------------------
574 # Print the SVN property PROP for PATH.
575 sub cmd_propget {
576 my ($prop, $path) = @_;
577 $path = '.' if not defined $path;
578 usage(1) if not defined $prop;
579 my $props = get_svnprops($path);
580 if (not defined $props->{$prop}) {
581 fatal("`$path' does not have a `$prop' SVN property.\n");
583 print $props->{$prop} . "\n";
586 sub cmd_multi_init {
587 my $url = shift;
588 unless (defined $_trunk || defined $_branches || defined $_tags) {
589 usage(1);
592 # there are currently some bugs that prevent multi-init/multi-fetch
593 # setups from working well without this.
594 $Git::SVN::_minimize_url = 1;
596 $_prefix = '' unless defined $_prefix;
597 if (defined $url) {
598 $url =~ s#/+$##;
599 init_subdir(@_);
601 do_git_init_db();
602 if (defined $_trunk) {
603 my $trunk_ref = $_prefix . 'trunk';
604 # try both old-style and new-style lookups:
605 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
606 unless ($gs_trunk) {
607 my ($trunk_url, $trunk_path) =
608 complete_svn_url($url, $_trunk);
609 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
610 undef, $trunk_ref);
613 return unless defined $_branches || defined $_tags;
614 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
615 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
616 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
619 sub cmd_multi_fetch {
620 my $remotes = Git::SVN::read_all_remotes();
621 foreach my $repo_id (sort keys %$remotes) {
622 if ($remotes->{$repo_id}->{url}) {
623 Git::SVN::fetch_all($repo_id, $remotes);
628 # this command is special because it requires no metadata
629 sub cmd_commit_diff {
630 my ($ta, $tb, $url) = @_;
631 my $usage = "Usage: $0 commit-diff -r<revision> ".
632 "<tree-ish> <tree-ish> [<URL>]\n";
633 fatal($usage) if (!defined $ta || !defined $tb);
634 my $svn_path;
635 if (!defined $url) {
636 my $gs = eval { Git::SVN->new };
637 if (!$gs) {
638 fatal("Needed URL or usable git-svn --id in ",
639 "the command-line\n", $usage);
641 $url = $gs->{url};
642 $svn_path = $gs->{path};
644 unless (defined $_revision) {
645 fatal("-r|--revision is a required argument\n", $usage);
647 if (defined $_message && defined $_file) {
648 fatal("Both --message/-m and --file/-F specified ",
649 "for the commit message.\n",
650 "I have no idea what you mean\n");
652 if (defined $_file) {
653 $_message = file_to_s($_file);
654 } else {
655 $_message ||= get_commit_entry($tb)->{log};
657 my $ra ||= Git::SVN::Ra->new($url);
658 $svn_path ||= $ra->{svn_path};
659 my $r = $_revision;
660 if ($r eq 'HEAD') {
661 $r = $ra->get_latest_revnum;
662 } elsif ($r !~ /^\d+$/) {
663 die "revision argument: $r not understood by git-svn\n";
665 my %ed_opts = ( r => $r,
666 log => $_message,
667 ra => $ra,
668 tree_a => $ta,
669 tree_b => $tb,
670 editor_cb => sub { print "Committed r$_[0]\n" },
671 svn_path => $svn_path );
672 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
673 print "No changes\n$ta == $tb\n";
677 ########################### utility functions #########################
679 sub rebase_cmd {
680 my @cmd = qw/rebase/;
681 push @cmd, '-v' if $_verbose;
682 push @cmd, qw/--merge/ if $_merge;
683 push @cmd, "--strategy=$_strategy" if $_strategy;
684 @cmd;
687 sub post_fetch_checkout {
688 return if $_no_checkout;
689 my $gs = $Git::SVN::_head or return;
690 return if verify_ref('refs/heads/master^0');
692 my $valid_head = verify_ref('HEAD^0');
693 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
694 return if ($valid_head || !verify_ref('HEAD^0'));
696 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
697 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
698 return if -f $index;
700 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
701 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
702 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
703 print STDERR "Checked out HEAD:\n ",
704 $gs->full_url, " r", $gs->last_rev, "\n";
707 sub complete_svn_url {
708 my ($url, $path) = @_;
709 $path =~ s#/+$##;
710 if ($path !~ m#^[a-z\+]+://#) {
711 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
712 fatal("E: '$path' is not a complete URL ",
713 "and a separate URL is not specified\n");
715 return ($url, $path);
717 return ($path, '');
720 sub complete_url_ls_init {
721 my ($ra, $repo_path, $switch, $pfx) = @_;
722 unless ($repo_path) {
723 print STDERR "W: $switch not specified\n";
724 return;
726 $repo_path =~ s#/+$##;
727 if ($repo_path =~ m#^[a-z\+]+://#) {
728 $ra = Git::SVN::Ra->new($repo_path);
729 $repo_path = '';
730 } else {
731 $repo_path =~ s#^/+##;
732 unless ($ra) {
733 fatal("E: '$repo_path' is not a complete URL ",
734 "and a separate URL is not specified\n");
737 my $url = $ra->{url};
738 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
739 my $k = "svn-remote.$gs->{repo_id}.url";
740 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
741 if ($orig_url && ($orig_url ne $gs->{url})) {
742 die "$k already set: $orig_url\n",
743 "wanted to set to: $gs->{url}\n";
745 command_oneline('config', $k, $gs->{url}) unless $orig_url;
746 my $remote_path = "$ra->{svn_path}/$repo_path/*";
747 $remote_path =~ s#/+#/#g;
748 $remote_path =~ s#^/##g;
749 my ($n) = ($switch =~ /^--(\w+)/);
750 if (length $pfx && $pfx !~ m#/$#) {
751 die "--prefix='$pfx' must have a trailing slash '/'\n";
753 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
754 "$remote_path:refs/remotes/$pfx*");
757 sub verify_ref {
758 my ($ref) = @_;
759 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
760 { STDERR => 0 }); };
763 sub get_tree_from_treeish {
764 my ($treeish) = @_;
765 # $treeish can be a symbolic ref, too:
766 my $type = command_oneline(qw/cat-file -t/, $treeish);
767 my $expected;
768 while ($type eq 'tag') {
769 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
771 if ($type eq 'commit') {
772 $expected = (grep /^tree /, command(qw/cat-file commit/,
773 $treeish))[0];
774 ($expected) = ($expected =~ /^tree ($sha1)$/o);
775 die "Unable to get tree from $treeish\n" unless $expected;
776 } elsif ($type eq 'tree') {
777 $expected = $treeish;
778 } else {
779 die "$treeish is a $type, expected tree, tag or commit\n";
781 return $expected;
784 sub get_commit_entry {
785 my ($treeish) = shift;
786 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
787 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
788 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
789 open my $log_fh, '>', $commit_editmsg or croak $!;
791 my $type = command_oneline(qw/cat-file -t/, $treeish);
792 if ($type eq 'commit' || $type eq 'tag') {
793 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
794 $type, $treeish);
795 my $in_msg = 0;
796 while (<$msg_fh>) {
797 if (!$in_msg) {
798 $in_msg = 1 if (/^\s*$/);
799 } elsif (/^git-svn-id: /) {
800 # skip this for now, we regenerate the
801 # correct one on re-fetch anyways
802 # TODO: set *:merge properties or like...
803 } else {
804 print $log_fh $_ or croak $!;
807 command_close_pipe($msg_fh, $ctx);
809 close $log_fh or croak $!;
811 if ($_edit || ($type eq 'tree')) {
812 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
813 # TODO: strip out spaces, comments, like git-commit.sh
814 system($editor, $commit_editmsg);
816 rename $commit_editmsg, $commit_msg or croak $!;
817 open $log_fh, '<', $commit_msg or croak $!;
818 { local $/; chomp($log_entry{log} = <$log_fh>); }
819 close $log_fh or croak $!;
820 unlink $commit_msg;
821 \%log_entry;
824 sub s_to_file {
825 my ($str, $file, $mode) = @_;
826 open my $fd,'>',$file or croak $!;
827 print $fd $str,"\n" or croak $!;
828 close $fd or croak $!;
829 chmod ($mode &~ umask, $file) if (defined $mode);
832 sub file_to_s {
833 my $file = shift;
834 open my $fd,'<',$file or croak "$!: file: $file\n";
835 local $/;
836 my $ret = <$fd>;
837 close $fd or croak $!;
838 $ret =~ s/\s*$//s;
839 return $ret;
842 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
843 sub load_authors {
844 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
845 my $log = $cmd eq 'log';
846 while (<$authors>) {
847 chomp;
848 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
849 my ($user, $name, $email) = ($1, $2, $3);
850 if ($log) {
851 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
852 } else {
853 $users{$user} = [$name, $email];
856 close $authors or croak $!;
859 # convert GetOpt::Long specs for use by git-config
860 sub read_repo_config {
861 return unless -d $ENV{GIT_DIR};
862 my $opts = shift;
863 my @config_only;
864 foreach my $o (keys %$opts) {
865 # if we have mixedCase and a long option-only, then
866 # it's a config-only variable that we don't need for
867 # the command-line.
868 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
869 my $v = $opts->{$o};
870 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
871 $key =~ s/-//g;
872 my $arg = 'git-config';
873 $arg .= ' --int' if ($o =~ /[:=]i$/);
874 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
875 if (ref $v eq 'ARRAY') {
876 chomp(my @tmp = `$arg --get-all svn.$key`);
877 @$v = @tmp if @tmp;
878 } else {
879 chomp(my $tmp = `$arg --get svn.$key`);
880 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
881 $$v = $tmp;
885 delete @$opts{@config_only} if @config_only;
888 sub extract_metadata {
889 my $id = shift or return (undef, undef, undef);
890 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
891 \s([a-f\d\-]+)$/x);
892 if (!defined $rev || !$uuid || !$url) {
893 # some of the original repositories I made had
894 # identifiers like this:
895 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
897 return ($url, $rev, $uuid);
900 sub cmt_metadata {
901 return extract_metadata((grep(/^git-svn-id: /,
902 command(qw/cat-file commit/, shift)))[-1]);
905 sub working_head_info {
906 my ($head, $refs) = @_;
907 my @args = ('log', '--no-color', '--first-parent');
908 my ($fh, $ctx) = command_output_pipe(@args, $head);
909 my $hash;
910 my %max;
911 while (<$fh>) {
912 if ( m{^commit ($::sha1)$} ) {
913 unshift @$refs, $hash if $hash and $refs;
914 $hash = $1;
915 next;
917 next unless s{^\s*(git-svn-id:)}{$1};
918 my ($url, $rev, $uuid) = extract_metadata($_);
919 if (defined $url && defined $rev) {
920 next if $max{$url} and $max{$url} < $rev;
921 if (my $gs = Git::SVN->find_by_url($url)) {
922 my $c = $gs->rev_db_get($rev);
923 if ($c && $c eq $hash) {
924 close $fh; # break the pipe
925 return ($url, $rev, $uuid, $gs);
926 } else {
927 $max{$url} ||= $gs->rev_db_max;
932 command_close_pipe($fh, $ctx);
933 (undef, undef, undef, undef);
936 sub read_commit_parents {
937 my ($parents, $c) = @_;
938 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
939 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
940 @{$parents->{$c}} = split(/ /, $p);
943 sub linearize_history {
944 my ($gs, $refs) = @_;
945 my %parents;
946 foreach my $c (@$refs) {
947 read_commit_parents(\%parents, $c);
950 my @linear_refs;
951 my %skip = ();
952 my $last_svn_commit = $gs->last_commit;
953 foreach my $c (reverse @$refs) {
954 next if $c eq $last_svn_commit;
955 last if $skip{$c};
957 unshift @linear_refs, $c;
958 $skip{$c} = 1;
960 # we only want the first parent to diff against for linear
961 # history, we save the rest to inject when we finalize the
962 # svn commit
963 my $fp_a = verify_ref("$c~1");
964 my $fp_b = shift @{$parents{$c}} if $parents{$c};
965 if (!$fp_a || !$fp_b) {
966 die "Commit $c\n",
967 "has no parent commit, and therefore ",
968 "nothing to diff against.\n",
969 "You should be working from a repository ",
970 "originally created by git-svn\n";
972 if ($fp_a ne $fp_b) {
973 die "$c~1 = $fp_a, however parsing commit $c ",
974 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
977 foreach my $p (@{$parents{$c}}) {
978 $skip{$p} = 1;
981 (\@linear_refs, \%parents);
984 package Git::SVN;
985 use strict;
986 use warnings;
987 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
988 $_repack $_repack_flags $_use_svm_props $_head
989 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
990 use Carp qw/croak/;
991 use File::Path qw/mkpath/;
992 use File::Copy qw/copy/;
993 use IPC::Open3;
995 my $_repack_nr;
996 # properties that we do not log:
997 my %SKIP_PROP;
998 BEGIN {
999 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1000 svn:special svn:executable
1001 svn:entry:committed-rev
1002 svn:entry:last-author
1003 svn:entry:uuid
1004 svn:entry:committed-date/;
1006 # some options are read globally, but can be overridden locally
1007 # per [svn-remote "..."] section. Command-line options will *NOT*
1008 # override options set in an [svn-remote "..."] section
1009 no strict 'refs';
1010 for my $option (qw/follow_parent no_metadata use_svm_props
1011 use_svnsync_props/) {
1012 my $key = $option;
1013 $key =~ tr/_//d;
1014 my $prop = "-$option";
1015 *$option = sub {
1016 my ($self) = @_;
1017 return $self->{$prop} if exists $self->{$prop};
1018 my $k = "svn-remote.$self->{repo_id}.$key";
1019 eval { command_oneline(qw/config --get/, $k) };
1020 if ($@) {
1021 $self->{$prop} = ${"Git::SVN::_$option"};
1022 } else {
1023 my $v = command_oneline(qw/config --bool/,$k);
1024 $self->{$prop} = $v eq 'false' ? 0 : 1;
1026 return $self->{$prop};
1031 my %LOCKFILES;
1032 END { unlink keys %LOCKFILES if %LOCKFILES }
1034 sub resolve_local_globs {
1035 my ($url, $fetch, $glob_spec) = @_;
1036 return unless defined $glob_spec;
1037 my $ref = $glob_spec->{ref};
1038 my $path = $glob_spec->{path};
1039 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1040 next unless m#^refs/remotes/$ref->{regex}$#;
1041 my $p = $1;
1042 my $pathname = desanitize_refname($path->full_path($p));
1043 my $refname = desanitize_refname($ref->full_path($p));
1044 if (my $existing = $fetch->{$pathname}) {
1045 if ($existing ne $refname) {
1046 die "Refspec conflict:\n",
1047 "existing: refs/remotes/$existing\n",
1048 " globbed: refs/remotes/$refname\n";
1050 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1051 $u =~ s!^\Q$url\E(/|$)!! or die
1052 "refs/remotes/$refname: '$url' not found in '$u'\n";
1053 if ($pathname ne $u) {
1054 warn "W: Refspec glob conflict ",
1055 "(ref: refs/remotes/$refname):\n",
1056 "expected path: $pathname\n",
1057 " real path: $u\n",
1058 "Continuing ahead with $u\n";
1059 next;
1061 } else {
1062 $fetch->{$pathname} = $refname;
1067 sub parse_revision_argument {
1068 my ($base, $head) = @_;
1069 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1070 return ($base, $head);
1072 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1073 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1074 return ($head, $head) if ($::_revision eq 'HEAD');
1075 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1076 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1077 die "revision argument: $::_revision not understood by git-svn\n";
1080 sub fetch_all {
1081 my ($repo_id, $remotes) = @_;
1082 if (ref $repo_id) {
1083 my $gs = $repo_id;
1084 $repo_id = undef;
1085 $repo_id = $gs->{repo_id};
1087 $remotes ||= read_all_remotes();
1088 my $remote = $remotes->{$repo_id} or
1089 die "[svn-remote \"$repo_id\"] unknown\n";
1090 my $fetch = $remote->{fetch};
1091 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1092 my (@gs, @globs);
1093 my $ra = Git::SVN::Ra->new($url);
1094 my $uuid = $ra->get_uuid;
1095 my $head = $ra->get_latest_revnum;
1096 my $base = defined $fetch ? $head : 0;
1098 # read the max revs for wildcard expansion (branches/*, tags/*)
1099 foreach my $t (qw/branches tags/) {
1100 defined $remote->{$t} or next;
1101 push @globs, $remote->{$t};
1102 my $max_rev = eval { tmp_config(qw/--int --get/,
1103 "svn-remote.$repo_id.${t}-maxRev") };
1104 if (defined $max_rev && ($max_rev < $base)) {
1105 $base = $max_rev;
1106 } elsif (!defined $max_rev) {
1107 $base = 0;
1111 if ($fetch) {
1112 foreach my $p (sort keys %$fetch) {
1113 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1114 my $lr = $gs->rev_db_max;
1115 if (defined $lr) {
1116 $base = $lr if ($lr < $base);
1118 push @gs, $gs;
1122 ($base, $head) = parse_revision_argument($base, $head);
1123 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1126 sub read_all_remotes {
1127 my $r = {};
1128 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1129 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1130 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1131 $local_ref =~ s{^/}{};
1132 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1133 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1134 $r->{$1}->{url} = $2;
1135 } elsif (m!^(.+)\.(branches|tags)=
1136 (.*):refs/remotes/(.+)\s*$/!x) {
1137 my ($p, $g) = ($3, $4);
1138 my $rs = $r->{$1}->{$2} = {
1139 t => $2,
1140 remote => $1,
1141 path => Git::SVN::GlobSpec->new($p),
1142 ref => Git::SVN::GlobSpec->new($g) };
1143 if (length($rs->{ref}->{right}) != 0) {
1144 die "The '*' glob character must be the last ",
1145 "character of '$g'\n";
1152 sub init_vars {
1153 if (defined $_repack) {
1154 $_repack = 1000 if ($_repack <= 0);
1155 $_repack_nr = $_repack;
1156 $_repack_flags ||= '-d';
1160 sub verify_remotes_sanity {
1161 return unless -d $ENV{GIT_DIR};
1162 my %seen;
1163 foreach (command(qw/config -l/)) {
1164 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1165 if ($seen{$1}) {
1166 die "Remote ref refs/remote/$1 is tracked by",
1167 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1168 "Please resolve this ambiguity in ",
1169 "your git configuration file before ",
1170 "continuing\n";
1172 $seen{$1} = $_;
1177 # we allow more chars than remotes2config.sh...
1178 sub sanitize_remote_name {
1179 my ($name) = @_;
1180 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1181 $name;
1184 sub find_existing_remote {
1185 my ($url, $remotes) = @_;
1186 return undef if $no_reuse_existing;
1187 my $existing;
1188 foreach my $repo_id (keys %$remotes) {
1189 my $u = $remotes->{$repo_id}->{url} or next;
1190 next if $u ne $url;
1191 $existing = $repo_id;
1192 last;
1194 $existing;
1197 sub init_remote_config {
1198 my ($self, $url, $no_write) = @_;
1199 $url =~ s!/+$!!; # strip trailing slash
1200 my $r = read_all_remotes();
1201 my $existing = find_existing_remote($url, $r);
1202 if ($existing) {
1203 unless ($no_write) {
1204 print STDERR "Using existing ",
1205 "[svn-remote \"$existing\"]\n";
1207 $self->{repo_id} = $existing;
1208 } elsif ($_minimize_url) {
1209 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1210 $existing = find_existing_remote($min_url, $r);
1211 if ($existing) {
1212 unless ($no_write) {
1213 print STDERR "Using existing ",
1214 "[svn-remote \"$existing\"]\n";
1216 $self->{repo_id} = $existing;
1218 if ($min_url ne $url) {
1219 unless ($no_write) {
1220 print STDERR "Using higher level of URL: ",
1221 "$url => $min_url\n";
1223 my $old_path = $self->{path};
1224 $self->{path} = $url;
1225 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1226 if (length $old_path) {
1227 $self->{path} .= "/$old_path";
1229 $url = $min_url;
1232 my $orig_url;
1233 if (!$existing) {
1234 # verify that we aren't overwriting anything:
1235 $orig_url = eval {
1236 command_oneline('config', '--get',
1237 "svn-remote.$self->{repo_id}.url")
1239 if ($orig_url && ($orig_url ne $url)) {
1240 die "svn-remote.$self->{repo_id}.url already set: ",
1241 "$orig_url\nwanted to set to: $url\n";
1244 my ($xrepo_id, $xpath) = find_ref($self->refname);
1245 if (defined $xpath) {
1246 die "svn-remote.$xrepo_id.fetch already set to track ",
1247 "$xpath:refs/remotes/", $self->refname, "\n";
1249 unless ($no_write) {
1250 command_noisy('config',
1251 "svn-remote.$self->{repo_id}.url", $url);
1252 $self->{path} =~ s{^/}{};
1253 command_noisy('config', '--add',
1254 "svn-remote.$self->{repo_id}.fetch",
1255 "$self->{path}:".$self->refname);
1257 $self->{url} = $url;
1260 sub find_by_url { # repos_root and, path are optional
1261 my ($class, $full_url, $repos_root, $path) = @_;
1263 return undef unless defined $full_url;
1264 remove_username($full_url);
1265 remove_username($repos_root) if defined $repos_root;
1266 my $remotes = read_all_remotes();
1267 if (defined $full_url && defined $repos_root && !defined $path) {
1268 $path = $full_url;
1269 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1271 foreach my $repo_id (keys %$remotes) {
1272 my $u = $remotes->{$repo_id}->{url} or next;
1273 remove_username($u);
1274 next if defined $repos_root && $repos_root ne $u;
1276 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1277 foreach (qw/branches tags/) {
1278 resolve_local_globs($u, $fetch,
1279 $remotes->{$repo_id}->{$_});
1281 my $p = $path;
1282 unless (defined $p) {
1283 $p = $full_url;
1284 $p =~ s#^\Q$u\E(?:/|$)## or next;
1286 foreach my $f (keys %$fetch) {
1287 next if $f ne $p;
1288 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1291 undef;
1294 sub init {
1295 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1296 my $self = _new($class, $repo_id, $ref_id, $path);
1297 if (defined $url) {
1298 $self->init_remote_config($url, $no_write);
1300 $self;
1303 sub find_ref {
1304 my ($ref_id) = @_;
1305 foreach (command(qw/config -l/)) {
1306 next unless m!^svn-remote\.(.+)\.fetch=
1307 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1308 my ($repo_id, $path, $ref) = ($1, $2, $3);
1309 if ($ref eq $ref_id) {
1310 $path = '' if ($path =~ m#^\./?#);
1311 return ($repo_id, $path);
1314 (undef, undef, undef);
1317 sub new {
1318 my ($class, $ref_id, $repo_id, $path) = @_;
1319 if (defined $ref_id && !defined $repo_id && !defined $path) {
1320 ($repo_id, $path) = find_ref($ref_id);
1321 if (!defined $repo_id) {
1322 die "Could not find a \"svn-remote.*.fetch\" key ",
1323 "in the repository configuration matching: ",
1324 "refs/remotes/$ref_id\n";
1327 my $self = _new($class, $repo_id, $ref_id, $path);
1328 if (!defined $self->{path} || !length $self->{path}) {
1329 my $fetch = command_oneline('config', '--get',
1330 "svn-remote.$repo_id.fetch",
1331 ":refs/remotes/$ref_id\$") or
1332 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1333 "\":refs/remotes/$ref_id\$\" in config\n";
1334 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1336 $self->{url} = command_oneline('config', '--get',
1337 "svn-remote.$repo_id.url") or
1338 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1339 $self->rebuild;
1340 $self;
1343 sub refname {
1344 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1346 # It cannot end with a slash /, we'll throw up on this because
1347 # SVN can't have directories with a slash in their name, either:
1348 if ($refname =~ m{/$}) {
1349 die "ref: '$refname' ends with a trailing slash, this is ",
1350 "not permitted by git nor Subversion\n";
1353 # It cannot have ASCII control character space, tilde ~, caret ^,
1354 # colon :, question-mark ?, asterisk *, space, or open bracket [
1355 # anywhere.
1357 # Additionally, % must be escaped because it is used for escaping
1358 # and we want our escaped refname to be reversible
1359 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1361 # no slash-separated component can begin with a dot .
1362 # /.* becomes /%2E*
1363 $refname =~ s{/\.}{/%2E}g;
1365 # It cannot have two consecutive dots .. anywhere
1366 # .. becomes %2E%2E
1367 $refname =~ s{\.\.}{%2E%2E}g;
1369 return $refname;
1372 sub desanitize_refname {
1373 my ($refname) = @_;
1374 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1375 return $refname;
1378 sub svm_uuid {
1379 my ($self) = @_;
1380 return $self->{svm}->{uuid} if $self->svm;
1381 $self->ra;
1382 unless ($self->{svm}) {
1383 die "SVM UUID not cached, and reading remotely failed\n";
1385 $self->{svm}->{uuid};
1388 sub svm {
1389 my ($self) = @_;
1390 return $self->{svm} if $self->{svm};
1391 my $svm;
1392 # see if we have it in our config, first:
1393 eval {
1394 my $section = "svn-remote.$self->{repo_id}";
1395 $svm = {
1396 source => tmp_config('--get', "$section.svm-source"),
1397 uuid => tmp_config('--get', "$section.svm-uuid"),
1398 replace => tmp_config('--get', "$section.svm-replace"),
1401 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1402 $self->{svm} = $svm;
1404 $self->{svm};
1407 sub _set_svm_vars {
1408 my ($self, $ra) = @_;
1409 return $ra if $self->svm;
1411 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1412 "(svm:source, svm:uuid) ",
1413 "from the following URLs:\n" );
1414 sub read_svm_props {
1415 my ($self, $ra, $path, $r) = @_;
1416 my $props = ($ra->get_dir($path, $r))[2];
1417 my $src = $props->{'svm:source'};
1418 my $uuid = $props->{'svm:uuid'};
1419 return undef if (!$src || !$uuid);
1421 chomp($src, $uuid);
1423 $uuid =~ m{^[0-9a-f\-]{30,}$}
1424 or die "doesn't look right - svm:uuid is '$uuid'\n";
1426 # the '!' is used to mark the repos_root!/relative/path
1427 $src =~ s{/?!/?}{/};
1428 $src =~ s{/+$}{}; # no trailing slashes please
1429 # username is of no interest
1430 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1432 my $replace = $ra->{url};
1433 $replace .= "/$path" if length $path;
1435 my $section = "svn-remote.$self->{repo_id}";
1436 tmp_config("$section.svm-source", $src);
1437 tmp_config("$section.svm-replace", $replace);
1438 tmp_config("$section.svm-uuid", $uuid);
1439 $self->{svm} = {
1440 source => $src,
1441 uuid => $uuid,
1442 replace => $replace
1446 my $r = $ra->get_latest_revnum;
1447 my $path = $self->{path};
1448 my %tried;
1449 while (length $path) {
1450 unless ($tried{"$self->{url}/$path"}) {
1451 return $ra if $self->read_svm_props($ra, $path, $r);
1452 $tried{"$self->{url}/$path"} = 1;
1454 $path =~ s#/?[^/]+$##;
1456 die "Path: '$path' should be ''\n" if $path ne '';
1457 return $ra if $self->read_svm_props($ra, $path, $r);
1458 $tried{"$self->{url}/$path"} = 1;
1460 if ($ra->{repos_root} eq $self->{url}) {
1461 die @err, (map { " $_\n" } keys %tried), "\n";
1464 # nope, make sure we're connected to the repository root:
1465 my $ok;
1466 my @tried_b;
1467 $path = $ra->{svn_path};
1468 $ra = Git::SVN::Ra->new($ra->{repos_root});
1469 while (length $path) {
1470 unless ($tried{"$ra->{url}/$path"}) {
1471 $ok = $self->read_svm_props($ra, $path, $r);
1472 last if $ok;
1473 $tried{"$ra->{url}/$path"} = 1;
1475 $path =~ s#/?[^/]+$##;
1477 die "Path: '$path' should be ''\n" if $path ne '';
1478 $ok ||= $self->read_svm_props($ra, $path, $r);
1479 $tried{"$ra->{url}/$path"} = 1;
1480 if (!$ok) {
1481 die @err, (map { " $_\n" } keys %tried), "\n";
1483 Git::SVN::Ra->new($self->{url});
1486 sub svnsync {
1487 my ($self) = @_;
1488 return $self->{svnsync} if $self->{svnsync};
1490 if ($self->no_metadata) {
1491 die "Can't have both 'noMetadata' and ",
1492 "'useSvnsyncProps' options set!\n";
1494 if ($self->rewrite_root) {
1495 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1496 "options set!\n";
1499 my $svnsync;
1500 # see if we have it in our config, first:
1501 eval {
1502 my $section = "svn-remote.$self->{repo_id}";
1503 $svnsync = {
1504 url => tmp_config('--get', "$section.svnsync-url"),
1505 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1508 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1509 return $self->{svnsync} = $svnsync;
1512 my $err = "useSvnsyncProps set, but failed to read " .
1513 "svnsync property: svn:sync-from-";
1514 my $rp = $self->ra->rev_proplist(0);
1516 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1517 $url =~ m{^[a-z\+]+://} or
1518 die "doesn't look right - svn:sync-from-url is '$url'\n";
1520 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1521 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1522 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1524 my $section = "svn-remote.$self->{repo_id}";
1525 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1526 tmp_config('--add', "$section.svnsync-url", $url);
1527 return $self->{svnsync} = { url => $url, uuid => $uuid };
1530 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1531 # remote lookup (useful for 'git svn log').
1532 sub ra_uuid {
1533 my ($self) = @_;
1534 unless ($self->{ra_uuid}) {
1535 my $key = "svn-remote.$self->{repo_id}.uuid";
1536 my $uuid = eval { tmp_config('--get', $key) };
1537 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1538 $self->{ra_uuid} = $uuid;
1539 } else {
1540 die "ra_uuid called without URL\n" unless $self->{url};
1541 $self->{ra_uuid} = $self->ra->get_uuid;
1542 tmp_config('--add', $key, $self->{ra_uuid});
1545 $self->{ra_uuid};
1548 sub ra {
1549 my ($self) = shift;
1550 my $ra = Git::SVN::Ra->new($self->{url});
1551 if ($self->use_svm_props && !$self->{svm}) {
1552 if ($self->no_metadata) {
1553 die "Can't have both 'noMetadata' and ",
1554 "'useSvmProps' options set!\n";
1555 } elsif ($self->use_svnsync_props) {
1556 die "Can't have both 'useSvnsyncProps' and ",
1557 "'useSvmProps' options set!\n";
1559 $ra = $self->_set_svm_vars($ra);
1560 $self->{-want_revprops} = 1;
1562 $ra;
1565 sub rel_path {
1566 my ($self) = @_;
1567 my $repos_root = $self->ra->{repos_root};
1568 return $self->{path} if ($self->{url} eq $repos_root);
1569 my $url = $self->{url} .
1570 (length $self->{path} ? "/$self->{path}" : $self->{path});
1571 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1572 $url;
1575 # prop_walk(PATH, REV, SUB)
1576 # -------------------------
1577 # Recursively traverse PATH at revision REV and invoke SUB for each
1578 # directory that contains a SVN property. SUB will be invoked as
1579 # follows: &SUB(gs, path, props); where `gs' is this instance of
1580 # Git::SVN, `path' the path to the directory where the properties
1581 # `props' were found. The `path' will be relative to point of checkout,
1582 # that is, if url://repo/trunk is the current Git branch, and that
1583 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1584 # as `path' (note the trailing `/').
1585 sub prop_walk {
1586 my ($self, $path, $rev, $sub) = @_;
1588 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1589 $path =~ s#^/*#/#g;
1590 my $p = $path;
1591 # Strip the irrelevant part of the path.
1592 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1593 # Ensure the path is terminated by a `/'.
1594 $p =~ s#/*$#/#;
1596 # The properties contain all the internal SVN stuff nobody
1597 # (usually) cares about.
1598 my $interesting_props = 0;
1599 foreach (keys %{$props}) {
1600 # If it doesn't start with `svn:', it must be a
1601 # user-defined property.
1602 ++$interesting_props and next if $_ !~ /^svn:/;
1603 # FIXME: Fragile, if SVN adds new public properties,
1604 # this needs to be updated.
1605 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1606 |eol-style|mime-type
1607 |externals|needs-lock)$/x;
1609 &$sub($self, $p, $props) if $interesting_props;
1611 foreach (sort keys %$dirent) {
1612 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1613 $self->prop_walk($path . '/' . $_, $rev, $sub);
1617 sub last_rev { ($_[0]->last_rev_commit)[0] }
1618 sub last_commit { ($_[0]->last_rev_commit)[1] }
1620 # returns the newest SVN revision number and newest commit SHA1
1621 sub last_rev_commit {
1622 my ($self) = @_;
1623 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1624 return ($self->{last_rev}, $self->{last_commit});
1626 my $c = ::verify_ref($self->refname.'^0');
1627 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1628 my $rev = (::cmt_metadata($c))[1];
1629 if (defined $rev) {
1630 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1631 return ($rev, $c);
1634 my $db_path = $self->db_path;
1635 unless (-e $db_path) {
1636 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1637 return (undef, undef);
1639 my $offset = -41; # from tail
1640 my $rl;
1641 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1642 sysseek($fh, $offset, 2); # don't care for errors
1643 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1644 chomp $rl;
1645 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1646 $offset -= 41;
1647 sysseek($fh, $offset, 2); # don't care for errors
1648 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1649 chomp $rl;
1651 if ($c && $c ne $rl) {
1652 die "$db_path and ", $self->refname,
1653 " inconsistent!:\n$c != $rl\n";
1655 my $rev = sysseek($fh, 0, 1) or croak $!;
1656 $rev = ($rev - 41) / 41;
1657 close $fh or croak $!;
1658 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1659 return ($rev, $c);
1662 sub get_fetch_range {
1663 my ($self, $min, $max) = @_;
1664 $max ||= $self->ra->get_latest_revnum;
1665 $min ||= $self->rev_db_max;
1666 (++$min, $max);
1669 sub tmp_config {
1670 my (@args) = @_;
1671 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1672 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1673 if (! -f $config && -f $old_def_config) {
1674 rename $old_def_config, $config or
1675 die "Failed rename $old_def_config => $config: $!\n";
1677 my $old_config = $ENV{GIT_CONFIG};
1678 $ENV{GIT_CONFIG} = $config;
1679 $@ = undef;
1680 my @ret = eval {
1681 unless (-f $config) {
1682 mkfile($config);
1683 open my $fh, '>', $config or
1684 die "Can't open $config: $!\n";
1685 print $fh "; This file is used internally by ",
1686 "git-svn\n" or die
1687 "Couldn't write to $config: $!\n";
1688 print $fh "; You should not have to edit it\n" or
1689 die "Couldn't write to $config: $!\n";
1690 close $fh or die "Couldn't close $config: $!\n";
1692 command('config', @args);
1694 my $err = $@;
1695 if (defined $old_config) {
1696 $ENV{GIT_CONFIG} = $old_config;
1697 } else {
1698 delete $ENV{GIT_CONFIG};
1700 die $err if $err;
1701 wantarray ? @ret : $ret[0];
1704 sub tmp_index_do {
1705 my ($self, $sub) = @_;
1706 my $old_index = $ENV{GIT_INDEX_FILE};
1707 $ENV{GIT_INDEX_FILE} = $self->{index};
1708 $@ = undef;
1709 my @ret = eval {
1710 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1711 mkpath([$dir]) unless -d $dir;
1712 &$sub;
1714 my $err = $@;
1715 if (defined $old_index) {
1716 $ENV{GIT_INDEX_FILE} = $old_index;
1717 } else {
1718 delete $ENV{GIT_INDEX_FILE};
1720 die $err if $err;
1721 wantarray ? @ret : $ret[0];
1724 sub assert_index_clean {
1725 my ($self, $treeish) = @_;
1727 $self->tmp_index_do(sub {
1728 command_noisy('read-tree', $treeish) unless -e $self->{index};
1729 my $x = command_oneline('write-tree');
1730 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1731 /^tree ($::sha1)/mo);
1732 return if $y eq $x;
1734 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1735 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1736 command_noisy('read-tree', $treeish);
1737 $x = command_oneline('write-tree');
1738 if ($y ne $x) {
1739 ::fatal "trees ($treeish) $y != $x\n",
1740 "Something is seriously wrong...\n";
1745 sub get_commit_parents {
1746 my ($self, $log_entry) = @_;
1747 my (%seen, @ret, @tmp);
1748 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1749 if (my $ip = $self->{inject_parents}) {
1750 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1751 push @tmp, $commit;
1754 if (my $cur = ::verify_ref($self->refname.'^0')) {
1755 push @tmp, $cur;
1757 if (my $ipd = $self->{inject_parents_dcommit}) {
1758 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1759 push @tmp, @$commit;
1762 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1763 while (my $p = shift @tmp) {
1764 next if $seen{$p};
1765 $seen{$p} = 1;
1766 push @ret, $p;
1767 # MAXPARENT is defined to 16 in commit-tree.c:
1768 last if @ret >= 16;
1770 if (@tmp) {
1771 die "r$log_entry->{revision}: No room for parents:\n\t",
1772 join("\n\t", @tmp), "\n";
1774 @ret;
1777 sub rewrite_root {
1778 my ($self) = @_;
1779 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1780 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1781 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1782 if ($rwr) {
1783 $rwr =~ s#/+$##;
1784 if ($rwr !~ m#^[a-z\+]+://#) {
1785 die "$rwr is not a valid URL (key: $k)\n";
1788 $self->{-rewrite_root} = $rwr;
1791 sub metadata_url {
1792 my ($self) = @_;
1793 ($self->rewrite_root || $self->{url}) .
1794 (length $self->{path} ? '/' . $self->{path} : '');
1797 sub full_url {
1798 my ($self) = @_;
1799 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1802 sub do_git_commit {
1803 my ($self, $log_entry) = @_;
1804 my $lr = $self->last_rev;
1805 if (defined $lr && $lr >= $log_entry->{revision}) {
1806 die "Last fetched revision of ", $self->refname,
1807 " was r$lr, but we are about to fetch: ",
1808 "r$log_entry->{revision}!\n";
1810 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1811 croak "$log_entry->{revision} = $c already exists! ",
1812 "Why are we refetching it?\n";
1814 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1815 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1816 $log_entry->{email};
1817 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1819 my $tree = $log_entry->{tree};
1820 if (!defined $tree) {
1821 $tree = $self->tmp_index_do(sub {
1822 command_oneline('write-tree') });
1824 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1826 my @exec = ('git-commit-tree', $tree);
1827 foreach ($self->get_commit_parents($log_entry)) {
1828 push @exec, '-p', $_;
1830 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1831 or croak $!;
1832 print $msg_fh $log_entry->{log} or croak $!;
1833 unless ($self->no_metadata) {
1834 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1835 or croak $!;
1837 $msg_fh->flush == 0 or croak $!;
1838 close $msg_fh or croak $!;
1839 chomp(my $commit = do { local $/; <$out_fh> });
1840 close $out_fh or croak $!;
1841 waitpid $pid, 0;
1842 croak $? if $?;
1843 if ($commit !~ /^$::sha1$/o) {
1844 die "Failed to commit, invalid sha1: $commit\n";
1847 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1849 $self->{last_rev} = $log_entry->{revision};
1850 $self->{last_commit} = $commit;
1851 print "r$log_entry->{revision}";
1852 if (defined $log_entry->{svm_revision}) {
1853 print " (\@$log_entry->{svm_revision})";
1854 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1855 0, $self->svm_uuid);
1857 print " = $commit ($self->{ref_id})\n";
1858 if (defined $_repack && (--$_repack_nr == 0)) {
1859 $_repack_nr = $_repack;
1860 # repack doesn't use any arguments with spaces in them, does it?
1861 print "Running git repack $_repack_flags ...\n";
1862 command_noisy('repack', split(/\s+/, $_repack_flags));
1863 print "Done repacking\n";
1865 return $commit;
1868 sub match_paths {
1869 my ($self, $paths, $r) = @_;
1870 return 1 if $self->{path} eq '';
1871 if (my $path = $paths->{"/$self->{path}"}) {
1872 return ($path->{action} eq 'D') ? 0 : 1;
1874 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1875 if (grep /$self->{path_regex}/, keys %$paths) {
1876 return 1;
1878 my $c = '';
1879 foreach (split m#/#, $self->{path}) {
1880 $c .= "/$_";
1881 next unless ($paths->{$c} &&
1882 ($paths->{$c}->{action} =~ /^[AR]$/));
1883 if ($self->ra->check_path($self->{path}, $r) ==
1884 $SVN::Node::dir) {
1885 return 1;
1888 return 0;
1891 sub find_parent_branch {
1892 my ($self, $paths, $rev) = @_;
1893 return undef unless $self->follow_parent;
1894 unless (defined $paths) {
1895 my $err_handler = $SVN::Error::handler;
1896 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1897 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1898 $paths =
1899 Git::SVN::Ra::dup_changed_paths($_[0]) });
1900 $SVN::Error::handler = $err_handler;
1902 return undef unless defined $paths;
1904 # look for a parent from another branch:
1905 my @b_path_components = split m#/#, $self->rel_path;
1906 my @a_path_components;
1907 my $i;
1908 while (@b_path_components) {
1909 $i = $paths->{'/'.join('/', @b_path_components)};
1910 last if $i && defined $i->{copyfrom_path};
1911 unshift(@a_path_components, pop(@b_path_components));
1913 return undef unless defined $i && defined $i->{copyfrom_path};
1914 my $branch_from = $i->{copyfrom_path};
1915 if (@a_path_components) {
1916 print STDERR "branch_from: $branch_from => ";
1917 $branch_from .= '/'.join('/', @a_path_components);
1918 print STDERR $branch_from, "\n";
1920 my $r = $i->{copyfrom_rev};
1921 my $repos_root = $self->ra->{repos_root};
1922 my $url = $self->ra->{url};
1923 my $new_url = $repos_root . $branch_from;
1924 print STDERR "Found possible branch point: ",
1925 "$new_url => ", $self->full_url, ", $r\n";
1926 $branch_from =~ s#^/##;
1927 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1928 unless ($gs) {
1929 my $ref_id = $self->{ref_id};
1930 $ref_id =~ s/\@\d+$//;
1931 $ref_id .= "\@$r";
1932 # just grow a tail if we're not unique enough :x
1933 $ref_id .= '-' while find_ref($ref_id);
1934 print STDERR "Initializing parent: $ref_id\n";
1935 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1937 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1938 if (!defined $r0 || !defined $parent) {
1939 my ($base, $head) = parse_revision_argument(0, $r);
1940 if ($base <= $r) {
1941 $gs->fetch($base, $r);
1943 ($r0, $parent) = $gs->last_rev_commit;
1945 if (defined $r0 && defined $parent) {
1946 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1947 my $ed;
1948 if ($self->ra->can_do_switch) {
1949 $self->assert_index_clean($parent);
1950 print STDERR "Following parent with do_switch\n";
1951 # do_switch works with svn/trunk >= r22312, but that
1952 # is not included with SVN 1.4.3 (the latest version
1953 # at the moment), so we can't rely on it
1954 $self->{last_commit} = $parent;
1955 $ed = SVN::Git::Fetcher->new($self);
1956 $gs->ra->gs_do_switch($r0, $rev, $gs,
1957 $self->full_url, $ed)
1958 or die "SVN connection failed somewhere...\n";
1959 } elsif ($self->ra->trees_match($new_url, $r0,
1960 $self->full_url, $rev)) {
1961 print STDERR "Trees match:\n",
1962 " $new_url\@$r0\n",
1963 " ${\$self->full_url}\@$rev\n",
1964 "Following parent with no changes\n";
1965 $self->tmp_index_do(sub {
1966 command_noisy('read-tree', $parent);
1968 $self->{last_commit} = $parent;
1969 } else {
1970 print STDERR "Following parent with do_update\n";
1971 $ed = SVN::Git::Fetcher->new($self);
1972 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1973 or die "SVN connection failed somewhere...\n";
1975 print STDERR "Successfully followed parent\n";
1976 return $self->make_log_entry($rev, [$parent], $ed);
1978 return undef;
1981 sub do_fetch {
1982 my ($self, $paths, $rev) = @_;
1983 my $ed;
1984 my ($last_rev, @parents);
1985 if (my $lc = $self->last_commit) {
1986 # we can have a branch that was deleted, then re-added
1987 # under the same name but copied from another path, in
1988 # which case we'll have multiple parents (we don't
1989 # want to break the original ref, nor lose copypath info):
1990 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1991 push @{$log_entry->{parents}}, $lc;
1992 return $log_entry;
1994 $ed = SVN::Git::Fetcher->new($self);
1995 $last_rev = $self->{last_rev};
1996 $ed->{c} = $lc;
1997 @parents = ($lc);
1998 } else {
1999 $last_rev = $rev;
2000 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2001 return $log_entry;
2003 $ed = SVN::Git::Fetcher->new($self);
2005 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2006 die "SVN connection failed somewhere...\n";
2008 $self->make_log_entry($rev, \@parents, $ed);
2011 sub get_untracked {
2012 my ($self, $ed) = @_;
2013 my @out;
2014 my $h = $ed->{empty};
2015 foreach (sort keys %$h) {
2016 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2017 push @out, " $act: " . uri_encode($_);
2018 warn "W: $act: $_\n";
2020 foreach my $t (qw/dir_prop file_prop/) {
2021 $h = $ed->{$t} or next;
2022 foreach my $path (sort keys %$h) {
2023 my $ppath = $path eq '' ? '.' : $path;
2024 foreach my $prop (sort keys %{$h->{$path}}) {
2025 next if $SKIP_PROP{$prop};
2026 my $v = $h->{$path}->{$prop};
2027 my $t_ppath_prop = "$t: " .
2028 uri_encode($ppath) . ' ' .
2029 uri_encode($prop);
2030 if (defined $v) {
2031 push @out, " +$t_ppath_prop " .
2032 uri_encode($v);
2033 } else {
2034 push @out, " -$t_ppath_prop";
2039 foreach my $t (qw/absent_file absent_directory/) {
2040 $h = $ed->{$t} or next;
2041 foreach my $parent (sort keys %$h) {
2042 foreach my $path (sort @{$h->{$parent}}) {
2043 push @out, " $t: " .
2044 uri_encode("$parent/$path");
2045 warn "W: $t: $parent/$path ",
2046 "Insufficient permissions?\n";
2050 \@out;
2053 sub parse_svn_date {
2054 my $date = shift || return '+0000 1970-01-01 00:00:00';
2055 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2056 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2057 croak "Unable to parse date: $date\n";
2058 "+0000 $Y-$m-$d $H:$M:$S";
2061 sub check_author {
2062 my ($author) = @_;
2063 if (!defined $author || length $author == 0) {
2064 $author = '(no author)';
2066 if (defined $::_authors && ! defined $::users{$author}) {
2067 die "Author: $author not defined in $::_authors file\n";
2069 $author;
2072 sub make_log_entry {
2073 my ($self, $rev, $parents, $ed) = @_;
2074 my $untracked = $self->get_untracked($ed);
2076 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2077 print $un "r$rev\n" or croak $!;
2078 print $un $_, "\n" foreach @$untracked;
2079 my %log_entry = ( parents => $parents || [], revision => $rev,
2080 log => '');
2082 my $headrev;
2083 my $logged = delete $self->{logged_rev_props};
2084 if (!$logged || $self->{-want_revprops}) {
2085 my $rp = $self->ra->rev_proplist($rev);
2086 foreach (sort keys %$rp) {
2087 my $v = $rp->{$_};
2088 if (/^svn:(author|date|log)$/) {
2089 $log_entry{$1} = $v;
2090 } elsif ($_ eq 'svm:headrev') {
2091 $headrev = $v;
2092 } else {
2093 print $un " rev_prop: ", uri_encode($_), ' ',
2094 uri_encode($v), "\n";
2097 } else {
2098 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2100 close $un or croak $!;
2102 $log_entry{date} = parse_svn_date($log_entry{date});
2103 $log_entry{log} .= "\n";
2104 my $author = $log_entry{author} = check_author($log_entry{author});
2105 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2106 : ($author, undef);
2107 if (defined $headrev && $self->use_svm_props) {
2108 if ($self->rewrite_root) {
2109 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2110 "options set!\n";
2112 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2113 # we don't want "SVM: initializing mirror for junk" ...
2114 return undef if $r == 0;
2115 my $svm = $self->svm;
2116 if ($uuid ne $svm->{uuid}) {
2117 die "UUID mismatch on SVM path:\n",
2118 "expected: $svm->{uuid}\n",
2119 " got: $uuid\n";
2121 my $full_url = $self->full_url;
2122 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2123 die "Failed to replace '$svm->{replace}' with ",
2124 "'$svm->{source}' in $full_url\n";
2125 # throw away username for storing in records
2126 remove_username($full_url);
2127 $log_entry{metadata} = "$full_url\@$r $uuid";
2128 $log_entry{svm_revision} = $r;
2129 $email ||= "$author\@$uuid"
2130 } elsif ($self->use_svnsync_props) {
2131 my $full_url = $self->svnsync->{url};
2132 $full_url .= "/$self->{path}" if length $self->{path};
2133 remove_username($full_url);
2134 my $uuid = $self->svnsync->{uuid};
2135 $log_entry{metadata} = "$full_url\@$rev $uuid";
2136 $email ||= "$author\@$uuid"
2137 } else {
2138 my $url = $self->metadata_url;
2139 remove_username($url);
2140 $log_entry{metadata} = "$url\@$rev " .
2141 $self->ra->get_uuid;
2142 $email ||= "$author\@" . $self->ra->get_uuid;
2144 $log_entry{name} = $name;
2145 $log_entry{email} = $email;
2146 \%log_entry;
2149 sub fetch {
2150 my ($self, $min_rev, $max_rev, @parents) = @_;
2151 my ($last_rev, $last_commit) = $self->last_rev_commit;
2152 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2153 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2156 sub set_tree_cb {
2157 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2158 $self->{inject_parents} = { $rev => $tree };
2159 $self->fetch(undef, undef);
2162 sub set_tree {
2163 my ($self, $tree) = (shift, shift);
2164 my $log_entry = ::get_commit_entry($tree);
2165 unless ($self->{last_rev}) {
2166 fatal("Must have an existing revision to commit\n");
2168 my %ed_opts = ( r => $self->{last_rev},
2169 log => $log_entry->{log},
2170 ra => $self->ra,
2171 tree_a => $self->{last_commit},
2172 tree_b => $tree,
2173 editor_cb => sub {
2174 $self->set_tree_cb($log_entry, $tree, @_) },
2175 svn_path => $self->{path} );
2176 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2177 print "No changes\nr$self->{last_rev} = $tree\n";
2181 sub rebuild {
2182 my ($self) = @_;
2183 my $db_path = $self->db_path;
2184 return if (-e $db_path && ! -z $db_path);
2185 return unless ::verify_ref($self->refname.'^0');
2186 if (-f $self->{db_root}) {
2187 rename $self->{db_root}, $db_path or die
2188 "rename $self->{db_root} => $db_path failed: $!\n";
2189 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2190 symlink $base, $self->{db_root} or die
2191 "symlink $base => $self->{db_root} failed: $!\n";
2192 return;
2194 print "Rebuilding $db_path ...\n";
2195 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2196 my $latest;
2197 my $full_url = $self->full_url;
2198 remove_username($full_url);
2199 my $svn_uuid;
2200 my $c;
2201 while (<$log>) {
2202 if ( m{^commit ($::sha1)$} ) {
2203 $c = $1;
2204 next;
2206 next unless s{^\s*(git-svn-id:)}{$1};
2207 my ($url, $rev, $uuid) = ::extract_metadata($_);
2208 remove_username($url);
2210 # ignore merges (from set-tree)
2211 next if (!defined $rev || !$uuid);
2213 # if we merged or otherwise started elsewhere, this is
2214 # how we break out of it
2215 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2216 ($full_url && $url && ($url ne $full_url))) {
2217 next;
2219 $latest ||= $rev;
2220 $svn_uuid ||= $uuid;
2222 $self->rev_db_set($rev, $c);
2223 print "r$rev = $c\n";
2225 command_close_pipe($log, $ctx);
2226 print "Done rebuilding $db_path\n";
2229 # rev_db:
2230 # Tie::File seems to be prone to offset errors if revisions get sparse,
2231 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2232 # one of my favorite modules is out :< Next up would be one of the DBM
2233 # modules, but I'm not sure which is most portable... So I'll just
2234 # go with something that's plain-text, but still capable of
2235 # being randomly accessed. So here's my ultra-simple fixed-width
2236 # database. All records are 40 characters + "\n", so it's easy to seek
2237 # to a revision: (41 * rev) is the byte offset.
2238 # A record of 40 0s denotes an empty revision.
2239 # And yes, it's still pretty fast (faster than Tie::File).
2240 # These files are disposable unless noMetadata or useSvmProps is set
2242 sub _rev_db_set {
2243 my ($fh, $rev, $commit) = @_;
2244 my $offset = $rev * 41;
2245 # assume that append is the common case:
2246 seek $fh, 0, 2 or croak $!;
2247 my $pos = tell $fh;
2248 if ($pos < $offset) {
2249 for (1 .. (($offset - $pos) / 41)) {
2250 print $fh (('0' x 40),"\n") or croak $!;
2253 seek $fh, $offset, 0 or croak $!;
2254 print $fh $commit,"\n" or croak $!;
2257 sub mkfile {
2258 my ($path) = @_;
2259 unless (-e $path) {
2260 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2261 mkpath([$dir]) unless -d $dir;
2262 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2263 close $fh or die "Couldn't close (create) $path: $!\n";
2267 sub rev_db_set {
2268 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2269 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2270 my $db = $self->db_path($uuid);
2271 my $db_lock = "$db.lock";
2272 my $sig;
2273 if ($update_ref) {
2274 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2275 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2277 mkfile($db);
2279 $LOCKFILES{$db_lock} = 1;
2280 my $sync;
2281 # both of these options make our .rev_db file very, very important
2282 # and we can't afford to lose it because rebuild() won't work
2283 if ($self->use_svm_props || $self->no_metadata) {
2284 $sync = 1;
2285 copy($db, $db_lock) or die "rev_db_set(@_): ",
2286 "Failed to copy: ",
2287 "$db => $db_lock ($!)\n";
2288 } else {
2289 rename $db, $db_lock or die "rev_db_set(@_): ",
2290 "Failed to rename: ",
2291 "$db => $db_lock ($!)\n";
2293 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2294 _rev_db_set($fh, $rev, $commit);
2295 if ($sync) {
2296 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2297 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2299 close $fh or croak $!;
2300 if ($update_ref) {
2301 $_head = $self;
2302 command_noisy('update-ref', '-m', "r$rev",
2303 $self->refname, $commit);
2305 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2306 "$db_lock => $db ($!)\n";
2307 delete $LOCKFILES{$db_lock};
2308 if ($update_ref) {
2309 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2310 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2311 kill $sig, $$ if defined $sig;
2315 sub rev_db_max {
2316 my ($self) = @_;
2317 $self->rebuild;
2318 my $db_path = $self->db_path;
2319 my @stat = stat $db_path or return 0;
2320 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2321 my $max = $stat[7] / 41;
2322 (($max > 0) ? $max - 1 : 0);
2325 sub rev_db_get {
2326 my ($self, $rev, $uuid) = @_;
2327 my $ret;
2328 my $offset = $rev * 41;
2329 my $db_path = $self->db_path($uuid);
2330 return undef unless -e $db_path;
2331 open my $fh, '<', $db_path or croak $!;
2332 if (sysseek($fh, $offset, 0) == $offset) {
2333 my $read = sysread($fh, $ret, 40);
2334 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2336 close $fh or croak $!;
2337 $ret;
2340 sub find_rev_before {
2341 my ($self, $rev, $eq_ok) = @_;
2342 --$rev unless $eq_ok;
2343 while ($rev > 0) {
2344 if (my $c = $self->rev_db_get($rev)) {
2345 return ($rev, $c);
2347 --$rev;
2349 return (undef, undef);
2352 sub _new {
2353 my ($class, $repo_id, $ref_id, $path) = @_;
2354 unless (defined $repo_id && length $repo_id) {
2355 $repo_id = $Git::SVN::default_repo_id;
2357 unless (defined $ref_id && length $ref_id) {
2358 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2360 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2361 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2362 $_[3] = $path = '' unless (defined $path);
2363 mkpath(["$ENV{GIT_DIR}/svn"]);
2364 bless {
2365 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2366 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2367 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2370 sub db_path {
2371 my ($self, $uuid) = @_;
2372 $uuid ||= $self->ra_uuid;
2373 "$self->{db_root}.$uuid";
2376 sub uri_encode {
2377 my ($f) = @_;
2378 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2382 sub remove_username {
2383 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2386 package Git::SVN::Prompt;
2387 use strict;
2388 use warnings;
2389 require SVN::Core;
2390 use vars qw/$_no_auth_cache $_username/;
2392 sub simple {
2393 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2394 $may_save = undef if $_no_auth_cache;
2395 $default_username = $_username if defined $_username;
2396 if (defined $default_username && length $default_username) {
2397 if (defined $realm && length $realm) {
2398 print STDERR "Authentication realm: $realm\n";
2399 STDERR->flush;
2401 $cred->username($default_username);
2402 } else {
2403 username($cred, $realm, $may_save, $pool);
2405 $cred->password(_read_password("Password for '" .
2406 $cred->username . "': ", $realm));
2407 $cred->may_save($may_save);
2408 $SVN::_Core::SVN_NO_ERROR;
2411 sub ssl_server_trust {
2412 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2413 $may_save = undef if $_no_auth_cache;
2414 print STDERR "Error validating server certificate for '$realm':\n";
2416 no warnings 'once';
2417 # All variables SVN::Auth::SSL::* are used only once,
2418 # so we're shutting up Perl warnings about this.
2419 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2420 print STDERR " - The certificate is not issued ",
2421 "by a trusted authority. Use the\n",
2422 " fingerprint to validate ",
2423 "the certificate manually!\n";
2425 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2426 print STDERR " - The certificate hostname ",
2427 "does not match.\n";
2429 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2430 print STDERR " - The certificate is not yet valid.\n";
2432 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2433 print STDERR " - The certificate has expired.\n";
2435 if ($failures & $SVN::Auth::SSL::OTHER) {
2436 print STDERR " - The certificate has ",
2437 "an unknown error.\n";
2439 } # no warnings 'once'
2440 printf STDERR
2441 "Certificate information:\n".
2442 " - Hostname: %s\n".
2443 " - Valid: from %s until %s\n".
2444 " - Issuer: %s\n".
2445 " - Fingerprint: %s\n",
2446 map $cert_info->$_, qw(hostname valid_from valid_until
2447 issuer_dname fingerprint);
2448 my $choice;
2449 prompt:
2450 print STDERR $may_save ?
2451 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2452 "(R)eject or accept (t)emporarily? ";
2453 STDERR->flush;
2454 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2455 if ($choice =~ /^t$/i) {
2456 $cred->may_save(undef);
2457 } elsif ($choice =~ /^r$/i) {
2458 return -1;
2459 } elsif ($may_save && $choice =~ /^p$/i) {
2460 $cred->may_save($may_save);
2461 } else {
2462 goto prompt;
2464 $cred->accepted_failures($failures);
2465 $SVN::_Core::SVN_NO_ERROR;
2468 sub ssl_client_cert {
2469 my ($cred, $realm, $may_save, $pool) = @_;
2470 $may_save = undef if $_no_auth_cache;
2471 print STDERR "Client certificate filename: ";
2472 STDERR->flush;
2473 chomp(my $filename = <STDIN>);
2474 $cred->cert_file($filename);
2475 $cred->may_save($may_save);
2476 $SVN::_Core::SVN_NO_ERROR;
2479 sub ssl_client_cert_pw {
2480 my ($cred, $realm, $may_save, $pool) = @_;
2481 $may_save = undef if $_no_auth_cache;
2482 $cred->password(_read_password("Password: ", $realm));
2483 $cred->may_save($may_save);
2484 $SVN::_Core::SVN_NO_ERROR;
2487 sub username {
2488 my ($cred, $realm, $may_save, $pool) = @_;
2489 $may_save = undef if $_no_auth_cache;
2490 if (defined $realm && length $realm) {
2491 print STDERR "Authentication realm: $realm\n";
2493 my $username;
2494 if (defined $_username) {
2495 $username = $_username;
2496 } else {
2497 print STDERR "Username: ";
2498 STDERR->flush;
2499 chomp($username = <STDIN>);
2501 $cred->username($username);
2502 $cred->may_save($may_save);
2503 $SVN::_Core::SVN_NO_ERROR;
2506 sub _read_password {
2507 my ($prompt, $realm) = @_;
2508 print STDERR $prompt;
2509 STDERR->flush;
2510 require Term::ReadKey;
2511 Term::ReadKey::ReadMode('noecho');
2512 my $password = '';
2513 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2514 last if $key =~ /[\012\015]/; # \n\r
2515 $password .= $key;
2517 Term::ReadKey::ReadMode('restore');
2518 print STDERR "\n";
2519 STDERR->flush;
2520 $password;
2523 package SVN::Git::Fetcher;
2524 use vars qw/@ISA/;
2525 use strict;
2526 use warnings;
2527 use Carp qw/croak/;
2528 use IO::File qw//;
2529 use Digest::MD5;
2531 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2532 sub new {
2533 my ($class, $git_svn) = @_;
2534 my $self = SVN::Delta::Editor->new;
2535 bless $self, $class;
2536 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2537 $self->{empty} = {};
2538 $self->{dir_prop} = {};
2539 $self->{file_prop} = {};
2540 $self->{absent_dir} = {};
2541 $self->{absent_file} = {};
2542 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2543 $self;
2546 sub set_path_strip {
2547 my ($self, $path) = @_;
2548 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2551 sub open_root {
2552 { path => '' };
2555 sub open_directory {
2556 my ($self, $path, $pb, $rev) = @_;
2557 { path => $path };
2560 sub git_path {
2561 my ($self, $path) = @_;
2562 if ($self->{path_strip}) {
2563 $path =~ s!$self->{path_strip}!! or
2564 die "Failed to strip path '$path' ($self->{path_strip})\n";
2566 $path;
2569 sub delete_entry {
2570 my ($self, $path, $rev, $pb) = @_;
2572 my $gpath = $self->git_path($path);
2573 return undef if ($gpath eq '');
2575 # remove entire directories.
2576 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2577 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2578 -r --name-only -z/,
2579 $self->{c}, '--', $gpath);
2580 local $/ = "\0";
2581 while (<$ls>) {
2582 chomp;
2583 $self->{gii}->remove($_);
2584 print "\tD\t$_\n" unless $::_q;
2586 print "\tD\t$gpath/\n" unless $::_q;
2587 command_close_pipe($ls, $ctx);
2588 $self->{empty}->{$path} = 0
2589 } else {
2590 $self->{gii}->remove($gpath);
2591 print "\tD\t$gpath\n" unless $::_q;
2593 undef;
2596 sub open_file {
2597 my ($self, $path, $pb, $rev) = @_;
2598 my $gpath = $self->git_path($path);
2599 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2600 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2601 unless (defined $mode && defined $blob) {
2602 die "$path was not found in commit $self->{c} (r$rev)\n";
2604 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2605 pool => SVN::Pool->new, action => 'M' };
2608 sub add_file {
2609 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2610 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2611 delete $self->{empty}->{$dir};
2612 { path => $path, mode_a => 100644, mode_b => 100644,
2613 pool => SVN::Pool->new, action => 'A' };
2616 sub add_directory {
2617 my ($self, $path, $cp_path, $cp_rev) = @_;
2618 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2619 delete $self->{empty}->{$dir};
2620 $self->{empty}->{$path} = 1;
2621 { path => $path };
2624 sub change_dir_prop {
2625 my ($self, $db, $prop, $value) = @_;
2626 $self->{dir_prop}->{$db->{path}} ||= {};
2627 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2628 undef;
2631 sub absent_directory {
2632 my ($self, $path, $pb) = @_;
2633 $self->{absent_dir}->{$pb->{path}} ||= [];
2634 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2635 undef;
2638 sub absent_file {
2639 my ($self, $path, $pb) = @_;
2640 $self->{absent_file}->{$pb->{path}} ||= [];
2641 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2642 undef;
2645 sub change_file_prop {
2646 my ($self, $fb, $prop, $value) = @_;
2647 if ($prop eq 'svn:executable') {
2648 if ($fb->{mode_b} != 120000) {
2649 $fb->{mode_b} = defined $value ? 100755 : 100644;
2651 } elsif ($prop eq 'svn:special') {
2652 $fb->{mode_b} = defined $value ? 120000 : 100644;
2653 } else {
2654 $self->{file_prop}->{$fb->{path}} ||= {};
2655 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2657 undef;
2660 sub apply_textdelta {
2661 my ($self, $fb, $exp) = @_;
2662 my $fh = IO::File->new_tmpfile;
2663 $fh->autoflush(1);
2664 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2665 # (but $base does not,) so dup() it for reading in close_file
2666 open my $dup, '<&', $fh or croak $!;
2667 my $base = IO::File->new_tmpfile;
2668 $base->autoflush(1);
2669 if ($fb->{blob}) {
2670 defined (my $pid = fork) or croak $!;
2671 if (!$pid) {
2672 open STDOUT, '>&', $base or croak $!;
2673 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2674 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2676 waitpid $pid, 0;
2677 croak $? if $?;
2679 if (defined $exp) {
2680 seek $base, 0, 0 or croak $!;
2681 my $md5 = Digest::MD5->new;
2682 $md5->addfile($base);
2683 my $got = $md5->hexdigest;
2684 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2685 "expected: $exp\n",
2686 " got: $got\n" if ($got ne $exp);
2689 seek $base, 0, 0 or croak $!;
2690 $fb->{fh} = $dup;
2691 $fb->{base} = $base;
2692 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2695 sub close_file {
2696 my ($self, $fb, $exp) = @_;
2697 my $hash;
2698 my $path = $self->git_path($fb->{path});
2699 if (my $fh = $fb->{fh}) {
2700 if (defined $exp) {
2701 seek($fh, 0, 0) or croak $!;
2702 my $md5 = Digest::MD5->new;
2703 $md5->addfile($fh);
2704 my $got = $md5->hexdigest;
2705 if ($got ne $exp) {
2706 die "Checksum mismatch: $path\n",
2707 "expected: $exp\n got: $got\n";
2710 sysseek($fh, 0, 0) or croak $!;
2711 if ($fb->{mode_b} == 120000) {
2712 sysread($fh, my $buf, 5) == 5 or croak $!;
2713 $buf eq 'link ' or die "$path has mode 120000",
2714 "but is not a link\n";
2716 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2717 if (!$pid) {
2718 open STDIN, '<&', $fh or croak $!;
2719 exec qw/git-hash-object -w --stdin/ or croak $!;
2721 chomp($hash = do { local $/; <$out> });
2722 close $out or croak $!;
2723 close $fh or croak $!;
2724 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2725 close $fb->{base} or croak $!;
2726 } else {
2727 $hash = $fb->{blob} or die "no blob information\n";
2729 $fb->{pool}->clear;
2730 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2731 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2732 undef;
2735 sub abort_edit {
2736 my $self = shift;
2737 $self->{nr} = $self->{gii}->{nr};
2738 delete $self->{gii};
2739 $self->SUPER::abort_edit(@_);
2742 sub close_edit {
2743 my $self = shift;
2744 $self->{git_commit_ok} = 1;
2745 $self->{nr} = $self->{gii}->{nr};
2746 delete $self->{gii};
2747 $self->SUPER::close_edit(@_);
2750 package SVN::Git::Editor;
2751 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2752 use strict;
2753 use warnings;
2754 use Carp qw/croak/;
2755 use IO::File;
2756 use Digest::MD5;
2758 sub new {
2759 my ($class, $opts) = @_;
2760 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2761 die "$_ required!\n" unless (defined $opts->{$_});
2764 my $pool = SVN::Pool->new;
2765 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2766 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2767 $opts->{r}, $mods);
2769 # $opts->{ra} functions should not be used after this:
2770 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2771 $opts->{editor_cb}, $pool);
2772 my $self = SVN::Delta::Editor->new(@ce, $pool);
2773 bless $self, $class;
2774 foreach (qw/svn_path r tree_a tree_b/) {
2775 $self->{$_} = $opts->{$_};
2777 $self->{url} = $opts->{ra}->{url};
2778 $self->{mods} = $mods;
2779 $self->{types} = $types;
2780 $self->{pool} = $pool;
2781 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2782 $self->{rm} = { };
2783 $self->{path_prefix} = length $self->{svn_path} ?
2784 "$self->{svn_path}/" : '';
2785 return $self;
2788 sub generate_diff {
2789 my ($tree_a, $tree_b) = @_;
2790 my @diff_tree = qw(diff-tree -z -r);
2791 if ($_cp_similarity) {
2792 push @diff_tree, "-C$_cp_similarity";
2793 } else {
2794 push @diff_tree, '-C';
2796 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2797 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2798 push @diff_tree, $tree_a, $tree_b;
2799 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2800 local $/ = "\0";
2801 my $state = 'meta';
2802 my @mods;
2803 while (<$diff_fh>) {
2804 chomp $_; # this gets rid of the trailing "\0"
2805 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2806 $::sha1\s($::sha1)\s
2807 ([MTCRAD])\d*$/xo) {
2808 push @mods, { mode_a => $1, mode_b => $2,
2809 sha1_b => $3, chg => $4 };
2810 if ($4 =~ /^(?:C|R)$/) {
2811 $state = 'file_a';
2812 } else {
2813 $state = 'file_b';
2815 } elsif ($state eq 'file_a') {
2816 my $x = $mods[$#mods] or croak "Empty array\n";
2817 if ($x->{chg} !~ /^(?:C|R)$/) {
2818 croak "Error parsing $_, $x->{chg}\n";
2820 $x->{file_a} = $_;
2821 $state = 'file_b';
2822 } elsif ($state eq 'file_b') {
2823 my $x = $mods[$#mods] or croak "Empty array\n";
2824 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2825 croak "Error parsing $_, $x->{chg}\n";
2827 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2828 croak "Error parsing $_, $x->{chg}\n";
2830 $x->{file_b} = $_;
2831 $state = 'meta';
2832 } else {
2833 croak "Error parsing $_\n";
2836 command_close_pipe($diff_fh, $ctx);
2837 \@mods;
2840 sub check_diff_paths {
2841 my ($ra, $pfx, $rev, $mods) = @_;
2842 my %types;
2843 $pfx .= '/' if length $pfx;
2845 sub type_diff_paths {
2846 my ($ra, $types, $path, $rev) = @_;
2847 my @p = split m#/+#, $path;
2848 my $c = shift @p;
2849 unless (defined $types->{$c}) {
2850 $types->{$c} = $ra->check_path($c, $rev);
2852 while (@p) {
2853 $c .= '/' . shift @p;
2854 next if defined $types->{$c};
2855 $types->{$c} = $ra->check_path($c, $rev);
2859 foreach my $m (@$mods) {
2860 foreach my $f (qw/file_a file_b/) {
2861 next unless defined $m->{$f};
2862 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2863 if (length $pfx.$dir && ! defined $types{$dir}) {
2864 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2868 \%types;
2871 sub split_path {
2872 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2875 sub repo_path {
2876 my ($self, $path) = @_;
2877 $self->{path_prefix}.(defined $path ? $path : '');
2880 sub url_path {
2881 my ($self, $path) = @_;
2882 if ($self->{url} =~ m#^https?://#) {
2883 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2885 $self->{url} . '/' . $self->repo_path($path);
2888 sub rmdirs {
2889 my ($self) = @_;
2890 my $rm = $self->{rm};
2891 delete $rm->{''}; # we never delete the url we're tracking
2892 return unless %$rm;
2894 foreach (keys %$rm) {
2895 my @d = split m#/#, $_;
2896 my $c = shift @d;
2897 $rm->{$c} = 1;
2898 while (@d) {
2899 $c .= '/' . shift @d;
2900 $rm->{$c} = 1;
2903 delete $rm->{$self->{svn_path}};
2904 delete $rm->{''}; # we never delete the url we're tracking
2905 return unless %$rm;
2907 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2908 $self->{tree_b});
2909 local $/ = "\0";
2910 while (<$fh>) {
2911 chomp;
2912 my @dn = split m#/#, $_;
2913 while (pop @dn) {
2914 delete $rm->{join '/', @dn};
2916 unless (%$rm) {
2917 close $fh;
2918 return;
2921 command_close_pipe($fh, $ctx);
2923 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2924 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2925 $self->close_directory($bat->{$d}, $p);
2926 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2927 print "\tD+\t$d/\n" unless $::_q;
2928 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2929 delete $bat->{$d};
2933 sub open_or_add_dir {
2934 my ($self, $full_path, $baton) = @_;
2935 my $t = $self->{types}->{$full_path};
2936 if (!defined $t) {
2937 die "$full_path not known in r$self->{r} or we have a bug!\n";
2940 no warnings 'once';
2941 # SVN::Node::none and SVN::Node::file are used only once,
2942 # so we're shutting up Perl's warnings about them.
2943 if ($t == $SVN::Node::none) {
2944 return $self->add_directory($full_path, $baton,
2945 undef, -1, $self->{pool});
2946 } elsif ($t == $SVN::Node::dir) {
2947 return $self->open_directory($full_path, $baton,
2948 $self->{r}, $self->{pool});
2949 } # no warnings 'once'
2950 print STDERR "$full_path already exists in repository at ",
2951 "r$self->{r} and it is not a directory (",
2952 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2953 } # no warnings 'once'
2954 exit 1;
2957 sub ensure_path {
2958 my ($self, $path) = @_;
2959 my $bat = $self->{bat};
2960 my $repo_path = $self->repo_path($path);
2961 return $bat->{''} unless (length $repo_path);
2962 my @p = split m#/+#, $repo_path;
2963 my $c = shift @p;
2964 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2965 while (@p) {
2966 my $c0 = $c;
2967 $c .= '/' . shift @p;
2968 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2970 return $bat->{$c};
2973 sub A {
2974 my ($self, $m) = @_;
2975 my ($dir, $file) = split_path($m->{file_b});
2976 my $pbat = $self->ensure_path($dir);
2977 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2978 undef, -1);
2979 print "\tA\t$m->{file_b}\n" unless $::_q;
2980 $self->chg_file($fbat, $m);
2981 $self->close_file($fbat,undef,$self->{pool});
2984 sub C {
2985 my ($self, $m) = @_;
2986 my ($dir, $file) = split_path($m->{file_b});
2987 my $pbat = $self->ensure_path($dir);
2988 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2989 $self->url_path($m->{file_a}), $self->{r});
2990 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2991 $self->chg_file($fbat, $m);
2992 $self->close_file($fbat,undef,$self->{pool});
2995 sub delete_entry {
2996 my ($self, $path, $pbat) = @_;
2997 my $rpath = $self->repo_path($path);
2998 my ($dir, $file) = split_path($rpath);
2999 $self->{rm}->{$dir} = 1;
3000 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3003 sub R {
3004 my ($self, $m) = @_;
3005 my ($dir, $file) = split_path($m->{file_b});
3006 my $pbat = $self->ensure_path($dir);
3007 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3008 $self->url_path($m->{file_a}), $self->{r});
3009 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3010 $self->chg_file($fbat, $m);
3011 $self->close_file($fbat,undef,$self->{pool});
3013 ($dir, $file) = split_path($m->{file_a});
3014 $pbat = $self->ensure_path($dir);
3015 $self->delete_entry($m->{file_a}, $pbat);
3018 sub M {
3019 my ($self, $m) = @_;
3020 my ($dir, $file) = split_path($m->{file_b});
3021 my $pbat = $self->ensure_path($dir);
3022 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3023 $pbat,$self->{r},$self->{pool});
3024 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3025 $self->chg_file($fbat, $m);
3026 $self->close_file($fbat,undef,$self->{pool});
3029 sub T { shift->M(@_) }
3031 sub change_file_prop {
3032 my ($self, $fbat, $pname, $pval) = @_;
3033 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3036 sub chg_file {
3037 my ($self, $fbat, $m) = @_;
3038 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3039 $self->change_file_prop($fbat,'svn:executable','*');
3040 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3041 $self->change_file_prop($fbat,'svn:executable',undef);
3043 my $fh = IO::File->new_tmpfile or croak $!;
3044 if ($m->{mode_b} =~ /^120/) {
3045 print $fh 'link ' or croak $!;
3046 $self->change_file_prop($fbat,'svn:special','*');
3047 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3048 $self->change_file_prop($fbat,'svn:special',undef);
3050 defined(my $pid = fork) or croak $!;
3051 if (!$pid) {
3052 open STDOUT, '>&', $fh or croak $!;
3053 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3055 waitpid $pid, 0;
3056 croak $? if $?;
3057 $fh->flush == 0 or croak $!;
3058 seek $fh, 0, 0 or croak $!;
3060 my $md5 = Digest::MD5->new;
3061 $md5->addfile($fh) or croak $!;
3062 seek $fh, 0, 0 or croak $!;
3064 my $exp = $md5->hexdigest;
3065 my $pool = SVN::Pool->new;
3066 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3067 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3068 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3069 $pool->clear;
3071 close $fh or croak $!;
3074 sub D {
3075 my ($self, $m) = @_;
3076 my ($dir, $file) = split_path($m->{file_b});
3077 my $pbat = $self->ensure_path($dir);
3078 print "\tD\t$m->{file_b}\n" unless $::_q;
3079 $self->delete_entry($m->{file_b}, $pbat);
3082 sub close_edit {
3083 my ($self) = @_;
3084 my ($p,$bat) = ($self->{pool}, $self->{bat});
3085 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3086 next if $_ eq '';
3087 $self->close_directory($bat->{$_}, $p);
3089 $self->close_directory($bat->{''}, $p);
3090 $self->SUPER::close_edit($p);
3091 $p->clear;
3094 sub abort_edit {
3095 my ($self) = @_;
3096 $self->SUPER::abort_edit($self->{pool});
3099 sub DESTROY {
3100 my $self = shift;
3101 $self->SUPER::DESTROY(@_);
3102 $self->{pool}->clear;
3105 # this drives the editor
3106 sub apply_diff {
3107 my ($self) = @_;
3108 my $mods = $self->{mods};
3109 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3110 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3111 my $f = $m->{chg};
3112 if (defined $o{$f}) {
3113 $self->$f($m);
3114 } else {
3115 fatal("Invalid change type: $f\n");
3118 $self->rmdirs if $_rmdir;
3119 if (@$mods == 0) {
3120 $self->abort_edit;
3121 } else {
3122 $self->close_edit;
3124 return scalar @$mods;
3127 package Git::SVN::Ra;
3128 use vars qw/@ISA $config_dir $_log_window_size/;
3129 use strict;
3130 use warnings;
3131 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3133 BEGIN {
3134 # enforce temporary pool usage for some simple functions
3135 no strict 'refs';
3136 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3137 my $SUPER = "SUPER::$f";
3138 *$f = sub {
3139 my $self = shift;
3140 my $pool = SVN::Pool->new;
3141 my @ret = $self->$SUPER(@_,$pool);
3142 $pool->clear;
3143 wantarray ? @ret : $ret[0];
3148 sub _auth_providers () {
3150 SVN::Client::get_simple_provider(),
3151 SVN::Client::get_ssl_server_trust_file_provider(),
3152 SVN::Client::get_simple_prompt_provider(
3153 \&Git::SVN::Prompt::simple, 2),
3154 SVN::Client::get_ssl_client_cert_file_provider(),
3155 SVN::Client::get_ssl_client_cert_prompt_provider(
3156 \&Git::SVN::Prompt::ssl_client_cert, 2),
3157 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3158 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3159 SVN::Client::get_username_provider(),
3160 SVN::Client::get_ssl_server_trust_prompt_provider(
3161 \&Git::SVN::Prompt::ssl_server_trust),
3162 SVN::Client::get_username_prompt_provider(
3163 \&Git::SVN::Prompt::username, 2)
3167 sub new {
3168 my ($class, $url) = @_;
3169 $url =~ s!/+$!!;
3170 return $RA if ($RA && $RA->{url} eq $url);
3172 SVN::_Core::svn_config_ensure($config_dir, undef);
3173 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3174 my $config = SVN::Core::config_get_config($config_dir);
3175 $RA = undef;
3176 my $dont_store_passwords = 1;
3177 my $conf_t = ${$config}{'config'};
3179 no warnings 'once';
3180 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3181 # produces warnings that variables are used only once.
3182 # I had not found the better way to shut them up, so
3183 # the warnings of type 'once' are disabled in this block.
3184 if (SVN::_Core::svn_config_get_bool($conf_t,
3185 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3186 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3187 1) == 0) {
3188 SVN::_Core::svn_auth_set_parameter($baton,
3189 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3190 bless (\$dont_store_passwords, "_p_void"));
3192 if (SVN::_Core::svn_config_get_bool($conf_t,
3193 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3194 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3195 1) == 0) {
3196 $Git::SVN::Prompt::_no_auth_cache = 1;
3198 } # no warnings 'once'
3199 my $self = SVN::Ra->new(url => $url, auth => $baton,
3200 config => $config,
3201 pool => SVN::Pool->new,
3202 auth_provider_callbacks => $callbacks);
3203 $self->{svn_path} = $url;
3204 $self->{repos_root} = $self->get_repos_root;
3205 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3206 $self->{cache} = { check_path => { r => 0, data => {} },
3207 get_dir => { r => 0, data => {} } };
3208 $RA = bless $self, $class;
3211 sub check_path {
3212 my ($self, $path, $r) = @_;
3213 my $cache = $self->{cache}->{check_path};
3214 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3215 return $cache->{data}->{$path};
3217 my $pool = SVN::Pool->new;
3218 my $t = $self->SUPER::check_path($path, $r, $pool);
3219 $pool->clear;
3220 if ($r != $cache->{r}) {
3221 %{$cache->{data}} = ();
3222 $cache->{r} = $r;
3224 $cache->{data}->{$path} = $t;
3227 sub get_dir {
3228 my ($self, $dir, $r) = @_;
3229 my $cache = $self->{cache}->{get_dir};
3230 if ($r == $cache->{r}) {
3231 if (my $x = $cache->{data}->{$dir}) {
3232 return wantarray ? @$x : $x->[0];
3235 my $pool = SVN::Pool->new;
3236 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3237 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3238 $pool->clear;
3239 if ($r != $cache->{r}) {
3240 %{$cache->{data}} = ();
3241 $cache->{r} = $r;
3243 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3244 wantarray ? (\%dirents, $r, $props) : \%dirents;
3247 sub DESTROY {
3248 # do not call the real DESTROY since we store ourselves in $RA
3251 sub get_log {
3252 my ($self, @args) = @_;
3253 my $pool = SVN::Pool->new;
3254 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3255 my $ret = $self->SUPER::get_log(@args, $pool);
3256 $pool->clear;
3257 $ret;
3260 sub trees_match {
3261 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3262 my $ctx = SVN::Client->new(auth => _auth_providers);
3263 my $out = IO::File->new_tmpfile;
3265 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3266 # $ctx->diff(), so we'll create a default one
3267 my $pool = SVN::Pool->new_default_sub;
3269 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3270 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3271 $out->flush;
3272 my $ret = (($out->stat)[7] == 0);
3273 close $out or croak $!;
3275 $ret;
3278 sub get_commit_editor {
3279 my ($self, $log, $cb, $pool) = @_;
3280 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3281 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3284 sub gs_do_update {
3285 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3286 my $new = ($rev_a == $rev_b);
3287 my $path = $gs->{path};
3289 if ($new && -e $gs->{index}) {
3290 unlink $gs->{index} or die
3291 "Couldn't unlink index: $gs->{index}: $!\n";
3293 my $pool = SVN::Pool->new;
3294 $editor->set_path_strip($path);
3295 my (@pc) = split m#/#, $path;
3296 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3297 1, $editor, $pool);
3298 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3300 # Since we can't rely on svn_ra_reparent being available, we'll
3301 # just have to do some magic with set_path to make it so
3302 # we only want a partial path.
3303 my $sp = '';
3304 my $final = join('/', @pc);
3305 while (@pc) {
3306 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3307 $sp .= '/' if length $sp;
3308 $sp .= shift @pc;
3310 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3312 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3314 $reporter->finish_report($pool);
3315 $pool->clear;
3316 $editor->{git_commit_ok};
3319 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3320 # svn_ra_reparent didn't work before 1.4)
3321 sub gs_do_switch {
3322 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3323 my $path = $gs->{path};
3324 my $pool = SVN::Pool->new;
3326 my $full_url = $self->{url};
3327 my $old_url = $full_url;
3328 $full_url .= "/$path" if length $path;
3329 my ($ra, $reparented);
3330 if ($old_url ne $full_url) {
3331 if ($old_url !~ m#^svn(\+ssh)?://#) {
3332 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3333 $pool);
3334 $self->{url} = $full_url;
3335 $reparented = 1;
3336 } else {
3337 $_[0] = undef;
3338 $self = undef;
3339 $RA = undef;
3340 $ra = Git::SVN::Ra->new($full_url);
3341 $ra_invalid = 1;
3344 $ra ||= $self;
3345 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3346 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3347 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3348 $reporter->finish_report($pool);
3350 if ($reparented) {
3351 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3352 $self->{url} = $old_url;
3355 $pool->clear;
3356 $editor->{git_commit_ok};
3359 sub longest_common_path {
3360 my ($gsv, $globs) = @_;
3361 my %common;
3362 my $common_max = scalar @$gsv;
3364 foreach my $gs (@$gsv) {
3365 my @tmp = split m#/#, $gs->{path};
3366 my $p = '';
3367 foreach (@tmp) {
3368 $p .= length($p) ? "/$_" : $_;
3369 $common{$p} ||= 0;
3370 $common{$p}++;
3373 $globs ||= [];
3374 $common_max += scalar @$globs;
3375 foreach my $glob (@$globs) {
3376 my @tmp = split m#/#, $glob->{path}->{left};
3377 my $p = '';
3378 foreach (@tmp) {
3379 $p .= length($p) ? "/$_" : $_;
3380 $common{$p} ||= 0;
3381 $common{$p}++;
3385 my $longest_path = '';
3386 foreach (sort {length $b <=> length $a} keys %common) {
3387 if ($common{$_} == $common_max) {
3388 $longest_path = $_;
3389 last;
3392 $longest_path;
3395 sub gs_fetch_loop_common {
3396 my ($self, $base, $head, $gsv, $globs) = @_;
3397 return if ($base > $head);
3398 my $inc = $_log_window_size;
3399 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3400 my $longest_path = longest_common_path($gsv, $globs);
3401 my $ra_url = $self->{url};
3402 while (1) {
3403 my %revs;
3404 my $err;
3405 my $err_handler = $SVN::Error::handler;
3406 $SVN::Error::handler = sub {
3407 ($err) = @_;
3408 skip_unknown_revs($err);
3410 sub _cb {
3411 my ($paths, $r, $author, $date, $log) = @_;
3412 [ dup_changed_paths($paths),
3413 { author => $author, date => $date, log => $log } ];
3415 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3416 sub { $revs{$_[1]} = _cb(@_) });
3417 if ($err && $max >= $head) {
3418 print STDERR "Path '$longest_path' ",
3419 "was probably deleted:\n",
3420 $err->expanded_message,
3421 "\nWill attempt to follow ",
3422 "revisions r$min .. r$max ",
3423 "committed before the deletion\n";
3424 my $hi = $max;
3425 while (--$hi >= $min) {
3426 my $ok;
3427 $self->get_log([$longest_path], $min, $hi,
3428 0, 1, 1, sub {
3429 $ok ||= $_[1];
3430 $revs{$_[1]} = _cb(@_) });
3431 if ($ok) {
3432 print STDERR "r$min .. r$ok OK\n";
3433 last;
3437 $SVN::Error::handler = $err_handler;
3439 my %exists = map { $_->{path} => $_ } @$gsv;
3440 foreach my $r (sort {$a <=> $b} keys %revs) {
3441 my ($paths, $logged) = @{$revs{$r}};
3443 foreach my $gs ($self->match_globs(\%exists, $paths,
3444 $globs, $r)) {
3445 if ($gs->rev_db_max >= $r) {
3446 next;
3448 next unless $gs->match_paths($paths, $r);
3449 $gs->{logged_rev_props} = $logged;
3450 if (my $last_commit = $gs->last_commit) {
3451 $gs->assert_index_clean($last_commit);
3453 my $log_entry = $gs->do_fetch($paths, $r);
3454 if ($log_entry) {
3455 $gs->do_git_commit($log_entry);
3458 foreach my $g (@$globs) {
3459 my $k = "svn-remote.$g->{remote}." .
3460 "$g->{t}-maxRev";
3461 Git::SVN::tmp_config($k, $r);
3463 if ($ra_invalid) {
3464 $_[0] = undef;
3465 $self = undef;
3466 $RA = undef;
3467 $self = Git::SVN::Ra->new($ra_url);
3468 $ra_invalid = undef;
3471 # pre-fill the .rev_db since it'll eventually get filled in
3472 # with '0' x40 if something new gets committed
3473 foreach my $gs (@$gsv) {
3474 next if defined $gs->rev_db_get($max);
3475 $gs->rev_db_set($max, 0 x40);
3477 foreach my $g (@$globs) {
3478 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3479 Git::SVN::tmp_config($k, $max);
3481 last if $max >= $head;
3482 $min = $max + 1;
3483 $max += $inc;
3484 $max = $head if ($max > $head);
3488 sub match_globs {
3489 my ($self, $exists, $paths, $globs, $r) = @_;
3491 sub get_dir_check {
3492 my ($self, $exists, $g, $r) = @_;
3493 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3494 return unless scalar @x == 3;
3495 my $dirents = $x[0];
3496 foreach my $de (keys %$dirents) {
3497 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3498 my $p = $g->{path}->full_path($de);
3499 next if $exists->{$p};
3500 next if (length $g->{path}->{right} &&
3501 ($self->check_path($p, $r) !=
3502 $SVN::Node::dir));
3503 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3504 $g->{ref}->full_path($de), 1);
3507 foreach my $g (@$globs) {
3508 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3509 if ($path->{action} =~ /^[AR]$/) {
3510 get_dir_check($self, $exists, $g, $r);
3513 foreach (keys %$paths) {
3514 if (/$g->{path}->{left_regex}/ &&
3515 !/$g->{path}->{regex}/) {
3516 next if $paths->{$_}->{action} !~ /^[AR]$/;
3517 get_dir_check($self, $exists, $g, $r);
3519 next unless /$g->{path}->{regex}/;
3520 my $p = $1;
3521 my $pathname = $g->{path}->full_path($p);
3522 next if $exists->{$pathname};
3523 next if ($self->check_path($pathname, $r) !=
3524 $SVN::Node::dir);
3525 $exists->{$pathname} = Git::SVN->init(
3526 $self->{url}, $pathname, undef,
3527 $g->{ref}->full_path($p), 1);
3529 my $c = '';
3530 foreach (split m#/#, $g->{path}->{left}) {
3531 $c .= "/$_";
3532 next unless ($paths->{$c} &&
3533 ($paths->{$c}->{action} =~ /^[AR]$/));
3534 get_dir_check($self, $exists, $g, $r);
3537 values %$exists;
3540 sub minimize_url {
3541 my ($self) = @_;
3542 return $self->{url} if ($self->{url} eq $self->{repos_root});
3543 my $url = $self->{repos_root};
3544 my @components = split(m!/!, $self->{svn_path});
3545 my $c = '';
3546 do {
3547 $url .= "/$c" if length $c;
3548 eval { (ref $self)->new($url)->get_latest_revnum };
3549 } while ($@ && ($c = shift @components));
3550 $url;
3553 sub can_do_switch {
3554 my $self = shift;
3555 unless (defined $can_do_switch) {
3556 my $pool = SVN::Pool->new;
3557 my $rep = eval {
3558 $self->do_switch(1, '', 0, $self->{url},
3559 SVN::Delta::Editor->new, $pool);
3561 if ($@) {
3562 $can_do_switch = 0;
3563 } else {
3564 $rep->abort_report($pool);
3565 $can_do_switch = 1;
3567 $pool->clear;
3569 $can_do_switch;
3572 sub skip_unknown_revs {
3573 my ($err) = @_;
3574 my $errno = $err->apr_err();
3575 # Maybe the branch we're tracking didn't
3576 # exist when the repo started, so it's
3577 # not an error if it doesn't, just continue
3579 # Wonderfully consistent library, eh?
3580 # 160013 - svn:// and file://
3581 # 175002 - http(s)://
3582 # 175007 - http(s):// (this repo required authorization, too...)
3583 # More codes may be discovered later...
3584 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3585 my $err_key = $err->expanded_message;
3586 # revision numbers change every time, filter them out
3587 $err_key =~ s/\d+/\0/g;
3588 $err_key = "$errno\0$err_key";
3589 unless ($ignored_err{$err_key}) {
3590 warn "W: Ignoring error from SVN, path probably ",
3591 "does not exist: ($errno): ",
3592 $err->expanded_message,"\n";
3593 $ignored_err{$err_key} = 1;
3595 return;
3597 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3600 # svn_log_changed_path_t objects passed to get_log are likely to be
3601 # overwritten even if only the refs are copied to an external variable,
3602 # so we should dup the structures in their entirety. Using an externally
3603 # passed pool (instead of our temporary and quickly cleared pool in
3604 # Git::SVN::Ra) does not help matters at all...
3605 sub dup_changed_paths {
3606 my ($paths) = @_;
3607 return undef unless $paths;
3608 my %ret;
3609 foreach my $p (keys %$paths) {
3610 my $i = $paths->{$p};
3611 my %s = map { $_ => $i->$_ }
3612 qw/copyfrom_path copyfrom_rev action/;
3613 $ret{$p} = \%s;
3615 \%ret;
3618 package Git::SVN::Log;
3619 use strict;
3620 use warnings;
3621 use POSIX qw/strftime/;
3622 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3623 %rusers $show_commit $incremental/;
3624 my $l_fmt;
3626 sub cmt_showable {
3627 my ($c) = @_;
3628 return 1 if defined $c->{r};
3630 # big commit message got truncated by the 16k pretty buffer in rev-list
3631 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3632 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3633 @{$c->{l}} = ();
3634 my @log = command(qw/cat-file commit/, $c->{c});
3636 # shift off the headers
3637 shift @log while ($log[0] ne '');
3638 shift @log;
3640 # TODO: make $c->{l} not have a trailing newline in the future
3641 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3643 (undef, $c->{r}, undef) = ::extract_metadata(
3644 (grep(/^git-svn-id: /, @log))[-1]);
3646 return defined $c->{r};
3649 sub log_use_color {
3650 return 1 if $color;
3651 my ($dc, $dcvar);
3652 $dcvar = 'color.diff';
3653 $dc = `git-config --get $dcvar`;
3654 if ($dc eq '') {
3655 # nothing at all; fallback to "diff.color"
3656 $dcvar = 'diff.color';
3657 $dc = `git-config --get $dcvar`;
3659 chomp($dc);
3660 if ($dc eq 'auto') {
3661 my $pc;
3662 $pc = `git-config --get color.pager`;
3663 if ($pc eq '') {
3664 # does not have it -- fallback to pager.color
3665 $pc = `git-config --bool --get pager.color`;
3667 else {
3668 $pc = `git-config --bool --get color.pager`;
3669 if ($?) {
3670 $pc = 'false';
3673 chomp($pc);
3674 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3675 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3677 return 0;
3679 return 0 if $dc eq 'never';
3680 return 1 if $dc eq 'always';
3681 chomp($dc = `git-config --bool --get $dcvar`);
3682 return ($dc eq 'true');
3685 sub git_svn_log_cmd {
3686 my ($r_min, $r_max, @args) = @_;
3687 my $head = 'HEAD';
3688 my (@files, @log_opts);
3689 foreach my $x (@args) {
3690 if ($x eq '--' || @files) {
3691 push @files, $x;
3692 } else {
3693 if (::verify_ref("$x^0")) {
3694 $head = $x;
3695 } else {
3696 push @log_opts, $x;
3701 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3702 $gs ||= Git::SVN->_new;
3703 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3704 $gs->refname);
3705 push @cmd, '-r' unless $non_recursive;
3706 push @cmd, qw/--raw --name-status/ if $verbose;
3707 push @cmd, '--color' if log_use_color();
3708 push @cmd, @log_opts;
3709 if (defined $r_max && $r_max == $r_min) {
3710 push @cmd, '--max-count=1';
3711 if (my $c = $gs->rev_db_get($r_max)) {
3712 push @cmd, $c;
3714 } elsif (defined $r_max) {
3715 my ($c_min, $c_max);
3716 $c_max = $gs->rev_db_get($r_max);
3717 $c_min = $gs->rev_db_get($r_min);
3718 if (defined $c_min && defined $c_max) {
3719 if ($r_max > $r_max) {
3720 push @cmd, "$c_min..$c_max";
3721 } else {
3722 push @cmd, "$c_max..$c_min";
3724 } elsif ($r_max > $r_min) {
3725 push @cmd, $c_max;
3726 } else {
3727 push @cmd, $c_min;
3730 return (@cmd, @files);
3733 # adapted from pager.c
3734 sub config_pager {
3735 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3736 if (!defined $pager) {
3737 $pager = 'less';
3738 } elsif (length $pager == 0 || $pager eq 'cat') {
3739 $pager = undef;
3743 sub run_pager {
3744 return unless -t *STDOUT && defined $pager;
3745 pipe my $rfd, my $wfd or return;
3746 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3747 if (!$pid) {
3748 open STDOUT, '>&', $wfd or
3749 ::fatal "Can't redirect to stdout: $!\n";
3750 return;
3752 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3753 $ENV{LESS} ||= 'FRSX';
3754 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3757 sub tz_to_s_offset {
3758 my ($tz) = @_;
3759 $tz =~ s/(\d\d)$//;
3760 return ($1 * 60) + ($tz * 3600);
3763 sub get_author_info {
3764 my ($dest, $author, $t, $tz) = @_;
3765 $author =~ s/(?:^\s*|\s*$)//g;
3766 $dest->{a_raw} = $author;
3767 my $au;
3768 if ($::_authors) {
3769 $au = $rusers{$author} || undef;
3771 if (!$au) {
3772 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3774 $dest->{t} = $t;
3775 $dest->{tz} = $tz;
3776 $dest->{a} = $au;
3777 # Date::Parse isn't in the standard Perl distro :(
3778 if ($tz =~ s/^\+//) {
3779 $t += tz_to_s_offset($tz);
3780 } elsif ($tz =~ s/^\-//) {
3781 $t -= tz_to_s_offset($tz);
3783 $dest->{t_utc} = $t;
3786 sub process_commit {
3787 my ($c, $r_min, $r_max, $defer) = @_;
3788 if (defined $r_min && defined $r_max) {
3789 if ($r_min == $c->{r} && $r_min == $r_max) {
3790 show_commit($c);
3791 return 0;
3793 return 1 if $r_min == $r_max;
3794 if ($r_min < $r_max) {
3795 # we need to reverse the print order
3796 return 0 if (defined $limit && --$limit < 0);
3797 push @$defer, $c;
3798 return 1;
3800 if ($r_min != $r_max) {
3801 return 1 if ($r_min < $c->{r});
3802 return 1 if ($r_max > $c->{r});
3805 return 0 if (defined $limit && --$limit < 0);
3806 show_commit($c);
3807 return 1;
3810 sub show_commit {
3811 my $c = shift;
3812 if ($oneline) {
3813 my $x = "\n";
3814 if (my $l = $c->{l}) {
3815 while ($l->[0] =~ /^\s*$/) { shift @$l }
3816 $x = $l->[0];
3818 $l_fmt ||= 'A' . length($c->{r});
3819 print 'r',pack($l_fmt, $c->{r}),' | ';
3820 print "$c->{c} | " if $show_commit;
3821 print $x;
3822 } else {
3823 show_commit_normal($c);
3827 sub show_commit_changed_paths {
3828 my ($c) = @_;
3829 return unless $c->{changed};
3830 print "Changed paths:\n", @{$c->{changed}};
3833 sub show_commit_normal {
3834 my ($c) = @_;
3835 print '-' x72, "\nr$c->{r} | ";
3836 print "$c->{c} | " if $show_commit;
3837 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3838 localtime($c->{t_utc})), ' | ';
3839 my $nr_line = 0;
3841 if (my $l = $c->{l}) {
3842 while ($l->[$#$l] eq "\n" && $#$l > 0
3843 && $l->[($#$l - 1)] eq "\n") {
3844 pop @$l;
3846 $nr_line = scalar @$l;
3847 if (!$nr_line) {
3848 print "1 line\n\n\n";
3849 } else {
3850 if ($nr_line == 1) {
3851 $nr_line = '1 line';
3852 } else {
3853 $nr_line .= ' lines';
3855 print $nr_line, "\n";
3856 show_commit_changed_paths($c);
3857 print "\n";
3858 print $_ foreach @$l;
3860 } else {
3861 print "1 line\n";
3862 show_commit_changed_paths($c);
3863 print "\n";
3866 foreach my $x (qw/raw stat diff/) {
3867 if ($c->{$x}) {
3868 print "\n";
3869 print $_ foreach @{$c->{$x}}
3874 sub cmd_show_log {
3875 my (@args) = @_;
3876 my ($r_min, $r_max);
3877 my $r_last = -1; # prevent dupes
3878 if (defined $TZ) {
3879 $ENV{TZ} = $TZ;
3880 } else {
3881 delete $ENV{TZ};
3883 if (defined $::_revision) {
3884 if ($::_revision =~ /^(\d+):(\d+)$/) {
3885 ($r_min, $r_max) = ($1, $2);
3886 } elsif ($::_revision =~ /^\d+$/) {
3887 $r_min = $r_max = $::_revision;
3888 } else {
3889 ::fatal "-r$::_revision is not supported, use ",
3890 "standard \'git log\' arguments instead\n";
3894 config_pager();
3895 @args = git_svn_log_cmd($r_min, $r_max, @args);
3896 my $log = command_output_pipe(@args);
3897 run_pager();
3898 my (@k, $c, $d, $stat);
3899 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3900 while (<$log>) {
3901 if (/^${esc_color}commit ($::sha1_short)/o) {
3902 my $cmt = $1;
3903 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3904 $r_last = $c->{r};
3905 process_commit($c, $r_min, $r_max, \@k) or
3906 goto out;
3908 $d = undef;
3909 $c = { c => $cmt };
3910 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3911 get_author_info($c, $1, $2, $3);
3912 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3913 # ignore
3914 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3915 push @{$c->{raw}}, $_;
3916 } elsif (/^${esc_color}[ACRMDT]\t/) {
3917 # we could add $SVN->{svn_path} here, but that requires
3918 # remote access at the moment (repo_path_split)...
3919 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3920 push @{$c->{changed}}, $_;
3921 } elsif (/^${esc_color}diff /o) {
3922 $d = 1;
3923 push @{$c->{diff}}, $_;
3924 } elsif ($d) {
3925 push @{$c->{diff}}, $_;
3926 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3927 $esc_color*[\+\-]*$esc_color$/x) {
3928 $stat = 1;
3929 push @{$c->{stat}}, $_;
3930 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3931 push @{$c->{stat}}, $_;
3932 $stat = undef;
3933 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3934 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3935 } elsif (s/^${esc_color} //o) {
3936 push @{$c->{l}}, $_;
3939 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3940 $r_last = $c->{r};
3941 process_commit($c, $r_min, $r_max, \@k);
3943 if (@k) {
3944 my $swap = $r_max;
3945 $r_max = $r_min;
3946 $r_min = $swap;
3947 process_commit($_, $r_min, $r_max) foreach reverse @k;
3949 out:
3950 close $log;
3951 print '-' x72,"\n" unless $incremental || $oneline;
3954 package Git::SVN::Migration;
3955 # these version numbers do NOT correspond to actual version numbers
3956 # of git nor git-svn. They are just relative.
3958 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3960 # v1 layout: .git/$id/info/url, refs/remotes/$id
3962 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3964 # v3 layout: .git/svn/$id, refs/remotes/$id
3965 # - info/url may remain for backwards compatibility
3966 # - this is what we migrate up to this layout automatically,
3967 # - this will be used by git svn init on single branches
3968 # v3.1 layout (auto migrated):
3969 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3970 # for backwards compatibility
3972 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3973 # - this is only created for newly multi-init-ed
3974 # repositories. Similar in spirit to the
3975 # --use-separate-remotes option in git-clone (now default)
3976 # - we do not automatically migrate to this (following
3977 # the example set by core git)
3978 use strict;
3979 use warnings;
3980 use Carp qw/croak/;
3981 use File::Path qw/mkpath/;
3982 use File::Basename qw/dirname basename/;
3983 use vars qw/$_minimize/;
3985 sub migrate_from_v0 {
3986 my $git_dir = $ENV{GIT_DIR};
3987 return undef unless -d $git_dir;
3988 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3989 my $migrated = 0;
3990 while (<$fh>) {
3991 chomp;
3992 my ($id, $orig_ref) = ($_, $_);
3993 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3994 next unless -f "$git_dir/$id/info/url";
3995 my $new_ref = "refs/remotes/$id";
3996 if (::verify_ref("$new_ref^0")) {
3997 print STDERR "W: $orig_ref is probably an old ",
3998 "branch used by an ancient version of ",
3999 "git-svn.\n",
4000 "However, $new_ref also exists.\n",
4001 "We will not be able ",
4002 "to use this branch until this ",
4003 "ambiguity is resolved.\n";
4004 next;
4006 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4007 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4008 command_noisy('update-ref', $new_ref, $orig_ref);
4009 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4010 $migrated++;
4012 command_close_pipe($fh, $ctx);
4013 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4014 $migrated;
4017 sub migrate_from_v1 {
4018 my $git_dir = $ENV{GIT_DIR};
4019 my $migrated = 0;
4020 return $migrated unless -d $git_dir;
4021 my $svn_dir = "$git_dir/svn";
4023 # just in case somebody used 'svn' as their $id at some point...
4024 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4026 print STDERR "Migrating from a git-svn v1 layout...\n";
4027 mkpath([$svn_dir]);
4028 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4029 "$svn_dir\n\t(required for this version ",
4030 "($::VERSION) of git-svn) does not. exist\n";
4031 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4032 while (<$fh>) {
4033 my $x = $_;
4034 next unless $x =~ s#^refs/remotes/##;
4035 chomp $x;
4036 next unless -f "$git_dir/$x/info/url";
4037 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4038 next unless $u;
4039 my $dn = dirname("$git_dir/svn/$x");
4040 mkpath([$dn]) unless -d $dn;
4041 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4042 mkpath(["$git_dir/svn/svn"]);
4043 print STDERR " - $git_dir/$x/info => ",
4044 "$git_dir/svn/$x/info\n";
4045 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4046 croak "$!: $x";
4047 # don't worry too much about these, they probably
4048 # don't exist with repos this old (save for index,
4049 # and we can easily regenerate that)
4050 foreach my $f (qw/unhandled.log index .rev_db/) {
4051 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4053 } else {
4054 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4055 rename "$git_dir/$x", "$git_dir/svn/$x" or
4056 croak "$!: $x";
4058 $migrated++;
4060 command_close_pipe($fh, $ctx);
4061 print STDERR "Done migrating from a git-svn v1 layout\n";
4062 $migrated;
4065 sub read_old_urls {
4066 my ($l_map, $pfx, $path) = @_;
4067 my @dir;
4068 foreach (<$path/*>) {
4069 if (-r "$_/info/url") {
4070 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4071 my $ref_id = $pfx . basename $_;
4072 my $url = ::file_to_s("$_/info/url");
4073 $l_map->{$ref_id} = $url;
4074 } elsif (-d $_) {
4075 push @dir, $_;
4078 foreach (@dir) {
4079 my $x = $_;
4080 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4081 read_old_urls($l_map, $x, $_);
4085 sub migrate_from_v2 {
4086 my @cfg = command(qw/config -l/);
4087 return if grep /^svn-remote\..+\.url=/, @cfg;
4088 my %l_map;
4089 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4090 my $migrated = 0;
4092 foreach my $ref_id (sort keys %l_map) {
4093 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4094 if ($@) {
4095 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4097 $migrated++;
4099 $migrated;
4102 sub minimize_connections {
4103 my $r = Git::SVN::read_all_remotes();
4104 my $new_urls = {};
4105 my $root_repos = {};
4106 foreach my $repo_id (keys %$r) {
4107 my $url = $r->{$repo_id}->{url} or next;
4108 my $fetch = $r->{$repo_id}->{fetch} or next;
4109 my $ra = Git::SVN::Ra->new($url);
4111 # skip existing cases where we already connect to the root
4112 if (($ra->{url} eq $ra->{repos_root}) ||
4113 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4114 $repo_id)) {
4115 $root_repos->{$ra->{url}} = $repo_id;
4116 next;
4119 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4120 my $root_path = $ra->{url};
4121 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4122 foreach my $path (keys %$fetch) {
4123 my $ref_id = $fetch->{$path};
4124 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4126 # make sure we can read when connecting to
4127 # a higher level of a repository
4128 my ($last_rev, undef) = $gs->last_rev_commit;
4129 if (!defined $last_rev) {
4130 $last_rev = eval {
4131 $root_ra->get_latest_revnum;
4133 next if $@;
4135 my $new = $root_path;
4136 $new .= length $path ? "/$path" : '';
4137 eval {
4138 $root_ra->get_log([$new], $last_rev, $last_rev,
4139 0, 0, 1, sub { });
4141 next if $@;
4142 $new_urls->{$ra->{repos_root}}->{$new} =
4143 { ref_id => $ref_id,
4144 old_repo_id => $repo_id,
4145 old_path => $path };
4149 my @emptied;
4150 foreach my $url (keys %$new_urls) {
4151 # see if we can re-use an existing [svn-remote "repo_id"]
4152 # instead of creating a(n ugly) new section:
4153 my $repo_id = $root_repos->{$url} ||
4154 Git::SVN::sanitize_remote_name($url);
4156 my $fetch = $new_urls->{$url};
4157 foreach my $path (keys %$fetch) {
4158 my $x = $fetch->{$path};
4159 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4160 my $pfx = "svn-remote.$x->{old_repo_id}";
4162 my $old_fetch = quotemeta("$x->{old_path}:".
4163 "refs/remotes/$x->{ref_id}");
4164 command_noisy(qw/config --unset/,
4165 "$pfx.fetch", '^'. $old_fetch . '$');
4166 delete $r->{$x->{old_repo_id}}->
4167 {fetch}->{$x->{old_path}};
4168 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4169 command_noisy(qw/config --unset/,
4170 "$pfx.url");
4171 push @emptied, $x->{old_repo_id}
4175 if (@emptied) {
4176 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4177 "$ENV{GIT_DIR}/config";
4178 print STDERR <<EOF;
4179 The following [svn-remote] sections in your config file ($file) are empty
4180 and can be safely removed:
4182 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4186 sub migration_check {
4187 migrate_from_v0();
4188 migrate_from_v1();
4189 migrate_from_v2();
4190 minimize_connections() if $_minimize;
4193 package Git::IndexInfo;
4194 use strict;
4195 use warnings;
4196 use Git qw/command_input_pipe command_close_pipe/;
4198 sub new {
4199 my ($class) = @_;
4200 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4201 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4204 sub remove {
4205 my ($self, $path) = @_;
4206 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4207 return ++$self->{nr};
4209 undef;
4212 sub update {
4213 my ($self, $mode, $hash, $path) = @_;
4214 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4215 return ++$self->{nr};
4217 undef;
4220 sub DESTROY {
4221 my ($self) = @_;
4222 command_close_pipe($self->{gui}, $self->{ctx});
4225 package Git::SVN::GlobSpec;
4226 use strict;
4227 use warnings;
4229 sub new {
4230 my ($class, $glob) = @_;
4231 my $re = $glob;
4232 $re =~ s!/+$!!g; # no need for trailing slashes
4233 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4234 my ($left, $right) = ($1, $2);
4235 if ($nr > 1) {
4236 die "Only one '*' wildcard expansion ",
4237 "is supported (got $nr): '$glob'\n";
4238 } elsif ($nr == 0) {
4239 die "One '*' is needed for glob: '$glob'\n";
4241 $re = quotemeta($left) . $re . quotemeta($right);
4242 if (length $left && !($left =~ s!/+$!!g)) {
4243 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4245 if (length $right && !($right =~ s!^/+!!g)) {
4246 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4248 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4249 bless { left => $left, right => $right, left_regex => $left_re,
4250 regex => qr/$re/, glob => $glob }, $class;
4253 sub full_path {
4254 my ($self, $path) = @_;
4255 return (length $self->{left} ? "$self->{left}/" : '') .
4256 $path . (length $self->{right} ? "/$self->{right}" : '');
4259 __END__
4261 Data structures:
4264 $remotes = { # returned by read_all_remotes()
4265 'svn' => {
4266 # svn-remote.svn.url=https://svn.musicpd.org
4267 url => 'https://svn.musicpd.org',
4268 # svn-remote.svn.fetch=mpd/trunk:trunk
4269 fetch => {
4270 'mpd/trunk' => 'trunk',
4272 # svn-remote.svn.tags=mpd/tags/*:tags/*
4273 tags => {
4274 path => {
4275 left => 'mpd/tags',
4276 right => '',
4277 regex => qr!mpd/tags/([^/]+)$!,
4278 glob => 'tags/*',
4280 ref => {
4281 left => 'tags',
4282 right => '',
4283 regex => qr!tags/([^/]+)$!,
4284 glob => 'tags/*',
4290 $log_entry hashref as returned by libsvn_log_entry()
4292 log => 'whitespace-formatted log entry
4293 ', # trailing newline is preserved
4294 revision => '8', # integer
4295 date => '2004-02-24T17:01:44.108345Z', # commit date
4296 author => 'committer name'
4300 # this is generated by generate_diff();
4301 @mods = array of diff-index line hashes, each element represents one line
4302 of diff-index output
4304 diff-index line ($m hash)
4306 mode_a => first column of diff-index output, no leading ':',
4307 mode_b => second column of diff-index output,
4308 sha1_b => sha1sum of the final blob,
4309 chg => change type [MCRADT],
4310 file_a => original file name of a file (iff chg is 'C' or 'R')
4311 file_b => new/current file name of a file (any chg)
4315 # retval of read_url_paths{,_all}();
4316 $l_map = {
4317 # repository root url
4318 'https://svn.musicpd.org' => {
4319 # repository path # GIT_SVN_ID
4320 'mpd/trunk' => 'trunk',
4321 'mpd/tags/0.11.5' => 'tags/0.11.5',
4325 Notes:
4326 I don't trust the each() function on unless I created %hash myself
4327 because the internal iterator may not have started at base.