Make builtin-symbolic-ref.c use parse_options.
[git/trast.git] / git-svn.perl
blob22bb47b34d030ec4d1b3dc7cda05465559e0a09d
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use IO::File qw//;
39 use File::Basename qw/dirname basename/;
40 use File::Path qw/mkpath/;
41 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
42 use IPC::Open3;
43 use Git;
45 BEGIN {
46 # import functions from Git into our packages, en masse
47 no strict 'refs';
48 foreach (qw/command command_oneline command_noisy command_output_pipe
49 command_input_pipe command_close_pipe/) {
50 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
51 Git::SVN::Migration Git::SVN::Log Git::SVN),
52 __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 'proplist' => [ \&cmd_proplist,
139 'List all properties of a file or directory',
140 { 'revision|r=i' => \$_revision } ],
141 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
142 { 'revision|r=i' => \$_revision
143 } ],
144 'multi-fetch' => [ \&cmd_multi_fetch,
145 "Deprecated alias for $0 fetch --all",
146 { 'revision|r=s' => \$_revision, %fc_opts } ],
147 'migrate' => [ sub { },
148 # no-op, we automatically run this anyways,
149 'Migrate configuration/metadata/layout from
150 previous versions of git-svn',
151 { 'minimize' => \$Git::SVN::Migration::_minimize,
152 %remote_opts } ],
153 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
154 { 'limit=i' => \$Git::SVN::Log::limit,
155 'revision|r=s' => \$_revision,
156 'verbose|v' => \$Git::SVN::Log::verbose,
157 'incremental' => \$Git::SVN::Log::incremental,
158 'oneline' => \$Git::SVN::Log::oneline,
159 'show-commit' => \$Git::SVN::Log::show_commit,
160 'non-recursive' => \$Git::SVN::Log::non_recursive,
161 'authors-file|A=s' => \$_authors,
162 'color' => \$Git::SVN::Log::color,
163 'pager=s' => \$Git::SVN::Log::pager
164 } ],
165 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
166 {} ],
167 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
168 { 'merge|m|M' => \$_merge,
169 'verbose|v' => \$_verbose,
170 'strategy|s=s' => \$_strategy,
171 'local|l' => \$_local,
172 'fetch-all|all' => \$_fetch_all,
173 %fc_opts } ],
174 'commit-diff' => [ \&cmd_commit_diff,
175 'Commit a diff between two trees',
176 { 'message|m=s' => \$_message,
177 'file|F=s' => \$_file,
178 'revision|r=s' => \$_revision,
179 %cmt_opts } ],
182 my $cmd;
183 for (my $i = 0; $i < @ARGV; $i++) {
184 if (defined $cmd{$ARGV[$i]}) {
185 $cmd = $ARGV[$i];
186 splice @ARGV, $i, 1;
187 last;
191 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
193 read_repo_config(\%opts);
194 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
195 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
196 'minimize-connections' => \$Git::SVN::Migration::_minimize,
197 'id|i=s' => \$Git::SVN::default_ref_id,
198 'svn-remote|remote|R=s' => sub {
199 $Git::SVN::no_reuse_existing = 1;
200 $Git::SVN::default_repo_id = $_[1] });
201 exit 1 if (!$rv && $cmd && $cmd ne 'log');
203 usage(0) if $_help;
204 version() if $_version;
205 usage(1) unless defined $cmd;
206 load_authors() if $_authors;
208 # make sure we're always running
209 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
210 unless (-d $ENV{GIT_DIR}) {
211 if ($git_dir_user_set) {
212 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
213 "but it is not a directory\n";
215 my $git_dir = delete $ENV{GIT_DIR};
216 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
217 unless (length $cdup) {
218 die "Already at toplevel, but $git_dir ",
219 "not found '$cdup'\n";
221 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
222 unless (-d $git_dir) {
223 die "$git_dir still not found after going to ",
224 "'$cdup'\n";
226 $ENV{GIT_DIR} = $git_dir;
229 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
230 Git::SVN::Migration::migration_check();
232 Git::SVN::init_vars();
233 eval {
234 Git::SVN::verify_remotes_sanity();
235 $cmd{$cmd}->[0]->(@ARGV);
237 fatal $@ if $@;
238 post_fetch_checkout();
239 exit 0;
241 ####################### primary functions ######################
242 sub usage {
243 my $exit = shift || 0;
244 my $fd = $exit ? \*STDERR : \*STDOUT;
245 print $fd <<"";
246 git-svn - bidirectional operations between a single Subversion tree and git
247 Usage: $0 <command> [options] [arguments]\n
249 print $fd "Available commands:\n" unless $cmd;
251 foreach (sort keys %cmd) {
252 next if $cmd && $cmd ne $_;
253 next if /^multi-/; # don't show deprecated commands
254 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
255 foreach (keys %{$cmd{$_}->[2]}) {
256 # mixed-case options are for .git/config only
257 next if /[A-Z]/ && /^[a-z]+$/i;
258 # prints out arguments as they should be passed:
259 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
260 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
261 "--$_" : "-$_" }
262 split /\|/,$_)," $x\n";
265 print $fd <<"";
266 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
267 arbitrary identifier if you're tracking multiple SVN branches/repositories in
268 one git repository and want to keep them separate. See git-svn(1) for more
269 information.
271 exit $exit;
274 sub version {
275 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
276 exit 0;
279 sub do_git_init_db {
280 unless (-d $ENV{GIT_DIR}) {
281 my @init_db = ('init');
282 push @init_db, "--template=$_template" if defined $_template;
283 if (defined $_shared) {
284 if ($_shared =~ /[a-z]/) {
285 push @init_db, "--shared=$_shared";
286 } else {
287 push @init_db, "--shared";
290 command_noisy(@init_db);
292 my $set;
293 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
294 foreach my $i (keys %icv) {
295 die "'$set' and '$i' cannot both be set\n" if $set;
296 next unless defined $icv{$i};
297 command_noisy('config', "$pfx.$i", $icv{$i});
298 $set = $i;
302 sub init_subdir {
303 my $repo_path = shift or return;
304 mkpath([$repo_path]) unless -d $repo_path;
305 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
306 $ENV{GIT_DIR} = '.git';
309 sub cmd_clone {
310 my ($url, $path) = @_;
311 if (!defined $path &&
312 (defined $_trunk || defined $_branches || defined $_tags ||
313 defined $_stdlayout) &&
314 $url !~ m#^[a-z\+]+://#) {
315 $path = $url;
317 $path = basename($url) if !defined $path || !length $path;
318 cmd_init($url, $path);
319 Git::SVN::fetch_all($Git::SVN::default_repo_id);
322 sub cmd_init {
323 if (defined $_stdlayout) {
324 $_trunk = 'trunk' if (!defined $_trunk);
325 $_tags = 'tags' if (!defined $_tags);
326 $_branches = 'branches' if (!defined $_branches);
328 if (defined $_trunk || defined $_branches || defined $_tags) {
329 return cmd_multi_init(@_);
331 my $url = shift or die "SVN repository location required ",
332 "as a command-line argument\n";
333 init_subdir(@_);
334 do_git_init_db();
336 Git::SVN->init($url);
339 sub cmd_fetch {
340 if (grep /^\d+=./, @_) {
341 die "'<rev>=<commit>' fetch arguments are ",
342 "no longer supported.\n";
344 my ($remote) = @_;
345 if (@_ > 1) {
346 die "Usage: $0 fetch [--all] [svn-remote]\n";
348 $remote ||= $Git::SVN::default_repo_id;
349 if ($_fetch_all) {
350 cmd_multi_fetch();
351 } else {
352 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
356 sub cmd_set_tree {
357 my (@commits) = @_;
358 if ($_stdin || !@commits) {
359 print "Reading from stdin...\n";
360 @commits = ();
361 while (<STDIN>) {
362 if (/\b($sha1_short)\b/o) {
363 unshift @commits, $1;
367 my @revs;
368 foreach my $c (@commits) {
369 my @tmp = command('rev-parse',$c);
370 if (scalar @tmp == 1) {
371 push @revs, $tmp[0];
372 } elsif (scalar @tmp > 1) {
373 push @revs, reverse(command('rev-list',@tmp));
374 } else {
375 fatal "Failed to rev-parse $c";
378 my $gs = Git::SVN->new;
379 my ($r_last, $cmt_last) = $gs->last_rev_commit;
380 $gs->fetch;
381 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
382 fatal "There are new revisions that were fetched ",
383 "and need to be merged (or acknowledged) ",
384 "before committing.\nlast rev: $r_last\n",
385 " current: $gs->{last_rev}";
387 $gs->set_tree($_) foreach @revs;
388 print "Done committing ",scalar @revs," revisions to SVN\n";
391 sub cmd_dcommit {
392 my $head = shift;
393 $head ||= 'HEAD';
394 my @refs;
395 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
396 print "Committing to $url ...\n";
397 unless ($gs) {
398 die "Unable to determine upstream SVN information from ",
399 "$head history\n";
401 my $last_rev;
402 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
403 if ($_no_rebase && scalar(@$linear_refs) > 1) {
404 warn "Attempting to commit more than one change while ",
405 "--no-rebase is enabled.\n",
406 "If these changes depend on each other, re-running ",
407 "without --no-rebase will be required."
409 foreach my $d (@$linear_refs) {
410 unless (defined $last_rev) {
411 (undef, $last_rev, undef) = cmt_metadata("$d~1");
412 unless (defined $last_rev) {
413 fatal "Unable to extract revision information ",
414 "from commit $d~1";
417 if ($_dry_run) {
418 print "diff-tree $d~1 $d\n";
419 } else {
420 my $cmt_rev;
421 my %ed_opts = ( r => $last_rev,
422 log => get_commit_entry($d)->{log},
423 ra => Git::SVN::Ra->new($gs->full_url),
424 tree_a => "$d~1",
425 tree_b => $d,
426 editor_cb => sub {
427 print "Committed r$_[0]\n";
428 $cmt_rev = $_[0];
430 svn_path => '');
431 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
432 print "No changes\n$d~1 == $d\n";
433 } elsif ($parents->{$d} && @{$parents->{$d}}) {
434 $gs->{inject_parents_dcommit}->{$cmt_rev} =
435 $parents->{$d};
437 $_fetch_all ? $gs->fetch_all : $gs->fetch;
438 next if $_no_rebase;
440 # we always want to rebase against the current HEAD,
441 # not any head that was passed to us
442 my @diff = command('diff-tree', 'HEAD',
443 $gs->refname, '--');
444 my @finish;
445 if (@diff) {
446 @finish = rebase_cmd();
447 print STDERR "W: HEAD and ", $gs->refname,
448 " differ, using @finish:\n",
449 "@diff";
450 } else {
451 print "No changes between current HEAD and ",
452 $gs->refname,
453 "\nResetting to the latest ",
454 $gs->refname, "\n";
455 @finish = qw/reset --mixed/;
457 command_noisy(@finish, $gs->refname);
458 $last_rev = $cmt_rev;
463 sub cmd_find_rev {
464 my $revision_or_hash = shift;
465 my $result;
466 if ($revision_or_hash =~ /^r\d+$/) {
467 my $head = shift;
468 $head ||= 'HEAD';
469 my @refs;
470 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
471 unless ($gs) {
472 die "Unable to determine upstream SVN information from ",
473 "$head history\n";
475 my $desired_revision = substr($revision_or_hash, 1);
476 $result = $gs->rev_db_get($desired_revision);
477 } else {
478 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
479 $result = $rev;
481 print "$result\n" if $result;
484 sub cmd_rebase {
485 command_noisy(qw/update-index --refresh/);
486 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
487 unless ($gs) {
488 die "Unable to determine upstream SVN information from ",
489 "working tree history\n";
491 if (command(qw/diff-index HEAD --/)) {
492 print STDERR "Cannot rebase with uncommited changes:\n";
493 command_noisy('status');
494 exit 1;
496 unless ($_local) {
497 $_fetch_all ? $gs->fetch_all : $gs->fetch;
499 command_noisy(rebase_cmd(), $gs->refname);
502 sub cmd_show_ignore {
503 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
504 $gs ||= Git::SVN->new;
505 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
506 $gs->prop_walk($gs->{path}, $r, sub {
507 my ($gs, $path, $props) = @_;
508 print STDOUT "\n# $path\n";
509 my $s = $props->{'svn:ignore'} or return;
510 $s =~ s/[\r\n]+/\n/g;
511 chomp $s;
512 $s =~ s#^#$path#gm;
513 print STDOUT "$s\n";
517 sub cmd_create_ignore {
518 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
519 $gs ||= Git::SVN->new;
520 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
521 $gs->prop_walk($gs->{path}, $r, sub {
522 my ($gs, $path, $props) = @_;
523 # $path is of the form /path/to/dir/
524 my $ignore = '.' . $path . '.gitignore';
525 my $s = $props->{'svn:ignore'} or return;
526 open(GITIGNORE, '>', $ignore)
527 or fatal("Failed to open `$ignore' for writing: $!");
528 $s =~ s/[\r\n]+/\n/g;
529 chomp $s;
530 # Prefix all patterns so that the ignore doesn't apply
531 # to sub-directories.
532 $s =~ s#^#/#gm;
533 print GITIGNORE "$s\n";
534 close(GITIGNORE)
535 or fatal("Failed to close `$ignore': $!");
536 command_noisy('add', $ignore);
540 # get_svnprops(PATH)
541 # ------------------
542 # Helper for cmd_propget and cmd_proplist below.
543 sub get_svnprops {
544 my $path = shift;
545 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
546 $gs ||= Git::SVN->new;
548 # prefix THE PATH by the sub-directory from which the user
549 # invoked us.
550 $path = $cmd_dir_prefix . $path;
551 fatal("No such file or directory: $path") unless -e $path;
552 my $is_dir = -d $path ? 1 : 0;
553 $path = $gs->{path} . '/' . $path;
555 # canonicalize the path (otherwise libsvn will abort or fail to
556 # find the file)
557 # File::Spec->canonpath doesn't collapse x/../y into y (for a
558 # good reason), so let's do this manually.
559 $path =~ s#/+#/#g;
560 $path =~ s#/\.(?:/|$)#/#g;
561 $path =~ s#/[^/]+/\.\.##g;
562 $path =~ s#/$##g;
564 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
565 my $props;
566 if ($is_dir) {
567 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
569 else {
570 (undef, $props) = $gs->ra->get_file($path, $r, undef);
572 return $props;
575 # cmd_propget (PROP, PATH)
576 # ------------------------
577 # Print the SVN property PROP for PATH.
578 sub cmd_propget {
579 my ($prop, $path) = @_;
580 $path = '.' if not defined $path;
581 usage(1) if not defined $prop;
582 my $props = get_svnprops($path);
583 if (not defined $props->{$prop}) {
584 fatal("`$path' does not have a `$prop' SVN property.");
586 print $props->{$prop} . "\n";
589 # cmd_proplist (PATH)
590 # -------------------
591 # Print the list of SVN properties for PATH.
592 sub cmd_proplist {
593 my $path = shift;
594 $path = '.' if not defined $path;
595 my $props = get_svnprops($path);
596 print "Properties on '$path':\n";
597 foreach (sort keys %{$props}) {
598 print " $_\n";
602 sub cmd_multi_init {
603 my $url = shift;
604 unless (defined $_trunk || defined $_branches || defined $_tags) {
605 usage(1);
608 # there are currently some bugs that prevent multi-init/multi-fetch
609 # setups from working well without this.
610 $Git::SVN::_minimize_url = 1;
612 $_prefix = '' unless defined $_prefix;
613 if (defined $url) {
614 $url =~ s#/+$##;
615 init_subdir(@_);
617 do_git_init_db();
618 if (defined $_trunk) {
619 my $trunk_ref = $_prefix . 'trunk';
620 # try both old-style and new-style lookups:
621 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
622 unless ($gs_trunk) {
623 my ($trunk_url, $trunk_path) =
624 complete_svn_url($url, $_trunk);
625 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
626 undef, $trunk_ref);
629 return unless defined $_branches || defined $_tags;
630 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
631 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
632 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
635 sub cmd_multi_fetch {
636 my $remotes = Git::SVN::read_all_remotes();
637 foreach my $repo_id (sort keys %$remotes) {
638 if ($remotes->{$repo_id}->{url}) {
639 Git::SVN::fetch_all($repo_id, $remotes);
644 # this command is special because it requires no metadata
645 sub cmd_commit_diff {
646 my ($ta, $tb, $url) = @_;
647 my $usage = "Usage: $0 commit-diff -r<revision> ".
648 "<tree-ish> <tree-ish> [<URL>]";
649 fatal($usage) if (!defined $ta || !defined $tb);
650 my $svn_path;
651 if (!defined $url) {
652 my $gs = eval { Git::SVN->new };
653 if (!$gs) {
654 fatal("Needed URL or usable git-svn --id in ",
655 "the command-line\n", $usage);
657 $url = $gs->{url};
658 $svn_path = $gs->{path};
660 unless (defined $_revision) {
661 fatal("-r|--revision is a required argument\n", $usage);
663 if (defined $_message && defined $_file) {
664 fatal("Both --message/-m and --file/-F specified ",
665 "for the commit message.\n",
666 "I have no idea what you mean");
668 if (defined $_file) {
669 $_message = file_to_s($_file);
670 } else {
671 $_message ||= get_commit_entry($tb)->{log};
673 my $ra ||= Git::SVN::Ra->new($url);
674 $svn_path ||= $ra->{svn_path};
675 my $r = $_revision;
676 if ($r eq 'HEAD') {
677 $r = $ra->get_latest_revnum;
678 } elsif ($r !~ /^\d+$/) {
679 die "revision argument: $r not understood by git-svn\n";
681 my %ed_opts = ( r => $r,
682 log => $_message,
683 ra => $ra,
684 tree_a => $ta,
685 tree_b => $tb,
686 editor_cb => sub { print "Committed r$_[0]\n" },
687 svn_path => $svn_path );
688 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
689 print "No changes\n$ta == $tb\n";
693 ########################### utility functions #########################
695 sub rebase_cmd {
696 my @cmd = qw/rebase/;
697 push @cmd, '-v' if $_verbose;
698 push @cmd, qw/--merge/ if $_merge;
699 push @cmd, "--strategy=$_strategy" if $_strategy;
700 @cmd;
703 sub post_fetch_checkout {
704 return if $_no_checkout;
705 my $gs = $Git::SVN::_head or return;
706 return if verify_ref('refs/heads/master^0');
708 my $valid_head = verify_ref('HEAD^0');
709 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
710 return if ($valid_head || !verify_ref('HEAD^0'));
712 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
713 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
714 return if -f $index;
716 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
717 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
718 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
719 print STDERR "Checked out HEAD:\n ",
720 $gs->full_url, " r", $gs->last_rev, "\n";
723 sub complete_svn_url {
724 my ($url, $path) = @_;
725 $path =~ s#/+$##;
726 if ($path !~ m#^[a-z\+]+://#) {
727 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
728 fatal("E: '$path' is not a complete URL ",
729 "and a separate URL is not specified");
731 return ($url, $path);
733 return ($path, '');
736 sub complete_url_ls_init {
737 my ($ra, $repo_path, $switch, $pfx) = @_;
738 unless ($repo_path) {
739 print STDERR "W: $switch not specified\n";
740 return;
742 $repo_path =~ s#/+$##;
743 if ($repo_path =~ m#^[a-z\+]+://#) {
744 $ra = Git::SVN::Ra->new($repo_path);
745 $repo_path = '';
746 } else {
747 $repo_path =~ s#^/+##;
748 unless ($ra) {
749 fatal("E: '$repo_path' is not a complete URL ",
750 "and a separate URL is not specified");
753 my $url = $ra->{url};
754 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
755 my $k = "svn-remote.$gs->{repo_id}.url";
756 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
757 if ($orig_url && ($orig_url ne $gs->{url})) {
758 die "$k already set: $orig_url\n",
759 "wanted to set to: $gs->{url}\n";
761 command_oneline('config', $k, $gs->{url}) unless $orig_url;
762 my $remote_path = "$ra->{svn_path}/$repo_path/*";
763 $remote_path =~ s#/+#/#g;
764 $remote_path =~ s#^/##g;
765 my ($n) = ($switch =~ /^--(\w+)/);
766 if (length $pfx && $pfx !~ m#/$#) {
767 die "--prefix='$pfx' must have a trailing slash '/'\n";
769 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
770 "$remote_path:refs/remotes/$pfx*");
773 sub verify_ref {
774 my ($ref) = @_;
775 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
776 { STDERR => 0 }); };
779 sub get_tree_from_treeish {
780 my ($treeish) = @_;
781 # $treeish can be a symbolic ref, too:
782 my $type = command_oneline(qw/cat-file -t/, $treeish);
783 my $expected;
784 while ($type eq 'tag') {
785 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
787 if ($type eq 'commit') {
788 $expected = (grep /^tree /, command(qw/cat-file commit/,
789 $treeish))[0];
790 ($expected) = ($expected =~ /^tree ($sha1)$/o);
791 die "Unable to get tree from $treeish\n" unless $expected;
792 } elsif ($type eq 'tree') {
793 $expected = $treeish;
794 } else {
795 die "$treeish is a $type, expected tree, tag or commit\n";
797 return $expected;
800 sub get_commit_entry {
801 my ($treeish) = shift;
802 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
803 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
804 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
805 open my $log_fh, '>', $commit_editmsg or croak $!;
807 my $type = command_oneline(qw/cat-file -t/, $treeish);
808 if ($type eq 'commit' || $type eq 'tag') {
809 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
810 $type, $treeish);
811 my $in_msg = 0;
812 while (<$msg_fh>) {
813 if (!$in_msg) {
814 $in_msg = 1 if (/^\s*$/);
815 } elsif (/^git-svn-id: /) {
816 # skip this for now, we regenerate the
817 # correct one on re-fetch anyways
818 # TODO: set *:merge properties or like...
819 } else {
820 print $log_fh $_ or croak $!;
823 command_close_pipe($msg_fh, $ctx);
825 close $log_fh or croak $!;
827 if ($_edit || ($type eq 'tree')) {
828 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
829 # TODO: strip out spaces, comments, like git-commit.sh
830 system($editor, $commit_editmsg);
832 rename $commit_editmsg, $commit_msg or croak $!;
833 open $log_fh, '<', $commit_msg or croak $!;
834 { local $/; chomp($log_entry{log} = <$log_fh>); }
835 close $log_fh or croak $!;
836 unlink $commit_msg;
837 \%log_entry;
840 sub s_to_file {
841 my ($str, $file, $mode) = @_;
842 open my $fd,'>',$file or croak $!;
843 print $fd $str,"\n" or croak $!;
844 close $fd or croak $!;
845 chmod ($mode &~ umask, $file) if (defined $mode);
848 sub file_to_s {
849 my $file = shift;
850 open my $fd,'<',$file or croak "$!: file: $file\n";
851 local $/;
852 my $ret = <$fd>;
853 close $fd or croak $!;
854 $ret =~ s/\s*$//s;
855 return $ret;
858 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
859 sub load_authors {
860 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
861 my $log = $cmd eq 'log';
862 while (<$authors>) {
863 chomp;
864 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
865 my ($user, $name, $email) = ($1, $2, $3);
866 if ($log) {
867 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
868 } else {
869 $users{$user} = [$name, $email];
872 close $authors or croak $!;
875 # convert GetOpt::Long specs for use by git-config
876 sub read_repo_config {
877 return unless -d $ENV{GIT_DIR};
878 my $opts = shift;
879 my @config_only;
880 foreach my $o (keys %$opts) {
881 # if we have mixedCase and a long option-only, then
882 # it's a config-only variable that we don't need for
883 # the command-line.
884 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
885 my $v = $opts->{$o};
886 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
887 $key =~ s/-//g;
888 my $arg = 'git-config';
889 $arg .= ' --int' if ($o =~ /[:=]i$/);
890 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
891 if (ref $v eq 'ARRAY') {
892 chomp(my @tmp = `$arg --get-all svn.$key`);
893 @$v = @tmp if @tmp;
894 } else {
895 chomp(my $tmp = `$arg --get svn.$key`);
896 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
897 $$v = $tmp;
901 delete @$opts{@config_only} if @config_only;
904 sub extract_metadata {
905 my $id = shift or return (undef, undef, undef);
906 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
907 \s([a-f\d\-]+)$/x);
908 if (!defined $rev || !$uuid || !$url) {
909 # some of the original repositories I made had
910 # identifiers like this:
911 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
913 return ($url, $rev, $uuid);
916 sub cmt_metadata {
917 return extract_metadata((grep(/^git-svn-id: /,
918 command(qw/cat-file commit/, shift)))[-1]);
921 sub working_head_info {
922 my ($head, $refs) = @_;
923 my @args = ('log', '--no-color', '--first-parent');
924 my ($fh, $ctx) = command_output_pipe(@args, $head);
925 my $hash;
926 my %max;
927 while (<$fh>) {
928 if ( m{^commit ($::sha1)$} ) {
929 unshift @$refs, $hash if $hash and $refs;
930 $hash = $1;
931 next;
933 next unless s{^\s*(git-svn-id:)}{$1};
934 my ($url, $rev, $uuid) = extract_metadata($_);
935 if (defined $url && defined $rev) {
936 next if $max{$url} and $max{$url} < $rev;
937 if (my $gs = Git::SVN->find_by_url($url)) {
938 my $c = $gs->rev_db_get($rev);
939 if ($c && $c eq $hash) {
940 close $fh; # break the pipe
941 return ($url, $rev, $uuid, $gs);
942 } else {
943 $max{$url} ||= $gs->rev_db_max;
948 command_close_pipe($fh, $ctx);
949 (undef, undef, undef, undef);
952 sub read_commit_parents {
953 my ($parents, $c) = @_;
954 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
955 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
956 @{$parents->{$c}} = split(/ /, $p);
959 sub linearize_history {
960 my ($gs, $refs) = @_;
961 my %parents;
962 foreach my $c (@$refs) {
963 read_commit_parents(\%parents, $c);
966 my @linear_refs;
967 my %skip = ();
968 my $last_svn_commit = $gs->last_commit;
969 foreach my $c (reverse @$refs) {
970 next if $c eq $last_svn_commit;
971 last if $skip{$c};
973 unshift @linear_refs, $c;
974 $skip{$c} = 1;
976 # we only want the first parent to diff against for linear
977 # history, we save the rest to inject when we finalize the
978 # svn commit
979 my $fp_a = verify_ref("$c~1");
980 my $fp_b = shift @{$parents{$c}} if $parents{$c};
981 if (!$fp_a || !$fp_b) {
982 die "Commit $c\n",
983 "has no parent commit, and therefore ",
984 "nothing to diff against.\n",
985 "You should be working from a repository ",
986 "originally created by git-svn\n";
988 if ($fp_a ne $fp_b) {
989 die "$c~1 = $fp_a, however parsing commit $c ",
990 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
993 foreach my $p (@{$parents{$c}}) {
994 $skip{$p} = 1;
997 (\@linear_refs, \%parents);
1000 package Git::SVN;
1001 use strict;
1002 use warnings;
1003 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1004 $_repack $_repack_flags $_use_svm_props $_head
1005 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1006 use Carp qw/croak/;
1007 use File::Path qw/mkpath/;
1008 use File::Copy qw/copy/;
1009 use IPC::Open3;
1011 my $_repack_nr;
1012 # properties that we do not log:
1013 my %SKIP_PROP;
1014 BEGIN {
1015 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1016 svn:special svn:executable
1017 svn:entry:committed-rev
1018 svn:entry:last-author
1019 svn:entry:uuid
1020 svn:entry:committed-date/;
1022 # some options are read globally, but can be overridden locally
1023 # per [svn-remote "..."] section. Command-line options will *NOT*
1024 # override options set in an [svn-remote "..."] section
1025 no strict 'refs';
1026 for my $option (qw/follow_parent no_metadata use_svm_props
1027 use_svnsync_props/) {
1028 my $key = $option;
1029 $key =~ tr/_//d;
1030 my $prop = "-$option";
1031 *$option = sub {
1032 my ($self) = @_;
1033 return $self->{$prop} if exists $self->{$prop};
1034 my $k = "svn-remote.$self->{repo_id}.$key";
1035 eval { command_oneline(qw/config --get/, $k) };
1036 if ($@) {
1037 $self->{$prop} = ${"Git::SVN::_$option"};
1038 } else {
1039 my $v = command_oneline(qw/config --bool/,$k);
1040 $self->{$prop} = $v eq 'false' ? 0 : 1;
1042 return $self->{$prop};
1047 my %LOCKFILES;
1048 END { unlink keys %LOCKFILES if %LOCKFILES }
1050 sub resolve_local_globs {
1051 my ($url, $fetch, $glob_spec) = @_;
1052 return unless defined $glob_spec;
1053 my $ref = $glob_spec->{ref};
1054 my $path = $glob_spec->{path};
1055 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1056 next unless m#^refs/remotes/$ref->{regex}$#;
1057 my $p = $1;
1058 my $pathname = desanitize_refname($path->full_path($p));
1059 my $refname = desanitize_refname($ref->full_path($p));
1060 if (my $existing = $fetch->{$pathname}) {
1061 if ($existing ne $refname) {
1062 die "Refspec conflict:\n",
1063 "existing: refs/remotes/$existing\n",
1064 " globbed: refs/remotes/$refname\n";
1066 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1067 $u =~ s!^\Q$url\E(/|$)!! or die
1068 "refs/remotes/$refname: '$url' not found in '$u'\n";
1069 if ($pathname ne $u) {
1070 warn "W: Refspec glob conflict ",
1071 "(ref: refs/remotes/$refname):\n",
1072 "expected path: $pathname\n",
1073 " real path: $u\n",
1074 "Continuing ahead with $u\n";
1075 next;
1077 } else {
1078 $fetch->{$pathname} = $refname;
1083 sub parse_revision_argument {
1084 my ($base, $head) = @_;
1085 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1086 return ($base, $head);
1088 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1089 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1090 return ($head, $head) if ($::_revision eq 'HEAD');
1091 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1092 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1093 die "revision argument: $::_revision not understood by git-svn\n";
1096 sub fetch_all {
1097 my ($repo_id, $remotes) = @_;
1098 if (ref $repo_id) {
1099 my $gs = $repo_id;
1100 $repo_id = undef;
1101 $repo_id = $gs->{repo_id};
1103 $remotes ||= read_all_remotes();
1104 my $remote = $remotes->{$repo_id} or
1105 die "[svn-remote \"$repo_id\"] unknown\n";
1106 my $fetch = $remote->{fetch};
1107 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1108 my (@gs, @globs);
1109 my $ra = Git::SVN::Ra->new($url);
1110 my $uuid = $ra->get_uuid;
1111 my $head = $ra->get_latest_revnum;
1112 my $base = defined $fetch ? $head : 0;
1114 # read the max revs for wildcard expansion (branches/*, tags/*)
1115 foreach my $t (qw/branches tags/) {
1116 defined $remote->{$t} or next;
1117 push @globs, $remote->{$t};
1118 my $max_rev = eval { tmp_config(qw/--int --get/,
1119 "svn-remote.$repo_id.${t}-maxRev") };
1120 if (defined $max_rev && ($max_rev < $base)) {
1121 $base = $max_rev;
1122 } elsif (!defined $max_rev) {
1123 $base = 0;
1127 if ($fetch) {
1128 foreach my $p (sort keys %$fetch) {
1129 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1130 my $lr = $gs->rev_db_max;
1131 if (defined $lr) {
1132 $base = $lr if ($lr < $base);
1134 push @gs, $gs;
1138 ($base, $head) = parse_revision_argument($base, $head);
1139 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1142 sub read_all_remotes {
1143 my $r = {};
1144 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1145 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1146 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1147 $local_ref =~ s{^/}{};
1148 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1149 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1150 $r->{$1}->{url} = $2;
1151 } elsif (m!^(.+)\.(branches|tags)=
1152 (.*):refs/remotes/(.+)\s*$/!x) {
1153 my ($p, $g) = ($3, $4);
1154 my $rs = $r->{$1}->{$2} = {
1155 t => $2,
1156 remote => $1,
1157 path => Git::SVN::GlobSpec->new($p),
1158 ref => Git::SVN::GlobSpec->new($g) };
1159 if (length($rs->{ref}->{right}) != 0) {
1160 die "The '*' glob character must be the last ",
1161 "character of '$g'\n";
1168 sub init_vars {
1169 if (defined $_repack) {
1170 $_repack = 1000 if ($_repack <= 0);
1171 $_repack_nr = $_repack;
1172 $_repack_flags ||= '-d';
1176 sub verify_remotes_sanity {
1177 return unless -d $ENV{GIT_DIR};
1178 my %seen;
1179 foreach (command(qw/config -l/)) {
1180 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1181 if ($seen{$1}) {
1182 die "Remote ref refs/remote/$1 is tracked by",
1183 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1184 "Please resolve this ambiguity in ",
1185 "your git configuration file before ",
1186 "continuing\n";
1188 $seen{$1} = $_;
1193 # we allow more chars than remotes2config.sh...
1194 sub sanitize_remote_name {
1195 my ($name) = @_;
1196 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1197 $name;
1200 sub find_existing_remote {
1201 my ($url, $remotes) = @_;
1202 return undef if $no_reuse_existing;
1203 my $existing;
1204 foreach my $repo_id (keys %$remotes) {
1205 my $u = $remotes->{$repo_id}->{url} or next;
1206 next if $u ne $url;
1207 $existing = $repo_id;
1208 last;
1210 $existing;
1213 sub init_remote_config {
1214 my ($self, $url, $no_write) = @_;
1215 $url =~ s!/+$!!; # strip trailing slash
1216 my $r = read_all_remotes();
1217 my $existing = find_existing_remote($url, $r);
1218 if ($existing) {
1219 unless ($no_write) {
1220 print STDERR "Using existing ",
1221 "[svn-remote \"$existing\"]\n";
1223 $self->{repo_id} = $existing;
1224 } elsif ($_minimize_url) {
1225 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1226 $existing = find_existing_remote($min_url, $r);
1227 if ($existing) {
1228 unless ($no_write) {
1229 print STDERR "Using existing ",
1230 "[svn-remote \"$existing\"]\n";
1232 $self->{repo_id} = $existing;
1234 if ($min_url ne $url) {
1235 unless ($no_write) {
1236 print STDERR "Using higher level of URL: ",
1237 "$url => $min_url\n";
1239 my $old_path = $self->{path};
1240 $self->{path} = $url;
1241 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1242 if (length $old_path) {
1243 $self->{path} .= "/$old_path";
1245 $url = $min_url;
1248 my $orig_url;
1249 if (!$existing) {
1250 # verify that we aren't overwriting anything:
1251 $orig_url = eval {
1252 command_oneline('config', '--get',
1253 "svn-remote.$self->{repo_id}.url")
1255 if ($orig_url && ($orig_url ne $url)) {
1256 die "svn-remote.$self->{repo_id}.url already set: ",
1257 "$orig_url\nwanted to set to: $url\n";
1260 my ($xrepo_id, $xpath) = find_ref($self->refname);
1261 if (defined $xpath) {
1262 die "svn-remote.$xrepo_id.fetch already set to track ",
1263 "$xpath:refs/remotes/", $self->refname, "\n";
1265 unless ($no_write) {
1266 command_noisy('config',
1267 "svn-remote.$self->{repo_id}.url", $url);
1268 $self->{path} =~ s{^/}{};
1269 command_noisy('config', '--add',
1270 "svn-remote.$self->{repo_id}.fetch",
1271 "$self->{path}:".$self->refname);
1273 $self->{url} = $url;
1276 sub find_by_url { # repos_root and, path are optional
1277 my ($class, $full_url, $repos_root, $path) = @_;
1279 return undef unless defined $full_url;
1280 remove_username($full_url);
1281 remove_username($repos_root) if defined $repos_root;
1282 my $remotes = read_all_remotes();
1283 if (defined $full_url && defined $repos_root && !defined $path) {
1284 $path = $full_url;
1285 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1287 foreach my $repo_id (keys %$remotes) {
1288 my $u = $remotes->{$repo_id}->{url} or next;
1289 remove_username($u);
1290 next if defined $repos_root && $repos_root ne $u;
1292 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1293 foreach (qw/branches tags/) {
1294 resolve_local_globs($u, $fetch,
1295 $remotes->{$repo_id}->{$_});
1297 my $p = $path;
1298 unless (defined $p) {
1299 $p = $full_url;
1300 $p =~ s#^\Q$u\E(?:/|$)## or next;
1302 foreach my $f (keys %$fetch) {
1303 next if $f ne $p;
1304 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1307 undef;
1310 sub init {
1311 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1312 my $self = _new($class, $repo_id, $ref_id, $path);
1313 if (defined $url) {
1314 $self->init_remote_config($url, $no_write);
1316 $self;
1319 sub find_ref {
1320 my ($ref_id) = @_;
1321 foreach (command(qw/config -l/)) {
1322 next unless m!^svn-remote\.(.+)\.fetch=
1323 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1324 my ($repo_id, $path, $ref) = ($1, $2, $3);
1325 if ($ref eq $ref_id) {
1326 $path = '' if ($path =~ m#^\./?#);
1327 return ($repo_id, $path);
1330 (undef, undef, undef);
1333 sub new {
1334 my ($class, $ref_id, $repo_id, $path) = @_;
1335 if (defined $ref_id && !defined $repo_id && !defined $path) {
1336 ($repo_id, $path) = find_ref($ref_id);
1337 if (!defined $repo_id) {
1338 die "Could not find a \"svn-remote.*.fetch\" key ",
1339 "in the repository configuration matching: ",
1340 "refs/remotes/$ref_id\n";
1343 my $self = _new($class, $repo_id, $ref_id, $path);
1344 if (!defined $self->{path} || !length $self->{path}) {
1345 my $fetch = command_oneline('config', '--get',
1346 "svn-remote.$repo_id.fetch",
1347 ":refs/remotes/$ref_id\$") or
1348 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1349 "\":refs/remotes/$ref_id\$\" in config\n";
1350 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1352 $self->{url} = command_oneline('config', '--get',
1353 "svn-remote.$repo_id.url") or
1354 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1355 $self->rebuild;
1356 $self;
1359 sub refname {
1360 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1362 # It cannot end with a slash /, we'll throw up on this because
1363 # SVN can't have directories with a slash in their name, either:
1364 if ($refname =~ m{/$}) {
1365 die "ref: '$refname' ends with a trailing slash, this is ",
1366 "not permitted by git nor Subversion\n";
1369 # It cannot have ASCII control character space, tilde ~, caret ^,
1370 # colon :, question-mark ?, asterisk *, space, or open bracket [
1371 # anywhere.
1373 # Additionally, % must be escaped because it is used for escaping
1374 # and we want our escaped refname to be reversible
1375 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1377 # no slash-separated component can begin with a dot .
1378 # /.* becomes /%2E*
1379 $refname =~ s{/\.}{/%2E}g;
1381 # It cannot have two consecutive dots .. anywhere
1382 # .. becomes %2E%2E
1383 $refname =~ s{\.\.}{%2E%2E}g;
1385 return $refname;
1388 sub desanitize_refname {
1389 my ($refname) = @_;
1390 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1391 return $refname;
1394 sub svm_uuid {
1395 my ($self) = @_;
1396 return $self->{svm}->{uuid} if $self->svm;
1397 $self->ra;
1398 unless ($self->{svm}) {
1399 die "SVM UUID not cached, and reading remotely failed\n";
1401 $self->{svm}->{uuid};
1404 sub svm {
1405 my ($self) = @_;
1406 return $self->{svm} if $self->{svm};
1407 my $svm;
1408 # see if we have it in our config, first:
1409 eval {
1410 my $section = "svn-remote.$self->{repo_id}";
1411 $svm = {
1412 source => tmp_config('--get', "$section.svm-source"),
1413 uuid => tmp_config('--get', "$section.svm-uuid"),
1414 replace => tmp_config('--get', "$section.svm-replace"),
1417 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1418 $self->{svm} = $svm;
1420 $self->{svm};
1423 sub _set_svm_vars {
1424 my ($self, $ra) = @_;
1425 return $ra if $self->svm;
1427 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1428 "(svm:source, svm:uuid) ",
1429 "from the following URLs:\n" );
1430 sub read_svm_props {
1431 my ($self, $ra, $path, $r) = @_;
1432 my $props = ($ra->get_dir($path, $r))[2];
1433 my $src = $props->{'svm:source'};
1434 my $uuid = $props->{'svm:uuid'};
1435 return undef if (!$src || !$uuid);
1437 chomp($src, $uuid);
1439 $uuid =~ m{^[0-9a-f\-]{30,}$}
1440 or die "doesn't look right - svm:uuid is '$uuid'\n";
1442 # the '!' is used to mark the repos_root!/relative/path
1443 $src =~ s{/?!/?}{/};
1444 $src =~ s{/+$}{}; # no trailing slashes please
1445 # username is of no interest
1446 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1448 my $replace = $ra->{url};
1449 $replace .= "/$path" if length $path;
1451 my $section = "svn-remote.$self->{repo_id}";
1452 tmp_config("$section.svm-source", $src);
1453 tmp_config("$section.svm-replace", $replace);
1454 tmp_config("$section.svm-uuid", $uuid);
1455 $self->{svm} = {
1456 source => $src,
1457 uuid => $uuid,
1458 replace => $replace
1462 my $r = $ra->get_latest_revnum;
1463 my $path = $self->{path};
1464 my %tried;
1465 while (length $path) {
1466 unless ($tried{"$self->{url}/$path"}) {
1467 return $ra if $self->read_svm_props($ra, $path, $r);
1468 $tried{"$self->{url}/$path"} = 1;
1470 $path =~ s#/?[^/]+$##;
1472 die "Path: '$path' should be ''\n" if $path ne '';
1473 return $ra if $self->read_svm_props($ra, $path, $r);
1474 $tried{"$self->{url}/$path"} = 1;
1476 if ($ra->{repos_root} eq $self->{url}) {
1477 die @err, (map { " $_\n" } keys %tried), "\n";
1480 # nope, make sure we're connected to the repository root:
1481 my $ok;
1482 my @tried_b;
1483 $path = $ra->{svn_path};
1484 $ra = Git::SVN::Ra->new($ra->{repos_root});
1485 while (length $path) {
1486 unless ($tried{"$ra->{url}/$path"}) {
1487 $ok = $self->read_svm_props($ra, $path, $r);
1488 last if $ok;
1489 $tried{"$ra->{url}/$path"} = 1;
1491 $path =~ s#/?[^/]+$##;
1493 die "Path: '$path' should be ''\n" if $path ne '';
1494 $ok ||= $self->read_svm_props($ra, $path, $r);
1495 $tried{"$ra->{url}/$path"} = 1;
1496 if (!$ok) {
1497 die @err, (map { " $_\n" } keys %tried), "\n";
1499 Git::SVN::Ra->new($self->{url});
1502 sub svnsync {
1503 my ($self) = @_;
1504 return $self->{svnsync} if $self->{svnsync};
1506 if ($self->no_metadata) {
1507 die "Can't have both 'noMetadata' and ",
1508 "'useSvnsyncProps' options set!\n";
1510 if ($self->rewrite_root) {
1511 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1512 "options set!\n";
1515 my $svnsync;
1516 # see if we have it in our config, first:
1517 eval {
1518 my $section = "svn-remote.$self->{repo_id}";
1519 $svnsync = {
1520 url => tmp_config('--get', "$section.svnsync-url"),
1521 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1524 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1525 return $self->{svnsync} = $svnsync;
1528 my $err = "useSvnsyncProps set, but failed to read " .
1529 "svnsync property: svn:sync-from-";
1530 my $rp = $self->ra->rev_proplist(0);
1532 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1533 $url =~ m{^[a-z\+]+://} or
1534 die "doesn't look right - svn:sync-from-url is '$url'\n";
1536 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1537 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1538 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1540 my $section = "svn-remote.$self->{repo_id}";
1541 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1542 tmp_config('--add', "$section.svnsync-url", $url);
1543 return $self->{svnsync} = { url => $url, uuid => $uuid };
1546 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1547 # remote lookup (useful for 'git svn log').
1548 sub ra_uuid {
1549 my ($self) = @_;
1550 unless ($self->{ra_uuid}) {
1551 my $key = "svn-remote.$self->{repo_id}.uuid";
1552 my $uuid = eval { tmp_config('--get', $key) };
1553 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1554 $self->{ra_uuid} = $uuid;
1555 } else {
1556 die "ra_uuid called without URL\n" unless $self->{url};
1557 $self->{ra_uuid} = $self->ra->get_uuid;
1558 tmp_config('--add', $key, $self->{ra_uuid});
1561 $self->{ra_uuid};
1564 sub ra {
1565 my ($self) = shift;
1566 my $ra = Git::SVN::Ra->new($self->{url});
1567 if ($self->use_svm_props && !$self->{svm}) {
1568 if ($self->no_metadata) {
1569 die "Can't have both 'noMetadata' and ",
1570 "'useSvmProps' options set!\n";
1571 } elsif ($self->use_svnsync_props) {
1572 die "Can't have both 'useSvnsyncProps' and ",
1573 "'useSvmProps' options set!\n";
1575 $ra = $self->_set_svm_vars($ra);
1576 $self->{-want_revprops} = 1;
1578 $ra;
1581 sub rel_path {
1582 my ($self) = @_;
1583 my $repos_root = $self->ra->{repos_root};
1584 return $self->{path} if ($self->{url} eq $repos_root);
1585 my $url = $self->{url} .
1586 (length $self->{path} ? "/$self->{path}" : $self->{path});
1587 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1588 $url;
1591 # prop_walk(PATH, REV, SUB)
1592 # -------------------------
1593 # Recursively traverse PATH at revision REV and invoke SUB for each
1594 # directory that contains a SVN property. SUB will be invoked as
1595 # follows: &SUB(gs, path, props); where `gs' is this instance of
1596 # Git::SVN, `path' the path to the directory where the properties
1597 # `props' were found. The `path' will be relative to point of checkout,
1598 # that is, if url://repo/trunk is the current Git branch, and that
1599 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1600 # as `path' (note the trailing `/').
1601 sub prop_walk {
1602 my ($self, $path, $rev, $sub) = @_;
1604 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1605 $path =~ s#^/*#/#g;
1606 my $p = $path;
1607 # Strip the irrelevant part of the path.
1608 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1609 # Ensure the path is terminated by a `/'.
1610 $p =~ s#/*$#/#;
1612 # The properties contain all the internal SVN stuff nobody
1613 # (usually) cares about.
1614 my $interesting_props = 0;
1615 foreach (keys %{$props}) {
1616 # If it doesn't start with `svn:', it must be a
1617 # user-defined property.
1618 ++$interesting_props and next if $_ !~ /^svn:/;
1619 # FIXME: Fragile, if SVN adds new public properties,
1620 # this needs to be updated.
1621 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1622 |eol-style|mime-type
1623 |externals|needs-lock)$/x;
1625 &$sub($self, $p, $props) if $interesting_props;
1627 foreach (sort keys %$dirent) {
1628 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1629 $self->prop_walk($path . '/' . $_, $rev, $sub);
1633 sub last_rev { ($_[0]->last_rev_commit)[0] }
1634 sub last_commit { ($_[0]->last_rev_commit)[1] }
1636 # returns the newest SVN revision number and newest commit SHA1
1637 sub last_rev_commit {
1638 my ($self) = @_;
1639 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1640 return ($self->{last_rev}, $self->{last_commit});
1642 my $c = ::verify_ref($self->refname.'^0');
1643 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1644 my $rev = (::cmt_metadata($c))[1];
1645 if (defined $rev) {
1646 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1647 return ($rev, $c);
1650 my $db_path = $self->db_path;
1651 unless (-e $db_path) {
1652 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1653 return (undef, undef);
1655 my $offset = -41; # from tail
1656 my $rl;
1657 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1658 sysseek($fh, $offset, 2); # don't care for errors
1659 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1660 chomp $rl;
1661 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1662 $offset -= 41;
1663 sysseek($fh, $offset, 2); # don't care for errors
1664 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1665 chomp $rl;
1667 if ($c && $c ne $rl) {
1668 die "$db_path and ", $self->refname,
1669 " inconsistent!:\n$c != $rl\n";
1671 my $rev = sysseek($fh, 0, 1) or croak $!;
1672 $rev = ($rev - 41) / 41;
1673 close $fh or croak $!;
1674 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1675 return ($rev, $c);
1678 sub get_fetch_range {
1679 my ($self, $min, $max) = @_;
1680 $max ||= $self->ra->get_latest_revnum;
1681 $min ||= $self->rev_db_max;
1682 (++$min, $max);
1685 sub tmp_config {
1686 my (@args) = @_;
1687 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1688 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1689 if (! -f $config && -f $old_def_config) {
1690 rename $old_def_config, $config or
1691 die "Failed rename $old_def_config => $config: $!\n";
1693 my $old_config = $ENV{GIT_CONFIG};
1694 $ENV{GIT_CONFIG} = $config;
1695 $@ = undef;
1696 my @ret = eval {
1697 unless (-f $config) {
1698 mkfile($config);
1699 open my $fh, '>', $config or
1700 die "Can't open $config: $!\n";
1701 print $fh "; This file is used internally by ",
1702 "git-svn\n" or die
1703 "Couldn't write to $config: $!\n";
1704 print $fh "; You should not have to edit it\n" or
1705 die "Couldn't write to $config: $!\n";
1706 close $fh or die "Couldn't close $config: $!\n";
1708 command('config', @args);
1710 my $err = $@;
1711 if (defined $old_config) {
1712 $ENV{GIT_CONFIG} = $old_config;
1713 } else {
1714 delete $ENV{GIT_CONFIG};
1716 die $err if $err;
1717 wantarray ? @ret : $ret[0];
1720 sub tmp_index_do {
1721 my ($self, $sub) = @_;
1722 my $old_index = $ENV{GIT_INDEX_FILE};
1723 $ENV{GIT_INDEX_FILE} = $self->{index};
1724 $@ = undef;
1725 my @ret = eval {
1726 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1727 mkpath([$dir]) unless -d $dir;
1728 &$sub;
1730 my $err = $@;
1731 if (defined $old_index) {
1732 $ENV{GIT_INDEX_FILE} = $old_index;
1733 } else {
1734 delete $ENV{GIT_INDEX_FILE};
1736 die $err if $err;
1737 wantarray ? @ret : $ret[0];
1740 sub assert_index_clean {
1741 my ($self, $treeish) = @_;
1743 $self->tmp_index_do(sub {
1744 command_noisy('read-tree', $treeish) unless -e $self->{index};
1745 my $x = command_oneline('write-tree');
1746 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1747 /^tree ($::sha1)/mo);
1748 return if $y eq $x;
1750 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1751 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1752 command_noisy('read-tree', $treeish);
1753 $x = command_oneline('write-tree');
1754 if ($y ne $x) {
1755 ::fatal "trees ($treeish) $y != $x\n",
1756 "Something is seriously wrong...";
1761 sub get_commit_parents {
1762 my ($self, $log_entry) = @_;
1763 my (%seen, @ret, @tmp);
1764 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1765 if (my $ip = $self->{inject_parents}) {
1766 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1767 push @tmp, $commit;
1770 if (my $cur = ::verify_ref($self->refname.'^0')) {
1771 push @tmp, $cur;
1773 if (my $ipd = $self->{inject_parents_dcommit}) {
1774 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1775 push @tmp, @$commit;
1778 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1779 while (my $p = shift @tmp) {
1780 next if $seen{$p};
1781 $seen{$p} = 1;
1782 push @ret, $p;
1783 # MAXPARENT is defined to 16 in commit-tree.c:
1784 last if @ret >= 16;
1786 if (@tmp) {
1787 die "r$log_entry->{revision}: No room for parents:\n\t",
1788 join("\n\t", @tmp), "\n";
1790 @ret;
1793 sub rewrite_root {
1794 my ($self) = @_;
1795 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1796 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1797 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1798 if ($rwr) {
1799 $rwr =~ s#/+$##;
1800 if ($rwr !~ m#^[a-z\+]+://#) {
1801 die "$rwr is not a valid URL (key: $k)\n";
1804 $self->{-rewrite_root} = $rwr;
1807 sub metadata_url {
1808 my ($self) = @_;
1809 ($self->rewrite_root || $self->{url}) .
1810 (length $self->{path} ? '/' . $self->{path} : '');
1813 sub full_url {
1814 my ($self) = @_;
1815 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1818 sub do_git_commit {
1819 my ($self, $log_entry) = @_;
1820 my $lr = $self->last_rev;
1821 if (defined $lr && $lr >= $log_entry->{revision}) {
1822 die "Last fetched revision of ", $self->refname,
1823 " was r$lr, but we are about to fetch: ",
1824 "r$log_entry->{revision}!\n";
1826 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1827 croak "$log_entry->{revision} = $c already exists! ",
1828 "Why are we refetching it?\n";
1830 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1831 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1832 $log_entry->{email};
1833 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1835 my $tree = $log_entry->{tree};
1836 if (!defined $tree) {
1837 $tree = $self->tmp_index_do(sub {
1838 command_oneline('write-tree') });
1840 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1842 my @exec = ('git-commit-tree', $tree);
1843 foreach ($self->get_commit_parents($log_entry)) {
1844 push @exec, '-p', $_;
1846 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1847 or croak $!;
1848 print $msg_fh $log_entry->{log} or croak $!;
1849 unless ($self->no_metadata) {
1850 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1851 or croak $!;
1853 $msg_fh->flush == 0 or croak $!;
1854 close $msg_fh or croak $!;
1855 chomp(my $commit = do { local $/; <$out_fh> });
1856 close $out_fh or croak $!;
1857 waitpid $pid, 0;
1858 croak $? if $?;
1859 if ($commit !~ /^$::sha1$/o) {
1860 die "Failed to commit, invalid sha1: $commit\n";
1863 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1865 $self->{last_rev} = $log_entry->{revision};
1866 $self->{last_commit} = $commit;
1867 print "r$log_entry->{revision}";
1868 if (defined $log_entry->{svm_revision}) {
1869 print " (\@$log_entry->{svm_revision})";
1870 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1871 0, $self->svm_uuid);
1873 print " = $commit ($self->{ref_id})\n";
1874 if (defined $_repack && (--$_repack_nr == 0)) {
1875 $_repack_nr = $_repack;
1876 # repack doesn't use any arguments with spaces in them, does it?
1877 print "Running git repack $_repack_flags ...\n";
1878 command_noisy('repack', split(/\s+/, $_repack_flags));
1879 print "Done repacking\n";
1881 return $commit;
1884 sub match_paths {
1885 my ($self, $paths, $r) = @_;
1886 return 1 if $self->{path} eq '';
1887 if (my $path = $paths->{"/$self->{path}"}) {
1888 return ($path->{action} eq 'D') ? 0 : 1;
1890 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1891 if (grep /$self->{path_regex}/, keys %$paths) {
1892 return 1;
1894 my $c = '';
1895 foreach (split m#/#, $self->{path}) {
1896 $c .= "/$_";
1897 next unless ($paths->{$c} &&
1898 ($paths->{$c}->{action} =~ /^[AR]$/));
1899 if ($self->ra->check_path($self->{path}, $r) ==
1900 $SVN::Node::dir) {
1901 return 1;
1904 return 0;
1907 sub find_parent_branch {
1908 my ($self, $paths, $rev) = @_;
1909 return undef unless $self->follow_parent;
1910 unless (defined $paths) {
1911 my $err_handler = $SVN::Error::handler;
1912 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1913 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1914 $paths =
1915 Git::SVN::Ra::dup_changed_paths($_[0]) });
1916 $SVN::Error::handler = $err_handler;
1918 return undef unless defined $paths;
1920 # look for a parent from another branch:
1921 my @b_path_components = split m#/#, $self->rel_path;
1922 my @a_path_components;
1923 my $i;
1924 while (@b_path_components) {
1925 $i = $paths->{'/'.join('/', @b_path_components)};
1926 last if $i && defined $i->{copyfrom_path};
1927 unshift(@a_path_components, pop(@b_path_components));
1929 return undef unless defined $i && defined $i->{copyfrom_path};
1930 my $branch_from = $i->{copyfrom_path};
1931 if (@a_path_components) {
1932 print STDERR "branch_from: $branch_from => ";
1933 $branch_from .= '/'.join('/', @a_path_components);
1934 print STDERR $branch_from, "\n";
1936 my $r = $i->{copyfrom_rev};
1937 my $repos_root = $self->ra->{repos_root};
1938 my $url = $self->ra->{url};
1939 my $new_url = $repos_root . $branch_from;
1940 print STDERR "Found possible branch point: ",
1941 "$new_url => ", $self->full_url, ", $r\n";
1942 $branch_from =~ s#^/##;
1943 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1944 unless ($gs) {
1945 my $ref_id = $self->{ref_id};
1946 $ref_id =~ s/\@\d+$//;
1947 $ref_id .= "\@$r";
1948 # just grow a tail if we're not unique enough :x
1949 $ref_id .= '-' while find_ref($ref_id);
1950 print STDERR "Initializing parent: $ref_id\n";
1951 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1953 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1954 if (!defined $r0 || !defined $parent) {
1955 my ($base, $head) = parse_revision_argument(0, $r);
1956 if ($base <= $r) {
1957 $gs->fetch($base, $r);
1959 ($r0, $parent) = $gs->last_rev_commit;
1961 if (defined $r0 && defined $parent) {
1962 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1963 my $ed;
1964 if ($self->ra->can_do_switch) {
1965 $self->assert_index_clean($parent);
1966 print STDERR "Following parent with do_switch\n";
1967 # do_switch works with svn/trunk >= r22312, but that
1968 # is not included with SVN 1.4.3 (the latest version
1969 # at the moment), so we can't rely on it
1970 $self->{last_commit} = $parent;
1971 $ed = SVN::Git::Fetcher->new($self);
1972 $gs->ra->gs_do_switch($r0, $rev, $gs,
1973 $self->full_url, $ed)
1974 or die "SVN connection failed somewhere...\n";
1975 } elsif ($self->ra->trees_match($new_url, $r0,
1976 $self->full_url, $rev)) {
1977 print STDERR "Trees match:\n",
1978 " $new_url\@$r0\n",
1979 " ${\$self->full_url}\@$rev\n",
1980 "Following parent with no changes\n";
1981 $self->tmp_index_do(sub {
1982 command_noisy('read-tree', $parent);
1984 $self->{last_commit} = $parent;
1985 } else {
1986 print STDERR "Following parent with do_update\n";
1987 $ed = SVN::Git::Fetcher->new($self);
1988 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1989 or die "SVN connection failed somewhere...\n";
1991 print STDERR "Successfully followed parent\n";
1992 return $self->make_log_entry($rev, [$parent], $ed);
1994 return undef;
1997 sub do_fetch {
1998 my ($self, $paths, $rev) = @_;
1999 my $ed;
2000 my ($last_rev, @parents);
2001 if (my $lc = $self->last_commit) {
2002 # we can have a branch that was deleted, then re-added
2003 # under the same name but copied from another path, in
2004 # which case we'll have multiple parents (we don't
2005 # want to break the original ref, nor lose copypath info):
2006 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2007 push @{$log_entry->{parents}}, $lc;
2008 return $log_entry;
2010 $ed = SVN::Git::Fetcher->new($self);
2011 $last_rev = $self->{last_rev};
2012 $ed->{c} = $lc;
2013 @parents = ($lc);
2014 } else {
2015 $last_rev = $rev;
2016 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2017 return $log_entry;
2019 $ed = SVN::Git::Fetcher->new($self);
2021 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2022 die "SVN connection failed somewhere...\n";
2024 $self->make_log_entry($rev, \@parents, $ed);
2027 sub get_untracked {
2028 my ($self, $ed) = @_;
2029 my @out;
2030 my $h = $ed->{empty};
2031 foreach (sort keys %$h) {
2032 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2033 push @out, " $act: " . uri_encode($_);
2034 warn "W: $act: $_\n";
2036 foreach my $t (qw/dir_prop file_prop/) {
2037 $h = $ed->{$t} or next;
2038 foreach my $path (sort keys %$h) {
2039 my $ppath = $path eq '' ? '.' : $path;
2040 foreach my $prop (sort keys %{$h->{$path}}) {
2041 next if $SKIP_PROP{$prop};
2042 my $v = $h->{$path}->{$prop};
2043 my $t_ppath_prop = "$t: " .
2044 uri_encode($ppath) . ' ' .
2045 uri_encode($prop);
2046 if (defined $v) {
2047 push @out, " +$t_ppath_prop " .
2048 uri_encode($v);
2049 } else {
2050 push @out, " -$t_ppath_prop";
2055 foreach my $t (qw/absent_file absent_directory/) {
2056 $h = $ed->{$t} or next;
2057 foreach my $parent (sort keys %$h) {
2058 foreach my $path (sort @{$h->{$parent}}) {
2059 push @out, " $t: " .
2060 uri_encode("$parent/$path");
2061 warn "W: $t: $parent/$path ",
2062 "Insufficient permissions?\n";
2066 \@out;
2069 sub parse_svn_date {
2070 my $date = shift || return '+0000 1970-01-01 00:00:00';
2071 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2072 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2073 croak "Unable to parse date: $date\n";
2074 "+0000 $Y-$m-$d $H:$M:$S";
2077 sub check_author {
2078 my ($author) = @_;
2079 if (!defined $author || length $author == 0) {
2080 $author = '(no author)';
2082 if (defined $::_authors && ! defined $::users{$author}) {
2083 die "Author: $author not defined in $::_authors file\n";
2085 $author;
2088 sub make_log_entry {
2089 my ($self, $rev, $parents, $ed) = @_;
2090 my $untracked = $self->get_untracked($ed);
2092 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2093 print $un "r$rev\n" or croak $!;
2094 print $un $_, "\n" foreach @$untracked;
2095 my %log_entry = ( parents => $parents || [], revision => $rev,
2096 log => '');
2098 my $headrev;
2099 my $logged = delete $self->{logged_rev_props};
2100 if (!$logged || $self->{-want_revprops}) {
2101 my $rp = $self->ra->rev_proplist($rev);
2102 foreach (sort keys %$rp) {
2103 my $v = $rp->{$_};
2104 if (/^svn:(author|date|log)$/) {
2105 $log_entry{$1} = $v;
2106 } elsif ($_ eq 'svm:headrev') {
2107 $headrev = $v;
2108 } else {
2109 print $un " rev_prop: ", uri_encode($_), ' ',
2110 uri_encode($v), "\n";
2113 } else {
2114 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2116 close $un or croak $!;
2118 $log_entry{date} = parse_svn_date($log_entry{date});
2119 $log_entry{log} .= "\n";
2120 my $author = $log_entry{author} = check_author($log_entry{author});
2121 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2122 : ($author, undef);
2123 if (defined $headrev && $self->use_svm_props) {
2124 if ($self->rewrite_root) {
2125 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2126 "options set!\n";
2128 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2129 # we don't want "SVM: initializing mirror for junk" ...
2130 return undef if $r == 0;
2131 my $svm = $self->svm;
2132 if ($uuid ne $svm->{uuid}) {
2133 die "UUID mismatch on SVM path:\n",
2134 "expected: $svm->{uuid}\n",
2135 " got: $uuid\n";
2137 my $full_url = $self->full_url;
2138 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2139 die "Failed to replace '$svm->{replace}' with ",
2140 "'$svm->{source}' in $full_url\n";
2141 # throw away username for storing in records
2142 remove_username($full_url);
2143 $log_entry{metadata} = "$full_url\@$r $uuid";
2144 $log_entry{svm_revision} = $r;
2145 $email ||= "$author\@$uuid"
2146 } elsif ($self->use_svnsync_props) {
2147 my $full_url = $self->svnsync->{url};
2148 $full_url .= "/$self->{path}" if length $self->{path};
2149 remove_username($full_url);
2150 my $uuid = $self->svnsync->{uuid};
2151 $log_entry{metadata} = "$full_url\@$rev $uuid";
2152 $email ||= "$author\@$uuid"
2153 } else {
2154 my $url = $self->metadata_url;
2155 remove_username($url);
2156 $log_entry{metadata} = "$url\@$rev " .
2157 $self->ra->get_uuid;
2158 $email ||= "$author\@" . $self->ra->get_uuid;
2160 $log_entry{name} = $name;
2161 $log_entry{email} = $email;
2162 \%log_entry;
2165 sub fetch {
2166 my ($self, $min_rev, $max_rev, @parents) = @_;
2167 my ($last_rev, $last_commit) = $self->last_rev_commit;
2168 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2169 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2172 sub set_tree_cb {
2173 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2174 $self->{inject_parents} = { $rev => $tree };
2175 $self->fetch(undef, undef);
2178 sub set_tree {
2179 my ($self, $tree) = (shift, shift);
2180 my $log_entry = ::get_commit_entry($tree);
2181 unless ($self->{last_rev}) {
2182 fatal("Must have an existing revision to commit");
2184 my %ed_opts = ( r => $self->{last_rev},
2185 log => $log_entry->{log},
2186 ra => $self->ra,
2187 tree_a => $self->{last_commit},
2188 tree_b => $tree,
2189 editor_cb => sub {
2190 $self->set_tree_cb($log_entry, $tree, @_) },
2191 svn_path => $self->{path} );
2192 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2193 print "No changes\nr$self->{last_rev} = $tree\n";
2197 sub rebuild {
2198 my ($self) = @_;
2199 my $db_path = $self->db_path;
2200 return if (-e $db_path && ! -z $db_path);
2201 return unless ::verify_ref($self->refname.'^0');
2202 if (-f $self->{db_root}) {
2203 rename $self->{db_root}, $db_path or die
2204 "rename $self->{db_root} => $db_path failed: $!\n";
2205 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2206 symlink $base, $self->{db_root} or die
2207 "symlink $base => $self->{db_root} failed: $!\n";
2208 return;
2210 print "Rebuilding $db_path ...\n";
2211 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2212 my $latest;
2213 my $full_url = $self->full_url;
2214 remove_username($full_url);
2215 my $svn_uuid;
2216 my $c;
2217 while (<$log>) {
2218 if ( m{^commit ($::sha1)$} ) {
2219 $c = $1;
2220 next;
2222 next unless s{^\s*(git-svn-id:)}{$1};
2223 my ($url, $rev, $uuid) = ::extract_metadata($_);
2224 remove_username($url);
2226 # ignore merges (from set-tree)
2227 next if (!defined $rev || !$uuid);
2229 # if we merged or otherwise started elsewhere, this is
2230 # how we break out of it
2231 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2232 ($full_url && $url && ($url ne $full_url))) {
2233 next;
2235 $latest ||= $rev;
2236 $svn_uuid ||= $uuid;
2238 $self->rev_db_set($rev, $c);
2239 print "r$rev = $c\n";
2241 command_close_pipe($log, $ctx);
2242 print "Done rebuilding $db_path\n";
2245 # rev_db:
2246 # Tie::File seems to be prone to offset errors if revisions get sparse,
2247 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2248 # one of my favorite modules is out :< Next up would be one of the DBM
2249 # modules, but I'm not sure which is most portable... So I'll just
2250 # go with something that's plain-text, but still capable of
2251 # being randomly accessed. So here's my ultra-simple fixed-width
2252 # database. All records are 40 characters + "\n", so it's easy to seek
2253 # to a revision: (41 * rev) is the byte offset.
2254 # A record of 40 0s denotes an empty revision.
2255 # And yes, it's still pretty fast (faster than Tie::File).
2256 # These files are disposable unless noMetadata or useSvmProps is set
2258 sub _rev_db_set {
2259 my ($fh, $rev, $commit) = @_;
2260 my $offset = $rev * 41;
2261 # assume that append is the common case:
2262 seek $fh, 0, 2 or croak $!;
2263 my $pos = tell $fh;
2264 if ($pos < $offset) {
2265 for (1 .. (($offset - $pos) / 41)) {
2266 print $fh (('0' x 40),"\n") or croak $!;
2269 seek $fh, $offset, 0 or croak $!;
2270 print $fh $commit,"\n" or croak $!;
2273 sub mkfile {
2274 my ($path) = @_;
2275 unless (-e $path) {
2276 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2277 mkpath([$dir]) unless -d $dir;
2278 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2279 close $fh or die "Couldn't close (create) $path: $!\n";
2283 sub rev_db_set {
2284 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2285 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2286 my $db = $self->db_path($uuid);
2287 my $db_lock = "$db.lock";
2288 my $sig;
2289 if ($update_ref) {
2290 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2291 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2293 mkfile($db);
2295 $LOCKFILES{$db_lock} = 1;
2296 my $sync;
2297 # both of these options make our .rev_db file very, very important
2298 # and we can't afford to lose it because rebuild() won't work
2299 if ($self->use_svm_props || $self->no_metadata) {
2300 $sync = 1;
2301 copy($db, $db_lock) or die "rev_db_set(@_): ",
2302 "Failed to copy: ",
2303 "$db => $db_lock ($!)\n";
2304 } else {
2305 rename $db, $db_lock or die "rev_db_set(@_): ",
2306 "Failed to rename: ",
2307 "$db => $db_lock ($!)\n";
2309 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2310 _rev_db_set($fh, $rev, $commit);
2311 if ($sync) {
2312 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2313 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2315 close $fh or croak $!;
2316 if ($update_ref) {
2317 $_head = $self;
2318 command_noisy('update-ref', '-m', "r$rev",
2319 $self->refname, $commit);
2321 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2322 "$db_lock => $db ($!)\n";
2323 delete $LOCKFILES{$db_lock};
2324 if ($update_ref) {
2325 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2326 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2327 kill $sig, $$ if defined $sig;
2331 sub rev_db_max {
2332 my ($self) = @_;
2333 $self->rebuild;
2334 my $db_path = $self->db_path;
2335 my @stat = stat $db_path or return 0;
2336 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2337 my $max = $stat[7] / 41;
2338 (($max > 0) ? $max - 1 : 0);
2341 sub rev_db_get {
2342 my ($self, $rev, $uuid) = @_;
2343 my $ret;
2344 my $offset = $rev * 41;
2345 my $db_path = $self->db_path($uuid);
2346 return undef unless -e $db_path;
2347 open my $fh, '<', $db_path or croak $!;
2348 if (sysseek($fh, $offset, 0) == $offset) {
2349 my $read = sysread($fh, $ret, 40);
2350 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2352 close $fh or croak $!;
2353 $ret;
2356 sub find_rev_before {
2357 my ($self, $rev, $eq_ok) = @_;
2358 --$rev unless $eq_ok;
2359 while ($rev > 0) {
2360 if (my $c = $self->rev_db_get($rev)) {
2361 return ($rev, $c);
2363 --$rev;
2365 return (undef, undef);
2368 sub _new {
2369 my ($class, $repo_id, $ref_id, $path) = @_;
2370 unless (defined $repo_id && length $repo_id) {
2371 $repo_id = $Git::SVN::default_repo_id;
2373 unless (defined $ref_id && length $ref_id) {
2374 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2376 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2377 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2378 $_[3] = $path = '' unless (defined $path);
2379 mkpath(["$ENV{GIT_DIR}/svn"]);
2380 bless {
2381 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2382 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2383 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2386 sub db_path {
2387 my ($self, $uuid) = @_;
2388 $uuid ||= $self->ra_uuid;
2389 "$self->{db_root}.$uuid";
2392 sub uri_encode {
2393 my ($f) = @_;
2394 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2398 sub remove_username {
2399 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2402 package Git::SVN::Prompt;
2403 use strict;
2404 use warnings;
2405 require SVN::Core;
2406 use vars qw/$_no_auth_cache $_username/;
2408 sub simple {
2409 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2410 $may_save = undef if $_no_auth_cache;
2411 $default_username = $_username if defined $_username;
2412 if (defined $default_username && length $default_username) {
2413 if (defined $realm && length $realm) {
2414 print STDERR "Authentication realm: $realm\n";
2415 STDERR->flush;
2417 $cred->username($default_username);
2418 } else {
2419 username($cred, $realm, $may_save, $pool);
2421 $cred->password(_read_password("Password for '" .
2422 $cred->username . "': ", $realm));
2423 $cred->may_save($may_save);
2424 $SVN::_Core::SVN_NO_ERROR;
2427 sub ssl_server_trust {
2428 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2429 $may_save = undef if $_no_auth_cache;
2430 print STDERR "Error validating server certificate for '$realm':\n";
2432 no warnings 'once';
2433 # All variables SVN::Auth::SSL::* are used only once,
2434 # so we're shutting up Perl warnings about this.
2435 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2436 print STDERR " - The certificate is not issued ",
2437 "by a trusted authority. Use the\n",
2438 " fingerprint to validate ",
2439 "the certificate manually!\n";
2441 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2442 print STDERR " - The certificate hostname ",
2443 "does not match.\n";
2445 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2446 print STDERR " - The certificate is not yet valid.\n";
2448 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2449 print STDERR " - The certificate has expired.\n";
2451 if ($failures & $SVN::Auth::SSL::OTHER) {
2452 print STDERR " - The certificate has ",
2453 "an unknown error.\n";
2455 } # no warnings 'once'
2456 printf STDERR
2457 "Certificate information:\n".
2458 " - Hostname: %s\n".
2459 " - Valid: from %s until %s\n".
2460 " - Issuer: %s\n".
2461 " - Fingerprint: %s\n",
2462 map $cert_info->$_, qw(hostname valid_from valid_until
2463 issuer_dname fingerprint);
2464 my $choice;
2465 prompt:
2466 print STDERR $may_save ?
2467 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2468 "(R)eject or accept (t)emporarily? ";
2469 STDERR->flush;
2470 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2471 if ($choice =~ /^t$/i) {
2472 $cred->may_save(undef);
2473 } elsif ($choice =~ /^r$/i) {
2474 return -1;
2475 } elsif ($may_save && $choice =~ /^p$/i) {
2476 $cred->may_save($may_save);
2477 } else {
2478 goto prompt;
2480 $cred->accepted_failures($failures);
2481 $SVN::_Core::SVN_NO_ERROR;
2484 sub ssl_client_cert {
2485 my ($cred, $realm, $may_save, $pool) = @_;
2486 $may_save = undef if $_no_auth_cache;
2487 print STDERR "Client certificate filename: ";
2488 STDERR->flush;
2489 chomp(my $filename = <STDIN>);
2490 $cred->cert_file($filename);
2491 $cred->may_save($may_save);
2492 $SVN::_Core::SVN_NO_ERROR;
2495 sub ssl_client_cert_pw {
2496 my ($cred, $realm, $may_save, $pool) = @_;
2497 $may_save = undef if $_no_auth_cache;
2498 $cred->password(_read_password("Password: ", $realm));
2499 $cred->may_save($may_save);
2500 $SVN::_Core::SVN_NO_ERROR;
2503 sub username {
2504 my ($cred, $realm, $may_save, $pool) = @_;
2505 $may_save = undef if $_no_auth_cache;
2506 if (defined $realm && length $realm) {
2507 print STDERR "Authentication realm: $realm\n";
2509 my $username;
2510 if (defined $_username) {
2511 $username = $_username;
2512 } else {
2513 print STDERR "Username: ";
2514 STDERR->flush;
2515 chomp($username = <STDIN>);
2517 $cred->username($username);
2518 $cred->may_save($may_save);
2519 $SVN::_Core::SVN_NO_ERROR;
2522 sub _read_password {
2523 my ($prompt, $realm) = @_;
2524 print STDERR $prompt;
2525 STDERR->flush;
2526 require Term::ReadKey;
2527 Term::ReadKey::ReadMode('noecho');
2528 my $password = '';
2529 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2530 last if $key =~ /[\012\015]/; # \n\r
2531 $password .= $key;
2533 Term::ReadKey::ReadMode('restore');
2534 print STDERR "\n";
2535 STDERR->flush;
2536 $password;
2539 package SVN::Git::Fetcher;
2540 use vars qw/@ISA/;
2541 use strict;
2542 use warnings;
2543 use Carp qw/croak/;
2544 use IO::File qw//;
2545 use Digest::MD5;
2547 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2548 sub new {
2549 my ($class, $git_svn) = @_;
2550 my $self = SVN::Delta::Editor->new;
2551 bless $self, $class;
2552 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2553 $self->{empty} = {};
2554 $self->{dir_prop} = {};
2555 $self->{file_prop} = {};
2556 $self->{absent_dir} = {};
2557 $self->{absent_file} = {};
2558 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2559 $self;
2562 sub set_path_strip {
2563 my ($self, $path) = @_;
2564 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2567 sub open_root {
2568 { path => '' };
2571 sub open_directory {
2572 my ($self, $path, $pb, $rev) = @_;
2573 { path => $path };
2576 sub git_path {
2577 my ($self, $path) = @_;
2578 if ($self->{path_strip}) {
2579 $path =~ s!$self->{path_strip}!! or
2580 die "Failed to strip path '$path' ($self->{path_strip})\n";
2582 $path;
2585 sub delete_entry {
2586 my ($self, $path, $rev, $pb) = @_;
2588 my $gpath = $self->git_path($path);
2589 return undef if ($gpath eq '');
2591 # remove entire directories.
2592 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2593 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2594 -r --name-only -z/,
2595 $self->{c}, '--', $gpath);
2596 local $/ = "\0";
2597 while (<$ls>) {
2598 chomp;
2599 $self->{gii}->remove($_);
2600 print "\tD\t$_\n" unless $::_q;
2602 print "\tD\t$gpath/\n" unless $::_q;
2603 command_close_pipe($ls, $ctx);
2604 $self->{empty}->{$path} = 0
2605 } else {
2606 $self->{gii}->remove($gpath);
2607 print "\tD\t$gpath\n" unless $::_q;
2609 undef;
2612 sub open_file {
2613 my ($self, $path, $pb, $rev) = @_;
2614 my $gpath = $self->git_path($path);
2615 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2616 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2617 unless (defined $mode && defined $blob) {
2618 die "$path was not found in commit $self->{c} (r$rev)\n";
2620 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2621 pool => SVN::Pool->new, action => 'M' };
2624 sub add_file {
2625 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2626 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2627 delete $self->{empty}->{$dir};
2628 { path => $path, mode_a => 100644, mode_b => 100644,
2629 pool => SVN::Pool->new, action => 'A' };
2632 sub add_directory {
2633 my ($self, $path, $cp_path, $cp_rev) = @_;
2634 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2635 delete $self->{empty}->{$dir};
2636 $self->{empty}->{$path} = 1;
2637 { path => $path };
2640 sub change_dir_prop {
2641 my ($self, $db, $prop, $value) = @_;
2642 $self->{dir_prop}->{$db->{path}} ||= {};
2643 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2644 undef;
2647 sub absent_directory {
2648 my ($self, $path, $pb) = @_;
2649 $self->{absent_dir}->{$pb->{path}} ||= [];
2650 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2651 undef;
2654 sub absent_file {
2655 my ($self, $path, $pb) = @_;
2656 $self->{absent_file}->{$pb->{path}} ||= [];
2657 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2658 undef;
2661 sub change_file_prop {
2662 my ($self, $fb, $prop, $value) = @_;
2663 if ($prop eq 'svn:executable') {
2664 if ($fb->{mode_b} != 120000) {
2665 $fb->{mode_b} = defined $value ? 100755 : 100644;
2667 } elsif ($prop eq 'svn:special') {
2668 $fb->{mode_b} = defined $value ? 120000 : 100644;
2669 } else {
2670 $self->{file_prop}->{$fb->{path}} ||= {};
2671 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2673 undef;
2676 sub apply_textdelta {
2677 my ($self, $fb, $exp) = @_;
2678 my $fh = IO::File->new_tmpfile;
2679 $fh->autoflush(1);
2680 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2681 # (but $base does not,) so dup() it for reading in close_file
2682 open my $dup, '<&', $fh or croak $!;
2683 my $base = IO::File->new_tmpfile;
2684 $base->autoflush(1);
2685 if ($fb->{blob}) {
2686 defined (my $pid = fork) or croak $!;
2687 if (!$pid) {
2688 open STDOUT, '>&', $base or croak $!;
2689 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2690 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2692 waitpid $pid, 0;
2693 croak $? if $?;
2695 if (defined $exp) {
2696 seek $base, 0, 0 or croak $!;
2697 my $md5 = Digest::MD5->new;
2698 $md5->addfile($base);
2699 my $got = $md5->hexdigest;
2700 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2701 "expected: $exp\n",
2702 " got: $got\n" if ($got ne $exp);
2705 seek $base, 0, 0 or croak $!;
2706 $fb->{fh} = $dup;
2707 $fb->{base} = $base;
2708 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2711 sub close_file {
2712 my ($self, $fb, $exp) = @_;
2713 my $hash;
2714 my $path = $self->git_path($fb->{path});
2715 if (my $fh = $fb->{fh}) {
2716 if (defined $exp) {
2717 seek($fh, 0, 0) or croak $!;
2718 my $md5 = Digest::MD5->new;
2719 $md5->addfile($fh);
2720 my $got = $md5->hexdigest;
2721 if ($got ne $exp) {
2722 die "Checksum mismatch: $path\n",
2723 "expected: $exp\n got: $got\n";
2726 sysseek($fh, 0, 0) or croak $!;
2727 if ($fb->{mode_b} == 120000) {
2728 sysread($fh, my $buf, 5) == 5 or croak $!;
2729 $buf eq 'link ' or die "$path has mode 120000",
2730 "but is not a link\n";
2732 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2733 if (!$pid) {
2734 open STDIN, '<&', $fh or croak $!;
2735 exec qw/git-hash-object -w --stdin/ or croak $!;
2737 chomp($hash = do { local $/; <$out> });
2738 close $out or croak $!;
2739 close $fh or croak $!;
2740 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2741 close $fb->{base} or croak $!;
2742 } else {
2743 $hash = $fb->{blob} or die "no blob information\n";
2745 $fb->{pool}->clear;
2746 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2747 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2748 undef;
2751 sub abort_edit {
2752 my $self = shift;
2753 $self->{nr} = $self->{gii}->{nr};
2754 delete $self->{gii};
2755 $self->SUPER::abort_edit(@_);
2758 sub close_edit {
2759 my $self = shift;
2760 $self->{git_commit_ok} = 1;
2761 $self->{nr} = $self->{gii}->{nr};
2762 delete $self->{gii};
2763 $self->SUPER::close_edit(@_);
2766 package SVN::Git::Editor;
2767 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2768 use strict;
2769 use warnings;
2770 use Carp qw/croak/;
2771 use IO::File;
2772 use Digest::MD5;
2774 sub new {
2775 my ($class, $opts) = @_;
2776 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2777 die "$_ required!\n" unless (defined $opts->{$_});
2780 my $pool = SVN::Pool->new;
2781 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2782 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2783 $opts->{r}, $mods);
2785 # $opts->{ra} functions should not be used after this:
2786 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2787 $opts->{editor_cb}, $pool);
2788 my $self = SVN::Delta::Editor->new(@ce, $pool);
2789 bless $self, $class;
2790 foreach (qw/svn_path r tree_a tree_b/) {
2791 $self->{$_} = $opts->{$_};
2793 $self->{url} = $opts->{ra}->{url};
2794 $self->{mods} = $mods;
2795 $self->{types} = $types;
2796 $self->{pool} = $pool;
2797 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2798 $self->{rm} = { };
2799 $self->{path_prefix} = length $self->{svn_path} ?
2800 "$self->{svn_path}/" : '';
2801 return $self;
2804 sub generate_diff {
2805 my ($tree_a, $tree_b) = @_;
2806 my @diff_tree = qw(diff-tree -z -r);
2807 if ($_cp_similarity) {
2808 push @diff_tree, "-C$_cp_similarity";
2809 } else {
2810 push @diff_tree, '-C';
2812 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2813 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2814 push @diff_tree, $tree_a, $tree_b;
2815 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2816 local $/ = "\0";
2817 my $state = 'meta';
2818 my @mods;
2819 while (<$diff_fh>) {
2820 chomp $_; # this gets rid of the trailing "\0"
2821 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2822 $::sha1\s($::sha1)\s
2823 ([MTCRAD])\d*$/xo) {
2824 push @mods, { mode_a => $1, mode_b => $2,
2825 sha1_b => $3, chg => $4 };
2826 if ($4 =~ /^(?:C|R)$/) {
2827 $state = 'file_a';
2828 } else {
2829 $state = 'file_b';
2831 } elsif ($state eq 'file_a') {
2832 my $x = $mods[$#mods] or croak "Empty array\n";
2833 if ($x->{chg} !~ /^(?:C|R)$/) {
2834 croak "Error parsing $_, $x->{chg}\n";
2836 $x->{file_a} = $_;
2837 $state = 'file_b';
2838 } elsif ($state eq 'file_b') {
2839 my $x = $mods[$#mods] or croak "Empty array\n";
2840 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2841 croak "Error parsing $_, $x->{chg}\n";
2843 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2844 croak "Error parsing $_, $x->{chg}\n";
2846 $x->{file_b} = $_;
2847 $state = 'meta';
2848 } else {
2849 croak "Error parsing $_\n";
2852 command_close_pipe($diff_fh, $ctx);
2853 \@mods;
2856 sub check_diff_paths {
2857 my ($ra, $pfx, $rev, $mods) = @_;
2858 my %types;
2859 $pfx .= '/' if length $pfx;
2861 sub type_diff_paths {
2862 my ($ra, $types, $path, $rev) = @_;
2863 my @p = split m#/+#, $path;
2864 my $c = shift @p;
2865 unless (defined $types->{$c}) {
2866 $types->{$c} = $ra->check_path($c, $rev);
2868 while (@p) {
2869 $c .= '/' . shift @p;
2870 next if defined $types->{$c};
2871 $types->{$c} = $ra->check_path($c, $rev);
2875 foreach my $m (@$mods) {
2876 foreach my $f (qw/file_a file_b/) {
2877 next unless defined $m->{$f};
2878 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2879 if (length $pfx.$dir && ! defined $types{$dir}) {
2880 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2884 \%types;
2887 sub split_path {
2888 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2891 sub repo_path {
2892 my ($self, $path) = @_;
2893 $self->{path_prefix}.(defined $path ? $path : '');
2896 sub url_path {
2897 my ($self, $path) = @_;
2898 if ($self->{url} =~ m#^https?://#) {
2899 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2901 $self->{url} . '/' . $self->repo_path($path);
2904 sub rmdirs {
2905 my ($self) = @_;
2906 my $rm = $self->{rm};
2907 delete $rm->{''}; # we never delete the url we're tracking
2908 return unless %$rm;
2910 foreach (keys %$rm) {
2911 my @d = split m#/#, $_;
2912 my $c = shift @d;
2913 $rm->{$c} = 1;
2914 while (@d) {
2915 $c .= '/' . shift @d;
2916 $rm->{$c} = 1;
2919 delete $rm->{$self->{svn_path}};
2920 delete $rm->{''}; # we never delete the url we're tracking
2921 return unless %$rm;
2923 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2924 $self->{tree_b});
2925 local $/ = "\0";
2926 while (<$fh>) {
2927 chomp;
2928 my @dn = split m#/#, $_;
2929 while (pop @dn) {
2930 delete $rm->{join '/', @dn};
2932 unless (%$rm) {
2933 close $fh;
2934 return;
2937 command_close_pipe($fh, $ctx);
2939 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2940 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2941 $self->close_directory($bat->{$d}, $p);
2942 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2943 print "\tD+\t$d/\n" unless $::_q;
2944 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2945 delete $bat->{$d};
2949 sub open_or_add_dir {
2950 my ($self, $full_path, $baton) = @_;
2951 my $t = $self->{types}->{$full_path};
2952 if (!defined $t) {
2953 die "$full_path not known in r$self->{r} or we have a bug!\n";
2956 no warnings 'once';
2957 # SVN::Node::none and SVN::Node::file are used only once,
2958 # so we're shutting up Perl's warnings about them.
2959 if ($t == $SVN::Node::none) {
2960 return $self->add_directory($full_path, $baton,
2961 undef, -1, $self->{pool});
2962 } elsif ($t == $SVN::Node::dir) {
2963 return $self->open_directory($full_path, $baton,
2964 $self->{r}, $self->{pool});
2965 } # no warnings 'once'
2966 print STDERR "$full_path already exists in repository at ",
2967 "r$self->{r} and it is not a directory (",
2968 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2969 } # no warnings 'once'
2970 exit 1;
2973 sub ensure_path {
2974 my ($self, $path) = @_;
2975 my $bat = $self->{bat};
2976 my $repo_path = $self->repo_path($path);
2977 return $bat->{''} unless (length $repo_path);
2978 my @p = split m#/+#, $repo_path;
2979 my $c = shift @p;
2980 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2981 while (@p) {
2982 my $c0 = $c;
2983 $c .= '/' . shift @p;
2984 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2986 return $bat->{$c};
2989 sub A {
2990 my ($self, $m) = @_;
2991 my ($dir, $file) = split_path($m->{file_b});
2992 my $pbat = $self->ensure_path($dir);
2993 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2994 undef, -1);
2995 print "\tA\t$m->{file_b}\n" unless $::_q;
2996 $self->chg_file($fbat, $m);
2997 $self->close_file($fbat,undef,$self->{pool});
3000 sub C {
3001 my ($self, $m) = @_;
3002 my ($dir, $file) = split_path($m->{file_b});
3003 my $pbat = $self->ensure_path($dir);
3004 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3005 $self->url_path($m->{file_a}), $self->{r});
3006 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3007 $self->chg_file($fbat, $m);
3008 $self->close_file($fbat,undef,$self->{pool});
3011 sub delete_entry {
3012 my ($self, $path, $pbat) = @_;
3013 my $rpath = $self->repo_path($path);
3014 my ($dir, $file) = split_path($rpath);
3015 $self->{rm}->{$dir} = 1;
3016 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3019 sub R {
3020 my ($self, $m) = @_;
3021 my ($dir, $file) = split_path($m->{file_b});
3022 my $pbat = $self->ensure_path($dir);
3023 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3024 $self->url_path($m->{file_a}), $self->{r});
3025 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3026 $self->chg_file($fbat, $m);
3027 $self->close_file($fbat,undef,$self->{pool});
3029 ($dir, $file) = split_path($m->{file_a});
3030 $pbat = $self->ensure_path($dir);
3031 $self->delete_entry($m->{file_a}, $pbat);
3034 sub M {
3035 my ($self, $m) = @_;
3036 my ($dir, $file) = split_path($m->{file_b});
3037 my $pbat = $self->ensure_path($dir);
3038 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3039 $pbat,$self->{r},$self->{pool});
3040 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3041 $self->chg_file($fbat, $m);
3042 $self->close_file($fbat,undef,$self->{pool});
3045 sub T { shift->M(@_) }
3047 sub change_file_prop {
3048 my ($self, $fbat, $pname, $pval) = @_;
3049 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3052 sub chg_file {
3053 my ($self, $fbat, $m) = @_;
3054 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3055 $self->change_file_prop($fbat,'svn:executable','*');
3056 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3057 $self->change_file_prop($fbat,'svn:executable',undef);
3059 my $fh = IO::File->new_tmpfile or croak $!;
3060 if ($m->{mode_b} =~ /^120/) {
3061 print $fh 'link ' or croak $!;
3062 $self->change_file_prop($fbat,'svn:special','*');
3063 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3064 $self->change_file_prop($fbat,'svn:special',undef);
3066 defined(my $pid = fork) or croak $!;
3067 if (!$pid) {
3068 open STDOUT, '>&', $fh or croak $!;
3069 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3071 waitpid $pid, 0;
3072 croak $? if $?;
3073 $fh->flush == 0 or croak $!;
3074 seek $fh, 0, 0 or croak $!;
3076 my $md5 = Digest::MD5->new;
3077 $md5->addfile($fh) or croak $!;
3078 seek $fh, 0, 0 or croak $!;
3080 my $exp = $md5->hexdigest;
3081 my $pool = SVN::Pool->new;
3082 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3083 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3084 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3085 $pool->clear;
3087 close $fh or croak $!;
3090 sub D {
3091 my ($self, $m) = @_;
3092 my ($dir, $file) = split_path($m->{file_b});
3093 my $pbat = $self->ensure_path($dir);
3094 print "\tD\t$m->{file_b}\n" unless $::_q;
3095 $self->delete_entry($m->{file_b}, $pbat);
3098 sub close_edit {
3099 my ($self) = @_;
3100 my ($p,$bat) = ($self->{pool}, $self->{bat});
3101 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3102 next if $_ eq '';
3103 $self->close_directory($bat->{$_}, $p);
3105 $self->close_directory($bat->{''}, $p);
3106 $self->SUPER::close_edit($p);
3107 $p->clear;
3110 sub abort_edit {
3111 my ($self) = @_;
3112 $self->SUPER::abort_edit($self->{pool});
3115 sub DESTROY {
3116 my $self = shift;
3117 $self->SUPER::DESTROY(@_);
3118 $self->{pool}->clear;
3121 # this drives the editor
3122 sub apply_diff {
3123 my ($self) = @_;
3124 my $mods = $self->{mods};
3125 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3126 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3127 my $f = $m->{chg};
3128 if (defined $o{$f}) {
3129 $self->$f($m);
3130 } else {
3131 fatal("Invalid change type: $f");
3134 $self->rmdirs if $_rmdir;
3135 if (@$mods == 0) {
3136 $self->abort_edit;
3137 } else {
3138 $self->close_edit;
3140 return scalar @$mods;
3143 package Git::SVN::Ra;
3144 use vars qw/@ISA $config_dir $_log_window_size/;
3145 use strict;
3146 use warnings;
3147 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3149 BEGIN {
3150 # enforce temporary pool usage for some simple functions
3151 no strict 'refs';
3152 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3153 my $SUPER = "SUPER::$f";
3154 *$f = sub {
3155 my $self = shift;
3156 my $pool = SVN::Pool->new;
3157 my @ret = $self->$SUPER(@_,$pool);
3158 $pool->clear;
3159 wantarray ? @ret : $ret[0];
3164 sub _auth_providers () {
3166 SVN::Client::get_simple_provider(),
3167 SVN::Client::get_ssl_server_trust_file_provider(),
3168 SVN::Client::get_simple_prompt_provider(
3169 \&Git::SVN::Prompt::simple, 2),
3170 SVN::Client::get_ssl_client_cert_file_provider(),
3171 SVN::Client::get_ssl_client_cert_prompt_provider(
3172 \&Git::SVN::Prompt::ssl_client_cert, 2),
3173 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3174 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3175 SVN::Client::get_username_provider(),
3176 SVN::Client::get_ssl_server_trust_prompt_provider(
3177 \&Git::SVN::Prompt::ssl_server_trust),
3178 SVN::Client::get_username_prompt_provider(
3179 \&Git::SVN::Prompt::username, 2)
3183 sub new {
3184 my ($class, $url) = @_;
3185 $url =~ s!/+$!!;
3186 return $RA if ($RA && $RA->{url} eq $url);
3188 SVN::_Core::svn_config_ensure($config_dir, undef);
3189 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3190 my $config = SVN::Core::config_get_config($config_dir);
3191 $RA = undef;
3192 my $dont_store_passwords = 1;
3193 my $conf_t = ${$config}{'config'};
3195 no warnings 'once';
3196 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3197 # produces warnings that variables are used only once.
3198 # I had not found the better way to shut them up, so
3199 # the warnings of type 'once' are disabled in this block.
3200 if (SVN::_Core::svn_config_get_bool($conf_t,
3201 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3202 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3203 1) == 0) {
3204 SVN::_Core::svn_auth_set_parameter($baton,
3205 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3206 bless (\$dont_store_passwords, "_p_void"));
3208 if (SVN::_Core::svn_config_get_bool($conf_t,
3209 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3210 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3211 1) == 0) {
3212 $Git::SVN::Prompt::_no_auth_cache = 1;
3214 } # no warnings 'once'
3215 my $self = SVN::Ra->new(url => $url, auth => $baton,
3216 config => $config,
3217 pool => SVN::Pool->new,
3218 auth_provider_callbacks => $callbacks);
3219 $self->{svn_path} = $url;
3220 $self->{repos_root} = $self->get_repos_root;
3221 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3222 $self->{cache} = { check_path => { r => 0, data => {} },
3223 get_dir => { r => 0, data => {} } };
3224 $RA = bless $self, $class;
3227 sub check_path {
3228 my ($self, $path, $r) = @_;
3229 my $cache = $self->{cache}->{check_path};
3230 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3231 return $cache->{data}->{$path};
3233 my $pool = SVN::Pool->new;
3234 my $t = $self->SUPER::check_path($path, $r, $pool);
3235 $pool->clear;
3236 if ($r != $cache->{r}) {
3237 %{$cache->{data}} = ();
3238 $cache->{r} = $r;
3240 $cache->{data}->{$path} = $t;
3243 sub get_dir {
3244 my ($self, $dir, $r) = @_;
3245 my $cache = $self->{cache}->{get_dir};
3246 if ($r == $cache->{r}) {
3247 if (my $x = $cache->{data}->{$dir}) {
3248 return wantarray ? @$x : $x->[0];
3251 my $pool = SVN::Pool->new;
3252 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3253 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3254 $pool->clear;
3255 if ($r != $cache->{r}) {
3256 %{$cache->{data}} = ();
3257 $cache->{r} = $r;
3259 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3260 wantarray ? (\%dirents, $r, $props) : \%dirents;
3263 sub DESTROY {
3264 # do not call the real DESTROY since we store ourselves in $RA
3267 sub get_log {
3268 my ($self, @args) = @_;
3269 my $pool = SVN::Pool->new;
3270 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3271 my $ret = $self->SUPER::get_log(@args, $pool);
3272 $pool->clear;
3273 $ret;
3276 sub trees_match {
3277 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3278 my $ctx = SVN::Client->new(auth => _auth_providers);
3279 my $out = IO::File->new_tmpfile;
3281 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3282 # $ctx->diff(), so we'll create a default one
3283 my $pool = SVN::Pool->new_default_sub;
3285 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3286 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3287 $out->flush;
3288 my $ret = (($out->stat)[7] == 0);
3289 close $out or croak $!;
3291 $ret;
3294 sub get_commit_editor {
3295 my ($self, $log, $cb, $pool) = @_;
3296 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3297 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3300 sub gs_do_update {
3301 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3302 my $new = ($rev_a == $rev_b);
3303 my $path = $gs->{path};
3305 if ($new && -e $gs->{index}) {
3306 unlink $gs->{index} or die
3307 "Couldn't unlink index: $gs->{index}: $!\n";
3309 my $pool = SVN::Pool->new;
3310 $editor->set_path_strip($path);
3311 my (@pc) = split m#/#, $path;
3312 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3313 1, $editor, $pool);
3314 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3316 # Since we can't rely on svn_ra_reparent being available, we'll
3317 # just have to do some magic with set_path to make it so
3318 # we only want a partial path.
3319 my $sp = '';
3320 my $final = join('/', @pc);
3321 while (@pc) {
3322 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3323 $sp .= '/' if length $sp;
3324 $sp .= shift @pc;
3326 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3328 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3330 $reporter->finish_report($pool);
3331 $pool->clear;
3332 $editor->{git_commit_ok};
3335 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3336 # svn_ra_reparent didn't work before 1.4)
3337 sub gs_do_switch {
3338 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3339 my $path = $gs->{path};
3340 my $pool = SVN::Pool->new;
3342 my $full_url = $self->{url};
3343 my $old_url = $full_url;
3344 $full_url .= "/$path" if length $path;
3345 my ($ra, $reparented);
3346 if ($old_url ne $full_url) {
3347 if ($old_url !~ m#^svn(\+ssh)?://#) {
3348 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3349 $pool);
3350 $self->{url} = $full_url;
3351 $reparented = 1;
3352 } else {
3353 $_[0] = undef;
3354 $self = undef;
3355 $RA = undef;
3356 $ra = Git::SVN::Ra->new($full_url);
3357 $ra_invalid = 1;
3360 $ra ||= $self;
3361 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3362 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3363 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3364 $reporter->finish_report($pool);
3366 if ($reparented) {
3367 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3368 $self->{url} = $old_url;
3371 $pool->clear;
3372 $editor->{git_commit_ok};
3375 sub longest_common_path {
3376 my ($gsv, $globs) = @_;
3377 my %common;
3378 my $common_max = scalar @$gsv;
3380 foreach my $gs (@$gsv) {
3381 my @tmp = split m#/#, $gs->{path};
3382 my $p = '';
3383 foreach (@tmp) {
3384 $p .= length($p) ? "/$_" : $_;
3385 $common{$p} ||= 0;
3386 $common{$p}++;
3389 $globs ||= [];
3390 $common_max += scalar @$globs;
3391 foreach my $glob (@$globs) {
3392 my @tmp = split m#/#, $glob->{path}->{left};
3393 my $p = '';
3394 foreach (@tmp) {
3395 $p .= length($p) ? "/$_" : $_;
3396 $common{$p} ||= 0;
3397 $common{$p}++;
3401 my $longest_path = '';
3402 foreach (sort {length $b <=> length $a} keys %common) {
3403 if ($common{$_} == $common_max) {
3404 $longest_path = $_;
3405 last;
3408 $longest_path;
3411 sub gs_fetch_loop_common {
3412 my ($self, $base, $head, $gsv, $globs) = @_;
3413 return if ($base > $head);
3414 my $inc = $_log_window_size;
3415 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3416 my $longest_path = longest_common_path($gsv, $globs);
3417 my $ra_url = $self->{url};
3418 while (1) {
3419 my %revs;
3420 my $err;
3421 my $err_handler = $SVN::Error::handler;
3422 $SVN::Error::handler = sub {
3423 ($err) = @_;
3424 skip_unknown_revs($err);
3426 sub _cb {
3427 my ($paths, $r, $author, $date, $log) = @_;
3428 [ dup_changed_paths($paths),
3429 { author => $author, date => $date, log => $log } ];
3431 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3432 sub { $revs{$_[1]} = _cb(@_) });
3433 if ($err && $max >= $head) {
3434 print STDERR "Path '$longest_path' ",
3435 "was probably deleted:\n",
3436 $err->expanded_message,
3437 "\nWill attempt to follow ",
3438 "revisions r$min .. r$max ",
3439 "committed before the deletion\n";
3440 my $hi = $max;
3441 while (--$hi >= $min) {
3442 my $ok;
3443 $self->get_log([$longest_path], $min, $hi,
3444 0, 1, 1, sub {
3445 $ok ||= $_[1];
3446 $revs{$_[1]} = _cb(@_) });
3447 if ($ok) {
3448 print STDERR "r$min .. r$ok OK\n";
3449 last;
3453 $SVN::Error::handler = $err_handler;
3455 my %exists = map { $_->{path} => $_ } @$gsv;
3456 foreach my $r (sort {$a <=> $b} keys %revs) {
3457 my ($paths, $logged) = @{$revs{$r}};
3459 foreach my $gs ($self->match_globs(\%exists, $paths,
3460 $globs, $r)) {
3461 if ($gs->rev_db_max >= $r) {
3462 next;
3464 next unless $gs->match_paths($paths, $r);
3465 $gs->{logged_rev_props} = $logged;
3466 if (my $last_commit = $gs->last_commit) {
3467 $gs->assert_index_clean($last_commit);
3469 my $log_entry = $gs->do_fetch($paths, $r);
3470 if ($log_entry) {
3471 $gs->do_git_commit($log_entry);
3474 foreach my $g (@$globs) {
3475 my $k = "svn-remote.$g->{remote}." .
3476 "$g->{t}-maxRev";
3477 Git::SVN::tmp_config($k, $r);
3479 if ($ra_invalid) {
3480 $_[0] = undef;
3481 $self = undef;
3482 $RA = undef;
3483 $self = Git::SVN::Ra->new($ra_url);
3484 $ra_invalid = undef;
3487 # pre-fill the .rev_db since it'll eventually get filled in
3488 # with '0' x40 if something new gets committed
3489 foreach my $gs (@$gsv) {
3490 next if defined $gs->rev_db_get($max);
3491 $gs->rev_db_set($max, 0 x40);
3493 foreach my $g (@$globs) {
3494 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3495 Git::SVN::tmp_config($k, $max);
3497 last if $max >= $head;
3498 $min = $max + 1;
3499 $max += $inc;
3500 $max = $head if ($max > $head);
3504 sub match_globs {
3505 my ($self, $exists, $paths, $globs, $r) = @_;
3507 sub get_dir_check {
3508 my ($self, $exists, $g, $r) = @_;
3509 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3510 return unless scalar @x == 3;
3511 my $dirents = $x[0];
3512 foreach my $de (keys %$dirents) {
3513 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3514 my $p = $g->{path}->full_path($de);
3515 next if $exists->{$p};
3516 next if (length $g->{path}->{right} &&
3517 ($self->check_path($p, $r) !=
3518 $SVN::Node::dir));
3519 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3520 $g->{ref}->full_path($de), 1);
3523 foreach my $g (@$globs) {
3524 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3525 if ($path->{action} =~ /^[AR]$/) {
3526 get_dir_check($self, $exists, $g, $r);
3529 foreach (keys %$paths) {
3530 if (/$g->{path}->{left_regex}/ &&
3531 !/$g->{path}->{regex}/) {
3532 next if $paths->{$_}->{action} !~ /^[AR]$/;
3533 get_dir_check($self, $exists, $g, $r);
3535 next unless /$g->{path}->{regex}/;
3536 my $p = $1;
3537 my $pathname = $g->{path}->full_path($p);
3538 next if $exists->{$pathname};
3539 next if ($self->check_path($pathname, $r) !=
3540 $SVN::Node::dir);
3541 $exists->{$pathname} = Git::SVN->init(
3542 $self->{url}, $pathname, undef,
3543 $g->{ref}->full_path($p), 1);
3545 my $c = '';
3546 foreach (split m#/#, $g->{path}->{left}) {
3547 $c .= "/$_";
3548 next unless ($paths->{$c} &&
3549 ($paths->{$c}->{action} =~ /^[AR]$/));
3550 get_dir_check($self, $exists, $g, $r);
3553 values %$exists;
3556 sub minimize_url {
3557 my ($self) = @_;
3558 return $self->{url} if ($self->{url} eq $self->{repos_root});
3559 my $url = $self->{repos_root};
3560 my @components = split(m!/!, $self->{svn_path});
3561 my $c = '';
3562 do {
3563 $url .= "/$c" if length $c;
3564 eval { (ref $self)->new($url)->get_latest_revnum };
3565 } while ($@ && ($c = shift @components));
3566 $url;
3569 sub can_do_switch {
3570 my $self = shift;
3571 unless (defined $can_do_switch) {
3572 my $pool = SVN::Pool->new;
3573 my $rep = eval {
3574 $self->do_switch(1, '', 0, $self->{url},
3575 SVN::Delta::Editor->new, $pool);
3577 if ($@) {
3578 $can_do_switch = 0;
3579 } else {
3580 $rep->abort_report($pool);
3581 $can_do_switch = 1;
3583 $pool->clear;
3585 $can_do_switch;
3588 sub skip_unknown_revs {
3589 my ($err) = @_;
3590 my $errno = $err->apr_err();
3591 # Maybe the branch we're tracking didn't
3592 # exist when the repo started, so it's
3593 # not an error if it doesn't, just continue
3595 # Wonderfully consistent library, eh?
3596 # 160013 - svn:// and file://
3597 # 175002 - http(s)://
3598 # 175007 - http(s):// (this repo required authorization, too...)
3599 # More codes may be discovered later...
3600 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3601 my $err_key = $err->expanded_message;
3602 # revision numbers change every time, filter them out
3603 $err_key =~ s/\d+/\0/g;
3604 $err_key = "$errno\0$err_key";
3605 unless ($ignored_err{$err_key}) {
3606 warn "W: Ignoring error from SVN, path probably ",
3607 "does not exist: ($errno): ",
3608 $err->expanded_message,"\n";
3609 $ignored_err{$err_key} = 1;
3611 return;
3613 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3616 # svn_log_changed_path_t objects passed to get_log are likely to be
3617 # overwritten even if only the refs are copied to an external variable,
3618 # so we should dup the structures in their entirety. Using an externally
3619 # passed pool (instead of our temporary and quickly cleared pool in
3620 # Git::SVN::Ra) does not help matters at all...
3621 sub dup_changed_paths {
3622 my ($paths) = @_;
3623 return undef unless $paths;
3624 my %ret;
3625 foreach my $p (keys %$paths) {
3626 my $i = $paths->{$p};
3627 my %s = map { $_ => $i->$_ }
3628 qw/copyfrom_path copyfrom_rev action/;
3629 $ret{$p} = \%s;
3631 \%ret;
3634 package Git::SVN::Log;
3635 use strict;
3636 use warnings;
3637 use POSIX qw/strftime/;
3638 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3639 %rusers $show_commit $incremental/;
3640 my $l_fmt;
3642 sub cmt_showable {
3643 my ($c) = @_;
3644 return 1 if defined $c->{r};
3646 # big commit message got truncated by the 16k pretty buffer in rev-list
3647 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3648 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3649 @{$c->{l}} = ();
3650 my @log = command(qw/cat-file commit/, $c->{c});
3652 # shift off the headers
3653 shift @log while ($log[0] ne '');
3654 shift @log;
3656 # TODO: make $c->{l} not have a trailing newline in the future
3657 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3659 (undef, $c->{r}, undef) = ::extract_metadata(
3660 (grep(/^git-svn-id: /, @log))[-1]);
3662 return defined $c->{r};
3665 sub log_use_color {
3666 return 1 if $color;
3667 my ($dc, $dcvar);
3668 $dcvar = 'color.diff';
3669 $dc = `git-config --get $dcvar`;
3670 if ($dc eq '') {
3671 # nothing at all; fallback to "diff.color"
3672 $dcvar = 'diff.color';
3673 $dc = `git-config --get $dcvar`;
3675 chomp($dc);
3676 if ($dc eq 'auto') {
3677 my $pc;
3678 $pc = `git-config --get color.pager`;
3679 if ($pc eq '') {
3680 # does not have it -- fallback to pager.color
3681 $pc = `git-config --bool --get pager.color`;
3683 else {
3684 $pc = `git-config --bool --get color.pager`;
3685 if ($?) {
3686 $pc = 'false';
3689 chomp($pc);
3690 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3691 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3693 return 0;
3695 return 0 if $dc eq 'never';
3696 return 1 if $dc eq 'always';
3697 chomp($dc = `git-config --bool --get $dcvar`);
3698 return ($dc eq 'true');
3701 sub git_svn_log_cmd {
3702 my ($r_min, $r_max, @args) = @_;
3703 my $head = 'HEAD';
3704 my (@files, @log_opts);
3705 foreach my $x (@args) {
3706 if ($x eq '--' || @files) {
3707 push @files, $x;
3708 } else {
3709 if (::verify_ref("$x^0")) {
3710 $head = $x;
3711 } else {
3712 push @log_opts, $x;
3717 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3718 $gs ||= Git::SVN->_new;
3719 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3720 $gs->refname);
3721 push @cmd, '-r' unless $non_recursive;
3722 push @cmd, qw/--raw --name-status/ if $verbose;
3723 push @cmd, '--color' if log_use_color();
3724 push @cmd, @log_opts;
3725 if (defined $r_max && $r_max == $r_min) {
3726 push @cmd, '--max-count=1';
3727 if (my $c = $gs->rev_db_get($r_max)) {
3728 push @cmd, $c;
3730 } elsif (defined $r_max) {
3731 my ($c_min, $c_max);
3732 $c_max = $gs->rev_db_get($r_max);
3733 $c_min = $gs->rev_db_get($r_min);
3734 if (defined $c_min && defined $c_max) {
3735 if ($r_max > $r_max) {
3736 push @cmd, "$c_min..$c_max";
3737 } else {
3738 push @cmd, "$c_max..$c_min";
3740 } elsif ($r_max > $r_min) {
3741 push @cmd, $c_max;
3742 } else {
3743 push @cmd, $c_min;
3746 return (@cmd, @files);
3749 # adapted from pager.c
3750 sub config_pager {
3751 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3752 if (!defined $pager) {
3753 $pager = 'less';
3754 } elsif (length $pager == 0 || $pager eq 'cat') {
3755 $pager = undef;
3759 sub run_pager {
3760 return unless -t *STDOUT && defined $pager;
3761 pipe my $rfd, my $wfd or return;
3762 defined(my $pid = fork) or ::fatal "Can't fork: $!";
3763 if (!$pid) {
3764 open STDOUT, '>&', $wfd or
3765 ::fatal "Can't redirect to stdout: $!";
3766 return;
3768 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
3769 $ENV{LESS} ||= 'FRSX';
3770 exec $pager or ::fatal "Can't run pager: $! ($pager)";
3773 sub tz_to_s_offset {
3774 my ($tz) = @_;
3775 $tz =~ s/(\d\d)$//;
3776 return ($1 * 60) + ($tz * 3600);
3779 sub get_author_info {
3780 my ($dest, $author, $t, $tz) = @_;
3781 $author =~ s/(?:^\s*|\s*$)//g;
3782 $dest->{a_raw} = $author;
3783 my $au;
3784 if ($::_authors) {
3785 $au = $rusers{$author} || undef;
3787 if (!$au) {
3788 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3790 $dest->{t} = $t;
3791 $dest->{tz} = $tz;
3792 $dest->{a} = $au;
3793 # Date::Parse isn't in the standard Perl distro :(
3794 if ($tz =~ s/^\+//) {
3795 $t += tz_to_s_offset($tz);
3796 } elsif ($tz =~ s/^\-//) {
3797 $t -= tz_to_s_offset($tz);
3799 $dest->{t_utc} = $t;
3802 sub process_commit {
3803 my ($c, $r_min, $r_max, $defer) = @_;
3804 if (defined $r_min && defined $r_max) {
3805 if ($r_min == $c->{r} && $r_min == $r_max) {
3806 show_commit($c);
3807 return 0;
3809 return 1 if $r_min == $r_max;
3810 if ($r_min < $r_max) {
3811 # we need to reverse the print order
3812 return 0 if (defined $limit && --$limit < 0);
3813 push @$defer, $c;
3814 return 1;
3816 if ($r_min != $r_max) {
3817 return 1 if ($r_min < $c->{r});
3818 return 1 if ($r_max > $c->{r});
3821 return 0 if (defined $limit && --$limit < 0);
3822 show_commit($c);
3823 return 1;
3826 sub show_commit {
3827 my $c = shift;
3828 if ($oneline) {
3829 my $x = "\n";
3830 if (my $l = $c->{l}) {
3831 while ($l->[0] =~ /^\s*$/) { shift @$l }
3832 $x = $l->[0];
3834 $l_fmt ||= 'A' . length($c->{r});
3835 print 'r',pack($l_fmt, $c->{r}),' | ';
3836 print "$c->{c} | " if $show_commit;
3837 print $x;
3838 } else {
3839 show_commit_normal($c);
3843 sub show_commit_changed_paths {
3844 my ($c) = @_;
3845 return unless $c->{changed};
3846 print "Changed paths:\n", @{$c->{changed}};
3849 sub show_commit_normal {
3850 my ($c) = @_;
3851 print '-' x72, "\nr$c->{r} | ";
3852 print "$c->{c} | " if $show_commit;
3853 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3854 localtime($c->{t_utc})), ' | ';
3855 my $nr_line = 0;
3857 if (my $l = $c->{l}) {
3858 while ($l->[$#$l] eq "\n" && $#$l > 0
3859 && $l->[($#$l - 1)] eq "\n") {
3860 pop @$l;
3862 $nr_line = scalar @$l;
3863 if (!$nr_line) {
3864 print "1 line\n\n\n";
3865 } else {
3866 if ($nr_line == 1) {
3867 $nr_line = '1 line';
3868 } else {
3869 $nr_line .= ' lines';
3871 print $nr_line, "\n";
3872 show_commit_changed_paths($c);
3873 print "\n";
3874 print $_ foreach @$l;
3876 } else {
3877 print "1 line\n";
3878 show_commit_changed_paths($c);
3879 print "\n";
3882 foreach my $x (qw/raw stat diff/) {
3883 if ($c->{$x}) {
3884 print "\n";
3885 print $_ foreach @{$c->{$x}}
3890 sub cmd_show_log {
3891 my (@args) = @_;
3892 my ($r_min, $r_max);
3893 my $r_last = -1; # prevent dupes
3894 if (defined $TZ) {
3895 $ENV{TZ} = $TZ;
3896 } else {
3897 delete $ENV{TZ};
3899 if (defined $::_revision) {
3900 if ($::_revision =~ /^(\d+):(\d+)$/) {
3901 ($r_min, $r_max) = ($1, $2);
3902 } elsif ($::_revision =~ /^\d+$/) {
3903 $r_min = $r_max = $::_revision;
3904 } else {
3905 ::fatal "-r$::_revision is not supported, use ",
3906 "standard 'git log' arguments instead";
3910 config_pager();
3911 @args = git_svn_log_cmd($r_min, $r_max, @args);
3912 my $log = command_output_pipe(@args);
3913 run_pager();
3914 my (@k, $c, $d, $stat);
3915 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3916 while (<$log>) {
3917 if (/^${esc_color}commit ($::sha1_short)/o) {
3918 my $cmt = $1;
3919 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3920 $r_last = $c->{r};
3921 process_commit($c, $r_min, $r_max, \@k) or
3922 goto out;
3924 $d = undef;
3925 $c = { c => $cmt };
3926 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3927 get_author_info($c, $1, $2, $3);
3928 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3929 # ignore
3930 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3931 push @{$c->{raw}}, $_;
3932 } elsif (/^${esc_color}[ACRMDT]\t/) {
3933 # we could add $SVN->{svn_path} here, but that requires
3934 # remote access at the moment (repo_path_split)...
3935 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3936 push @{$c->{changed}}, $_;
3937 } elsif (/^${esc_color}diff /o) {
3938 $d = 1;
3939 push @{$c->{diff}}, $_;
3940 } elsif ($d) {
3941 push @{$c->{diff}}, $_;
3942 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3943 $esc_color*[\+\-]*$esc_color$/x) {
3944 $stat = 1;
3945 push @{$c->{stat}}, $_;
3946 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3947 push @{$c->{stat}}, $_;
3948 $stat = undef;
3949 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3950 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3951 } elsif (s/^${esc_color} //o) {
3952 push @{$c->{l}}, $_;
3955 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3956 $r_last = $c->{r};
3957 process_commit($c, $r_min, $r_max, \@k);
3959 if (@k) {
3960 my $swap = $r_max;
3961 $r_max = $r_min;
3962 $r_min = $swap;
3963 process_commit($_, $r_min, $r_max) foreach reverse @k;
3965 out:
3966 close $log;
3967 print '-' x72,"\n" unless $incremental || $oneline;
3970 package Git::SVN::Migration;
3971 # these version numbers do NOT correspond to actual version numbers
3972 # of git nor git-svn. They are just relative.
3974 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3976 # v1 layout: .git/$id/info/url, refs/remotes/$id
3978 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3980 # v3 layout: .git/svn/$id, refs/remotes/$id
3981 # - info/url may remain for backwards compatibility
3982 # - this is what we migrate up to this layout automatically,
3983 # - this will be used by git svn init on single branches
3984 # v3.1 layout (auto migrated):
3985 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3986 # for backwards compatibility
3988 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3989 # - this is only created for newly multi-init-ed
3990 # repositories. Similar in spirit to the
3991 # --use-separate-remotes option in git-clone (now default)
3992 # - we do not automatically migrate to this (following
3993 # the example set by core git)
3994 use strict;
3995 use warnings;
3996 use Carp qw/croak/;
3997 use File::Path qw/mkpath/;
3998 use File::Basename qw/dirname basename/;
3999 use vars qw/$_minimize/;
4001 sub migrate_from_v0 {
4002 my $git_dir = $ENV{GIT_DIR};
4003 return undef unless -d $git_dir;
4004 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4005 my $migrated = 0;
4006 while (<$fh>) {
4007 chomp;
4008 my ($id, $orig_ref) = ($_, $_);
4009 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4010 next unless -f "$git_dir/$id/info/url";
4011 my $new_ref = "refs/remotes/$id";
4012 if (::verify_ref("$new_ref^0")) {
4013 print STDERR "W: $orig_ref is probably an old ",
4014 "branch used by an ancient version of ",
4015 "git-svn.\n",
4016 "However, $new_ref also exists.\n",
4017 "We will not be able ",
4018 "to use this branch until this ",
4019 "ambiguity is resolved.\n";
4020 next;
4022 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4023 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4024 command_noisy('update-ref', $new_ref, $orig_ref);
4025 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4026 $migrated++;
4028 command_close_pipe($fh, $ctx);
4029 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4030 $migrated;
4033 sub migrate_from_v1 {
4034 my $git_dir = $ENV{GIT_DIR};
4035 my $migrated = 0;
4036 return $migrated unless -d $git_dir;
4037 my $svn_dir = "$git_dir/svn";
4039 # just in case somebody used 'svn' as their $id at some point...
4040 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4042 print STDERR "Migrating from a git-svn v1 layout...\n";
4043 mkpath([$svn_dir]);
4044 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4045 "$svn_dir\n\t(required for this version ",
4046 "($::VERSION) of git-svn) does not. exist\n";
4047 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4048 while (<$fh>) {
4049 my $x = $_;
4050 next unless $x =~ s#^refs/remotes/##;
4051 chomp $x;
4052 next unless -f "$git_dir/$x/info/url";
4053 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4054 next unless $u;
4055 my $dn = dirname("$git_dir/svn/$x");
4056 mkpath([$dn]) unless -d $dn;
4057 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4058 mkpath(["$git_dir/svn/svn"]);
4059 print STDERR " - $git_dir/$x/info => ",
4060 "$git_dir/svn/$x/info\n";
4061 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4062 croak "$!: $x";
4063 # don't worry too much about these, they probably
4064 # don't exist with repos this old (save for index,
4065 # and we can easily regenerate that)
4066 foreach my $f (qw/unhandled.log index .rev_db/) {
4067 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4069 } else {
4070 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4071 rename "$git_dir/$x", "$git_dir/svn/$x" or
4072 croak "$!: $x";
4074 $migrated++;
4076 command_close_pipe($fh, $ctx);
4077 print STDERR "Done migrating from a git-svn v1 layout\n";
4078 $migrated;
4081 sub read_old_urls {
4082 my ($l_map, $pfx, $path) = @_;
4083 my @dir;
4084 foreach (<$path/*>) {
4085 if (-r "$_/info/url") {
4086 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4087 my $ref_id = $pfx . basename $_;
4088 my $url = ::file_to_s("$_/info/url");
4089 $l_map->{$ref_id} = $url;
4090 } elsif (-d $_) {
4091 push @dir, $_;
4094 foreach (@dir) {
4095 my $x = $_;
4096 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4097 read_old_urls($l_map, $x, $_);
4101 sub migrate_from_v2 {
4102 my @cfg = command(qw/config -l/);
4103 return if grep /^svn-remote\..+\.url=/, @cfg;
4104 my %l_map;
4105 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4106 my $migrated = 0;
4108 foreach my $ref_id (sort keys %l_map) {
4109 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4110 if ($@) {
4111 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4113 $migrated++;
4115 $migrated;
4118 sub minimize_connections {
4119 my $r = Git::SVN::read_all_remotes();
4120 my $new_urls = {};
4121 my $root_repos = {};
4122 foreach my $repo_id (keys %$r) {
4123 my $url = $r->{$repo_id}->{url} or next;
4124 my $fetch = $r->{$repo_id}->{fetch} or next;
4125 my $ra = Git::SVN::Ra->new($url);
4127 # skip existing cases where we already connect to the root
4128 if (($ra->{url} eq $ra->{repos_root}) ||
4129 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4130 $repo_id)) {
4131 $root_repos->{$ra->{url}} = $repo_id;
4132 next;
4135 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4136 my $root_path = $ra->{url};
4137 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4138 foreach my $path (keys %$fetch) {
4139 my $ref_id = $fetch->{$path};
4140 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4142 # make sure we can read when connecting to
4143 # a higher level of a repository
4144 my ($last_rev, undef) = $gs->last_rev_commit;
4145 if (!defined $last_rev) {
4146 $last_rev = eval {
4147 $root_ra->get_latest_revnum;
4149 next if $@;
4151 my $new = $root_path;
4152 $new .= length $path ? "/$path" : '';
4153 eval {
4154 $root_ra->get_log([$new], $last_rev, $last_rev,
4155 0, 0, 1, sub { });
4157 next if $@;
4158 $new_urls->{$ra->{repos_root}}->{$new} =
4159 { ref_id => $ref_id,
4160 old_repo_id => $repo_id,
4161 old_path => $path };
4165 my @emptied;
4166 foreach my $url (keys %$new_urls) {
4167 # see if we can re-use an existing [svn-remote "repo_id"]
4168 # instead of creating a(n ugly) new section:
4169 my $repo_id = $root_repos->{$url} ||
4170 Git::SVN::sanitize_remote_name($url);
4172 my $fetch = $new_urls->{$url};
4173 foreach my $path (keys %$fetch) {
4174 my $x = $fetch->{$path};
4175 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4176 my $pfx = "svn-remote.$x->{old_repo_id}";
4178 my $old_fetch = quotemeta("$x->{old_path}:".
4179 "refs/remotes/$x->{ref_id}");
4180 command_noisy(qw/config --unset/,
4181 "$pfx.fetch", '^'. $old_fetch . '$');
4182 delete $r->{$x->{old_repo_id}}->
4183 {fetch}->{$x->{old_path}};
4184 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4185 command_noisy(qw/config --unset/,
4186 "$pfx.url");
4187 push @emptied, $x->{old_repo_id}
4191 if (@emptied) {
4192 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4193 "$ENV{GIT_DIR}/config";
4194 print STDERR <<EOF;
4195 The following [svn-remote] sections in your config file ($file) are empty
4196 and can be safely removed:
4198 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4202 sub migration_check {
4203 migrate_from_v0();
4204 migrate_from_v1();
4205 migrate_from_v2();
4206 minimize_connections() if $_minimize;
4209 package Git::IndexInfo;
4210 use strict;
4211 use warnings;
4212 use Git qw/command_input_pipe command_close_pipe/;
4214 sub new {
4215 my ($class) = @_;
4216 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4217 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4220 sub remove {
4221 my ($self, $path) = @_;
4222 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4223 return ++$self->{nr};
4225 undef;
4228 sub update {
4229 my ($self, $mode, $hash, $path) = @_;
4230 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4231 return ++$self->{nr};
4233 undef;
4236 sub DESTROY {
4237 my ($self) = @_;
4238 command_close_pipe($self->{gui}, $self->{ctx});
4241 package Git::SVN::GlobSpec;
4242 use strict;
4243 use warnings;
4245 sub new {
4246 my ($class, $glob) = @_;
4247 my $re = $glob;
4248 $re =~ s!/+$!!g; # no need for trailing slashes
4249 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4250 my ($left, $right) = ($1, $2);
4251 if ($nr > 1) {
4252 die "Only one '*' wildcard expansion ",
4253 "is supported (got $nr): '$glob'\n";
4254 } elsif ($nr == 0) {
4255 die "One '*' is needed for glob: '$glob'\n";
4257 $re = quotemeta($left) . $re . quotemeta($right);
4258 if (length $left && !($left =~ s!/+$!!g)) {
4259 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4261 if (length $right && !($right =~ s!^/+!!g)) {
4262 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4264 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4265 bless { left => $left, right => $right, left_regex => $left_re,
4266 regex => qr/$re/, glob => $glob }, $class;
4269 sub full_path {
4270 my ($self, $path) = @_;
4271 return (length $self->{left} ? "$self->{left}/" : '') .
4272 $path . (length $self->{right} ? "/$self->{right}" : '');
4275 __END__
4277 Data structures:
4280 $remotes = { # returned by read_all_remotes()
4281 'svn' => {
4282 # svn-remote.svn.url=https://svn.musicpd.org
4283 url => 'https://svn.musicpd.org',
4284 # svn-remote.svn.fetch=mpd/trunk:trunk
4285 fetch => {
4286 'mpd/trunk' => 'trunk',
4288 # svn-remote.svn.tags=mpd/tags/*:tags/*
4289 tags => {
4290 path => {
4291 left => 'mpd/tags',
4292 right => '',
4293 regex => qr!mpd/tags/([^/]+)$!,
4294 glob => 'tags/*',
4296 ref => {
4297 left => 'tags',
4298 right => '',
4299 regex => qr!tags/([^/]+)$!,
4300 glob => 'tags/*',
4306 $log_entry hashref as returned by libsvn_log_entry()
4308 log => 'whitespace-formatted log entry
4309 ', # trailing newline is preserved
4310 revision => '8', # integer
4311 date => '2004-02-24T17:01:44.108345Z', # commit date
4312 author => 'committer name'
4316 # this is generated by generate_diff();
4317 @mods = array of diff-index line hashes, each element represents one line
4318 of diff-index output
4320 diff-index line ($m hash)
4322 mode_a => first column of diff-index output, no leading ':',
4323 mode_b => second column of diff-index output,
4324 sha1_b => sha1sum of the final blob,
4325 chg => change type [MCRADT],
4326 file_a => original file name of a file (iff chg is 'C' or 'R')
4327 file_b => new/current file name of a file (any chg)
4331 # retval of read_url_paths{,_all}();
4332 $l_map = {
4333 # repository root url
4334 'https://svn.musicpd.org' => {
4335 # repository path # GIT_SVN_ID
4336 'mpd/trunk' => 'trunk',
4337 'mpd/tags/0.11.5' => 'tags/0.11.5',
4341 Notes:
4342 I don't trust the each() function on unless I created %hash myself
4343 because the internal iterator may not have started at base.