blame: check return value from read_sha1_file()
[git/gitweb.git] / git-svn.perl
blob4e325b771ba136e40b9a420e16f043fbaf5d7bb7
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41 # import functions from Git into our packages, en masse
42 no strict 'refs';
43 foreach (qw/command command_oneline command_noisy command_output_pipe
44 command_input_pipe command_close_pipe/) {
45 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
46 Git::SVN::Migration Git::SVN::Log Git::SVN),
47 __PACKAGE__) {
48 *{"${package}::$_"} = \&{"Git::$_"};
53 my ($SVN);
55 $sha1 = qr/[a-f\d]{40}/;
56 $sha1_short = qr/[a-f\d]{4,40}/;
57 my ($_stdin, $_help, $_edit,
58 $_message, $_file,
59 $_template, $_shared,
60 $_version, $_fetch_all, $_no_rebase,
61 $_merge, $_strategy, $_dry_run, $_local,
62 $_prefix, $_no_checkout, $_verbose);
63 $Git::SVN::_follow_parent = 1;
64 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
65 'config-dir=s' => \$Git::SVN::Ra::config_dir,
66 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
67 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
68 'authors-file|A=s' => \$_authors,
69 'repack:i' => \$Git::SVN::_repack,
70 'noMetadata' => \$Git::SVN::_no_metadata,
71 'useSvmProps' => \$Git::SVN::_use_svm_props,
72 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
73 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
74 'no-checkout' => \$_no_checkout,
75 'quiet|q' => \$_q,
76 'repack-flags|repack-args|repack-opts=s' =>
77 \$Git::SVN::_repack_flags,
78 %remote_opts );
80 my ($_trunk, $_tags, $_branches, $_stdlayout);
81 my %icv;
82 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
83 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
84 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
85 'stdlayout|s' => \$_stdlayout,
86 'minimize-url|m' => \$Git::SVN::_minimize_url,
87 'no-metadata' => sub { $icv{noMetadata} = 1 },
88 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
89 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
90 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
91 %remote_opts );
92 my %cmt_opts = ( 'edit|e' => \$_edit,
93 'rmdir' => \$SVN::Git::Editor::_rmdir,
94 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
95 'l=i' => \$SVN::Git::Editor::_rename_limit,
96 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
99 my %cmd = (
100 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
101 { 'revision|r=s' => \$_revision,
102 'fetch-all|all' => \$_fetch_all,
103 %fc_opts } ],
104 clone => [ \&cmd_clone, "Initialize and fetch revisions",
105 { 'revision|r=s' => \$_revision,
106 %fc_opts, %init_opts } ],
107 init => [ \&cmd_init, "Initialize a repo for tracking" .
108 " (requires URL argument)",
109 \%init_opts ],
110 'multi-init' => [ \&cmd_multi_init,
111 "Deprecated alias for ".
112 "'$0 init -T<trunk> -b<branches> -t<tags>'",
113 \%init_opts ],
114 dcommit => [ \&cmd_dcommit,
115 'Commit several diffs to merge with upstream',
116 { 'merge|m|M' => \$_merge,
117 'strategy|s=s' => \$_strategy,
118 'verbose|v' => \$_verbose,
119 'dry-run|n' => \$_dry_run,
120 'fetch-all|all' => \$_fetch_all,
121 'no-rebase' => \$_no_rebase,
122 %cmt_opts, %fc_opts } ],
123 'set-tree' => [ \&cmd_set_tree,
124 "Set an SVN repository to a git tree-ish",
125 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
126 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
127 { 'revision|r=i' => \$_revision } ],
128 'multi-fetch' => [ \&cmd_multi_fetch,
129 "Deprecated alias for $0 fetch --all",
130 { 'revision|r=s' => \$_revision, %fc_opts } ],
131 'migrate' => [ sub { },
132 # no-op, we automatically run this anyways,
133 'Migrate configuration/metadata/layout from
134 previous versions of git-svn',
135 { 'minimize' => \$Git::SVN::Migration::_minimize,
136 %remote_opts } ],
137 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
138 { 'limit=i' => \$Git::SVN::Log::limit,
139 'revision|r=s' => \$_revision,
140 'verbose|v' => \$Git::SVN::Log::verbose,
141 'incremental' => \$Git::SVN::Log::incremental,
142 'oneline' => \$Git::SVN::Log::oneline,
143 'show-commit' => \$Git::SVN::Log::show_commit,
144 'non-recursive' => \$Git::SVN::Log::non_recursive,
145 'authors-file|A=s' => \$_authors,
146 'color' => \$Git::SVN::Log::color,
147 'pager=s' => \$Git::SVN::Log::pager,
148 } ],
149 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
150 { } ],
151 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
152 { 'merge|m|M' => \$_merge,
153 'verbose|v' => \$_verbose,
154 'strategy|s=s' => \$_strategy,
155 'local|l' => \$_local,
156 'fetch-all|all' => \$_fetch_all,
157 %fc_opts } ],
158 'commit-diff' => [ \&cmd_commit_diff,
159 'Commit a diff between two trees',
160 { 'message|m=s' => \$_message,
161 'file|F=s' => \$_file,
162 'revision|r=s' => \$_revision,
163 %cmt_opts } ],
166 my $cmd;
167 for (my $i = 0; $i < @ARGV; $i++) {
168 if (defined $cmd{$ARGV[$i]}) {
169 $cmd = $ARGV[$i];
170 splice @ARGV, $i, 1;
171 last;
175 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
177 read_repo_config(\%opts);
178 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
180 'minimize-connections' => \$Git::SVN::Migration::_minimize,
181 'id|i=s' => \$Git::SVN::default_ref_id,
182 'svn-remote|remote|R=s' => sub {
183 $Git::SVN::no_reuse_existing = 1;
184 $Git::SVN::default_repo_id = $_[1] });
185 exit 1 if (!$rv && $cmd && $cmd ne 'log');
187 usage(0) if $_help;
188 version() if $_version;
189 usage(1) unless defined $cmd;
190 load_authors() if $_authors;
192 # make sure we're always running
193 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
194 unless (-d $ENV{GIT_DIR}) {
195 if ($git_dir_user_set) {
196 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
197 "but it is not a directory\n";
199 my $git_dir = delete $ENV{GIT_DIR};
200 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
201 unless (length $cdup) {
202 die "Already at toplevel, but $git_dir ",
203 "not found '$cdup'\n";
205 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
206 unless (-d $git_dir) {
207 die "$git_dir still not found after going to ",
208 "'$cdup'\n";
210 $ENV{GIT_DIR} = $git_dir;
213 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
214 Git::SVN::Migration::migration_check();
216 Git::SVN::init_vars();
217 eval {
218 Git::SVN::verify_remotes_sanity();
219 $cmd{$cmd}->[0]->(@ARGV);
221 fatal $@ if $@;
222 post_fetch_checkout();
223 exit 0;
225 ####################### primary functions ######################
226 sub usage {
227 my $exit = shift || 0;
228 my $fd = $exit ? \*STDERR : \*STDOUT;
229 print $fd <<"";
230 git-svn - bidirectional operations between a single Subversion tree and git
231 Usage: $0 <command> [options] [arguments]\n
233 print $fd "Available commands:\n" unless $cmd;
235 foreach (sort keys %cmd) {
236 next if $cmd && $cmd ne $_;
237 next if /^multi-/; # don't show deprecated commands
238 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
239 foreach (keys %{$cmd{$_}->[2]}) {
240 # mixed-case options are for .git/config only
241 next if /[A-Z]/ && /^[a-z]+$/i;
242 # prints out arguments as they should be passed:
243 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
244 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
245 "--$_" : "-$_" }
246 split /\|/,$_)," $x\n";
249 print $fd <<"";
250 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
251 arbitrary identifier if you're tracking multiple SVN branches/repositories in
252 one git repository and want to keep them separate. See git-svn(1) for more
253 information.
255 exit $exit;
258 sub version {
259 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
260 exit 0;
263 sub do_git_init_db {
264 unless (-d $ENV{GIT_DIR}) {
265 my @init_db = ('init');
266 push @init_db, "--template=$_template" if defined $_template;
267 if (defined $_shared) {
268 if ($_shared =~ /[a-z]/) {
269 push @init_db, "--shared=$_shared";
270 } else {
271 push @init_db, "--shared";
274 command_noisy(@init_db);
276 my $set;
277 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
278 foreach my $i (keys %icv) {
279 die "'$set' and '$i' cannot both be set\n" if $set;
280 next unless defined $icv{$i};
281 command_noisy('config', "$pfx.$i", $icv{$i});
282 $set = $i;
286 sub init_subdir {
287 my $repo_path = shift or return;
288 mkpath([$repo_path]) unless -d $repo_path;
289 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
290 $ENV{GIT_DIR} = '.git';
293 sub cmd_clone {
294 my ($url, $path) = @_;
295 if (!defined $path &&
296 (defined $_trunk || defined $_branches || defined $_tags ||
297 defined $_stdlayout) &&
298 $url !~ m#^[a-z\+]+://#) {
299 $path = $url;
301 $path = basename($url) if !defined $path || !length $path;
302 cmd_init($url, $path);
303 Git::SVN::fetch_all($Git::SVN::default_repo_id);
306 sub cmd_init {
307 if (defined $_stdlayout) {
308 $_trunk = 'trunk' if (!defined $_trunk);
309 $_tags = 'tags' if (!defined $_tags);
310 $_branches = 'branches' if (!defined $_branches);
312 if (defined $_trunk || defined $_branches || defined $_tags) {
313 return cmd_multi_init(@_);
315 my $url = shift or die "SVN repository location required ",
316 "as a command-line argument\n";
317 init_subdir(@_);
318 do_git_init_db();
320 Git::SVN->init($url);
323 sub cmd_fetch {
324 if (grep /^\d+=./, @_) {
325 die "'<rev>=<commit>' fetch arguments are ",
326 "no longer supported.\n";
328 my ($remote) = @_;
329 if (@_ > 1) {
330 die "Usage: $0 fetch [--all] [svn-remote]\n";
332 $remote ||= $Git::SVN::default_repo_id;
333 if ($_fetch_all) {
334 cmd_multi_fetch();
335 } else {
336 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
340 sub cmd_set_tree {
341 my (@commits) = @_;
342 if ($_stdin || !@commits) {
343 print "Reading from stdin...\n";
344 @commits = ();
345 while (<STDIN>) {
346 if (/\b($sha1_short)\b/o) {
347 unshift @commits, $1;
351 my @revs;
352 foreach my $c (@commits) {
353 my @tmp = command('rev-parse',$c);
354 if (scalar @tmp == 1) {
355 push @revs, $tmp[0];
356 } elsif (scalar @tmp > 1) {
357 push @revs, reverse(command('rev-list',@tmp));
358 } else {
359 fatal "Failed to rev-parse $c\n";
362 my $gs = Git::SVN->new;
363 my ($r_last, $cmt_last) = $gs->last_rev_commit;
364 $gs->fetch;
365 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
366 fatal "There are new revisions that were fetched ",
367 "and need to be merged (or acknowledged) ",
368 "before committing.\nlast rev: $r_last\n",
369 " current: $gs->{last_rev}\n";
371 $gs->set_tree($_) foreach @revs;
372 print "Done committing ",scalar @revs," revisions to SVN\n";
375 sub cmd_dcommit {
376 my $head = shift;
377 $head ||= 'HEAD';
378 my @refs;
379 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
380 print "Committing to $url ...\n";
381 unless ($gs) {
382 die "Unable to determine upstream SVN information from ",
383 "$head history\n";
385 my $last_rev;
386 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
387 foreach my $d (@$linear_refs) {
388 unless (defined $last_rev) {
389 (undef, $last_rev, undef) = cmt_metadata("$d~1");
390 unless (defined $last_rev) {
391 fatal "Unable to extract revision information ",
392 "from commit $d~1\n";
395 if ($_dry_run) {
396 print "diff-tree $d~1 $d\n";
397 } else {
398 my %ed_opts = ( r => $last_rev,
399 log => get_commit_entry($d)->{log},
400 ra => Git::SVN::Ra->new($gs->full_url),
401 tree_a => "$d~1",
402 tree_b => $d,
403 editor_cb => sub {
404 print "Committed r$_[0]\n";
405 $last_rev = $_[0]; },
406 svn_path => '');
407 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
408 print "No changes\n$d~1 == $d\n";
409 } elsif ($parents->{$d} && @{$parents->{$d}}) {
410 $gs->{inject_parents_dcommit}->{$last_rev} =
411 $parents->{$d};
415 return if $_dry_run;
416 unless ($gs) {
417 warn "Could not determine fetch information for $url\n",
418 "Will not attempt to fetch and rebase commits.\n",
419 "This probably means you have useSvmProps and should\n",
420 "now resync your SVN::Mirror repository.\n";
421 return;
423 $_fetch_all ? $gs->fetch_all : $gs->fetch;
424 unless ($_no_rebase) {
425 # we always want to rebase against the current HEAD, not any
426 # head that was passed to us
427 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
428 my @finish;
429 if (@diff) {
430 @finish = rebase_cmd();
431 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
432 "using @finish:\n", "@diff";
433 } else {
434 print "No changes between current HEAD and ",
435 $gs->refname, "\nResetting to the latest ",
436 $gs->refname, "\n";
437 @finish = qw/reset --mixed/;
439 command_noisy(@finish, $gs->refname);
443 sub cmd_find_rev {
444 my $revision_or_hash = shift;
445 my $result;
446 if ($revision_or_hash =~ /^r\d+$/) {
447 my $head = shift;
448 $head ||= 'HEAD';
449 my @refs;
450 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
451 unless ($gs) {
452 die "Unable to determine upstream SVN information from ",
453 "$head history\n";
455 my $desired_revision = substr($revision_or_hash, 1);
456 $result = $gs->rev_db_get($desired_revision);
457 } else {
458 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
459 $result = $rev;
461 print "$result\n" if $result;
464 sub cmd_rebase {
465 command_noisy(qw/update-index --refresh/);
466 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
467 unless ($gs) {
468 die "Unable to determine upstream SVN information from ",
469 "working tree history\n";
471 if (command(qw/diff-index HEAD --/)) {
472 print STDERR "Cannot rebase with uncommited changes:\n";
473 command_noisy('status');
474 exit 1;
476 unless ($_local) {
477 $_fetch_all ? $gs->fetch_all : $gs->fetch;
479 command_noisy(rebase_cmd(), $gs->refname);
482 sub cmd_show_ignore {
483 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
484 $gs ||= Git::SVN->new;
485 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
486 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
489 sub cmd_multi_init {
490 my $url = shift;
491 unless (defined $_trunk || defined $_branches || defined $_tags) {
492 usage(1);
495 # there are currently some bugs that prevent multi-init/multi-fetch
496 # setups from working well without this.
497 $Git::SVN::_minimize_url = 1;
499 $_prefix = '' unless defined $_prefix;
500 if (defined $url) {
501 $url =~ s#/+$##;
502 init_subdir(@_);
504 do_git_init_db();
505 if (defined $_trunk) {
506 my $trunk_ref = $_prefix . 'trunk';
507 # try both old-style and new-style lookups:
508 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
509 unless ($gs_trunk) {
510 my ($trunk_url, $trunk_path) =
511 complete_svn_url($url, $_trunk);
512 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
513 undef, $trunk_ref);
516 return unless defined $_branches || defined $_tags;
517 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
518 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
519 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
522 sub cmd_multi_fetch {
523 my $remotes = Git::SVN::read_all_remotes();
524 foreach my $repo_id (sort keys %$remotes) {
525 if ($remotes->{$repo_id}->{url}) {
526 Git::SVN::fetch_all($repo_id, $remotes);
531 # this command is special because it requires no metadata
532 sub cmd_commit_diff {
533 my ($ta, $tb, $url) = @_;
534 my $usage = "Usage: $0 commit-diff -r<revision> ".
535 "<tree-ish> <tree-ish> [<URL>]\n";
536 fatal($usage) if (!defined $ta || !defined $tb);
537 my $svn_path;
538 if (!defined $url) {
539 my $gs = eval { Git::SVN->new };
540 if (!$gs) {
541 fatal("Needed URL or usable git-svn --id in ",
542 "the command-line\n", $usage);
544 $url = $gs->{url};
545 $svn_path = $gs->{path};
547 unless (defined $_revision) {
548 fatal("-r|--revision is a required argument\n", $usage);
550 if (defined $_message && defined $_file) {
551 fatal("Both --message/-m and --file/-F specified ",
552 "for the commit message.\n",
553 "I have no idea what you mean\n");
555 if (defined $_file) {
556 $_message = file_to_s($_file);
557 } else {
558 $_message ||= get_commit_entry($tb)->{log};
560 my $ra ||= Git::SVN::Ra->new($url);
561 $svn_path ||= $ra->{svn_path};
562 my $r = $_revision;
563 if ($r eq 'HEAD') {
564 $r = $ra->get_latest_revnum;
565 } elsif ($r !~ /^\d+$/) {
566 die "revision argument: $r not understood by git-svn\n";
568 my %ed_opts = ( r => $r,
569 log => $_message,
570 ra => $ra,
571 tree_a => $ta,
572 tree_b => $tb,
573 editor_cb => sub { print "Committed r$_[0]\n" },
574 svn_path => $svn_path );
575 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
576 print "No changes\n$ta == $tb\n";
580 ########################### utility functions #########################
582 sub rebase_cmd {
583 my @cmd = qw/rebase/;
584 push @cmd, '-v' if $_verbose;
585 push @cmd, qw/--merge/ if $_merge;
586 push @cmd, "--strategy=$_strategy" if $_strategy;
587 @cmd;
590 sub post_fetch_checkout {
591 return if $_no_checkout;
592 my $gs = $Git::SVN::_head or return;
593 return if verify_ref('refs/heads/master^0');
595 my $valid_head = verify_ref('HEAD^0');
596 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
597 return if ($valid_head || !verify_ref('HEAD^0'));
599 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
600 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
601 return if -f $index;
603 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
604 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
605 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
606 print STDERR "Checked out HEAD:\n ",
607 $gs->full_url, " r", $gs->last_rev, "\n";
610 sub complete_svn_url {
611 my ($url, $path) = @_;
612 $path =~ s#/+$##;
613 if ($path !~ m#^[a-z\+]+://#) {
614 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
615 fatal("E: '$path' is not a complete URL ",
616 "and a separate URL is not specified\n");
618 return ($url, $path);
620 return ($path, '');
623 sub complete_url_ls_init {
624 my ($ra, $repo_path, $switch, $pfx) = @_;
625 unless ($repo_path) {
626 print STDERR "W: $switch not specified\n";
627 return;
629 $repo_path =~ s#/+$##;
630 if ($repo_path =~ m#^[a-z\+]+://#) {
631 $ra = Git::SVN::Ra->new($repo_path);
632 $repo_path = '';
633 } else {
634 $repo_path =~ s#^/+##;
635 unless ($ra) {
636 fatal("E: '$repo_path' is not a complete URL ",
637 "and a separate URL is not specified\n");
640 my $url = $ra->{url};
641 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
642 my $k = "svn-remote.$gs->{repo_id}.url";
643 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
644 if ($orig_url && ($orig_url ne $gs->{url})) {
645 die "$k already set: $orig_url\n",
646 "wanted to set to: $gs->{url}\n";
648 command_oneline('config', $k, $gs->{url}) unless $orig_url;
649 my $remote_path = "$ra->{svn_path}/$repo_path/*";
650 $remote_path =~ s#/+#/#g;
651 $remote_path =~ s#^/##g;
652 my ($n) = ($switch =~ /^--(\w+)/);
653 if (length $pfx && $pfx !~ m#/$#) {
654 die "--prefix='$pfx' must have a trailing slash '/'\n";
656 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
657 "$remote_path:refs/remotes/$pfx*");
660 sub verify_ref {
661 my ($ref) = @_;
662 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
663 { STDERR => 0 }); };
666 sub get_tree_from_treeish {
667 my ($treeish) = @_;
668 # $treeish can be a symbolic ref, too:
669 my $type = command_oneline(qw/cat-file -t/, $treeish);
670 my $expected;
671 while ($type eq 'tag') {
672 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
674 if ($type eq 'commit') {
675 $expected = (grep /^tree /, command(qw/cat-file commit/,
676 $treeish))[0];
677 ($expected) = ($expected =~ /^tree ($sha1)$/o);
678 die "Unable to get tree from $treeish\n" unless $expected;
679 } elsif ($type eq 'tree') {
680 $expected = $treeish;
681 } else {
682 die "$treeish is a $type, expected tree, tag or commit\n";
684 return $expected;
687 sub get_commit_entry {
688 my ($treeish) = shift;
689 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
690 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
691 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
692 open my $log_fh, '>', $commit_editmsg or croak $!;
694 my $type = command_oneline(qw/cat-file -t/, $treeish);
695 if ($type eq 'commit' || $type eq 'tag') {
696 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
697 $type, $treeish);
698 my $in_msg = 0;
699 while (<$msg_fh>) {
700 if (!$in_msg) {
701 $in_msg = 1 if (/^\s*$/);
702 } elsif (/^git-svn-id: /) {
703 # skip this for now, we regenerate the
704 # correct one on re-fetch anyways
705 # TODO: set *:merge properties or like...
706 } else {
707 print $log_fh $_ or croak $!;
710 command_close_pipe($msg_fh, $ctx);
712 close $log_fh or croak $!;
714 if ($_edit || ($type eq 'tree')) {
715 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
716 # TODO: strip out spaces, comments, like git-commit.sh
717 system($editor, $commit_editmsg);
719 rename $commit_editmsg, $commit_msg or croak $!;
720 open $log_fh, '<', $commit_msg or croak $!;
721 { local $/; chomp($log_entry{log} = <$log_fh>); }
722 close $log_fh or croak $!;
723 unlink $commit_msg;
724 \%log_entry;
727 sub s_to_file {
728 my ($str, $file, $mode) = @_;
729 open my $fd,'>',$file or croak $!;
730 print $fd $str,"\n" or croak $!;
731 close $fd or croak $!;
732 chmod ($mode &~ umask, $file) if (defined $mode);
735 sub file_to_s {
736 my $file = shift;
737 open my $fd,'<',$file or croak "$!: file: $file\n";
738 local $/;
739 my $ret = <$fd>;
740 close $fd or croak $!;
741 $ret =~ s/\s*$//s;
742 return $ret;
745 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
746 sub load_authors {
747 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
748 my $log = $cmd eq 'log';
749 while (<$authors>) {
750 chomp;
751 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
752 my ($user, $name, $email) = ($1, $2, $3);
753 if ($log) {
754 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
755 } else {
756 $users{$user} = [$name, $email];
759 close $authors or croak $!;
762 # convert GetOpt::Long specs for use by git-config
763 sub read_repo_config {
764 return unless -d $ENV{GIT_DIR};
765 my $opts = shift;
766 my @config_only;
767 foreach my $o (keys %$opts) {
768 # if we have mixedCase and a long option-only, then
769 # it's a config-only variable that we don't need for
770 # the command-line.
771 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
772 my $v = $opts->{$o};
773 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
774 $key =~ s/-//g;
775 my $arg = 'git-config';
776 $arg .= ' --int' if ($o =~ /[:=]i$/);
777 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
778 if (ref $v eq 'ARRAY') {
779 chomp(my @tmp = `$arg --get-all svn.$key`);
780 @$v = @tmp if @tmp;
781 } else {
782 chomp(my $tmp = `$arg --get svn.$key`);
783 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
784 $$v = $tmp;
788 delete @$opts{@config_only} if @config_only;
791 sub extract_metadata {
792 my $id = shift or return (undef, undef, undef);
793 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
794 \s([a-f\d\-]+)$/x);
795 if (!defined $rev || !$uuid || !$url) {
796 # some of the original repositories I made had
797 # identifiers like this:
798 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
800 return ($url, $rev, $uuid);
803 sub cmt_metadata {
804 return extract_metadata((grep(/^git-svn-id: /,
805 command(qw/cat-file commit/, shift)))[-1]);
808 sub working_head_info {
809 my ($head, $refs) = @_;
810 my ($fh, $ctx) = command_output_pipe('log', $head);
811 my $hash;
812 my %max;
813 while (<$fh>) {
814 if ( m{^commit ($::sha1)$} ) {
815 unshift @$refs, $hash if $hash and $refs;
816 $hash = $1;
817 next;
819 next unless s{^\s*(git-svn-id:)}{$1};
820 my ($url, $rev, $uuid) = extract_metadata($_);
821 if (defined $url && defined $rev) {
822 next if $max{$url} and $max{$url} < $rev;
823 if (my $gs = Git::SVN->find_by_url($url)) {
824 my $c = $gs->rev_db_get($rev);
825 if ($c && $c eq $hash) {
826 close $fh; # break the pipe
827 return ($url, $rev, $uuid, $gs);
828 } else {
829 $max{$url} ||= $gs->rev_db_max;
834 command_close_pipe($fh, $ctx);
835 (undef, undef, undef, undef);
838 sub read_commit_parents {
839 my ($parents, $c) = @_;
840 my ($fh, $ctx) = command_output_pipe(qw/cat-file commit/, $c);
841 while (<$fh>) {
842 chomp;
843 last if '';
844 /^parent ($sha1)/ or next;
845 push @{$parents->{$c}}, $1;
847 close $fh; # break the pipe
850 sub linearize_history {
851 my ($gs, $refs) = @_;
852 my %parents;
853 foreach my $c (@$refs) {
854 read_commit_parents(\%parents, $c);
857 my @linear_refs;
858 my %skip = ();
859 my $last_svn_commit = $gs->last_commit;
860 foreach my $c (reverse @$refs) {
861 next if $c eq $last_svn_commit;
862 last if $skip{$c};
864 unshift @linear_refs, $c;
865 $skip{$c} = 1;
867 # we only want the first parent to diff against for linear
868 # history, we save the rest to inject when we finalize the
869 # svn commit
870 my $fp_a = verify_ref("$c~1");
871 my $fp_b = shift @{$parents{$c}} if $parents{$c};
872 if (!$fp_a || !$fp_b) {
873 die "Commit $c\n",
874 "has no parent commit, and therefore ",
875 "nothing to diff against.\n",
876 "You should be working from a repository ",
877 "originally created by git-svn\n";
879 if ($fp_a ne $fp_b) {
880 die "$c~1 = $fp_a, however parsing commit $c ",
881 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
884 foreach my $p (@{$parents{$c}}) {
885 $skip{$p} = 1;
888 (\@linear_refs, \%parents);
891 package Git::SVN;
892 use strict;
893 use warnings;
894 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
895 $_repack $_repack_flags $_use_svm_props $_head
896 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
897 use Carp qw/croak/;
898 use File::Path qw/mkpath/;
899 use File::Copy qw/copy/;
900 use IPC::Open3;
902 my $_repack_nr;
903 # properties that we do not log:
904 my %SKIP_PROP;
905 BEGIN {
906 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
907 svn:special svn:executable
908 svn:entry:committed-rev
909 svn:entry:last-author
910 svn:entry:uuid
911 svn:entry:committed-date/;
913 # some options are read globally, but can be overridden locally
914 # per [svn-remote "..."] section. Command-line options will *NOT*
915 # override options set in an [svn-remote "..."] section
916 no strict 'refs';
917 for my $option (qw/follow_parent no_metadata use_svm_props
918 use_svnsync_props/) {
919 my $key = $option;
920 $key =~ tr/_//d;
921 my $prop = "-$option";
922 *$option = sub {
923 my ($self) = @_;
924 return $self->{$prop} if exists $self->{$prop};
925 my $k = "svn-remote.$self->{repo_id}.$key";
926 eval { command_oneline(qw/config --get/, $k) };
927 if ($@) {
928 $self->{$prop} = ${"Git::SVN::_$option"};
929 } else {
930 my $v = command_oneline(qw/config --bool/,$k);
931 $self->{$prop} = $v eq 'false' ? 0 : 1;
933 return $self->{$prop};
938 my %LOCKFILES;
939 END { unlink keys %LOCKFILES if %LOCKFILES }
941 sub resolve_local_globs {
942 my ($url, $fetch, $glob_spec) = @_;
943 return unless defined $glob_spec;
944 my $ref = $glob_spec->{ref};
945 my $path = $glob_spec->{path};
946 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
947 next unless m#^refs/remotes/$ref->{regex}$#;
948 my $p = $1;
949 my $pathname = desanitize_refname($path->full_path($p));
950 my $refname = desanitize_refname($ref->full_path($p));
951 if (my $existing = $fetch->{$pathname}) {
952 if ($existing ne $refname) {
953 die "Refspec conflict:\n",
954 "existing: refs/remotes/$existing\n",
955 " globbed: refs/remotes/$refname\n";
957 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
958 $u =~ s!^\Q$url\E(/|$)!! or die
959 "refs/remotes/$refname: '$url' not found in '$u'\n";
960 if ($pathname ne $u) {
961 warn "W: Refspec glob conflict ",
962 "(ref: refs/remotes/$refname):\n",
963 "expected path: $pathname\n",
964 " real path: $u\n",
965 "Continuing ahead with $u\n";
966 next;
968 } else {
969 $fetch->{$pathname} = $refname;
974 sub parse_revision_argument {
975 my ($base, $head) = @_;
976 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
977 return ($base, $head);
979 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
980 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
981 return ($head, $head) if ($::_revision eq 'HEAD');
982 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
983 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
984 die "revision argument: $::_revision not understood by git-svn\n";
987 sub fetch_all {
988 my ($repo_id, $remotes) = @_;
989 if (ref $repo_id) {
990 my $gs = $repo_id;
991 $repo_id = undef;
992 $repo_id = $gs->{repo_id};
994 $remotes ||= read_all_remotes();
995 my $remote = $remotes->{$repo_id} or
996 die "[svn-remote \"$repo_id\"] unknown\n";
997 my $fetch = $remote->{fetch};
998 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
999 my (@gs, @globs);
1000 my $ra = Git::SVN::Ra->new($url);
1001 my $uuid = $ra->get_uuid;
1002 my $head = $ra->get_latest_revnum;
1003 my $base = defined $fetch ? $head : 0;
1005 # read the max revs for wildcard expansion (branches/*, tags/*)
1006 foreach my $t (qw/branches tags/) {
1007 defined $remote->{$t} or next;
1008 push @globs, $remote->{$t};
1009 my $max_rev = eval { tmp_config(qw/--int --get/,
1010 "svn-remote.$repo_id.${t}-maxRev") };
1011 if (defined $max_rev && ($max_rev < $base)) {
1012 $base = $max_rev;
1013 } elsif (!defined $max_rev) {
1014 $base = 0;
1018 if ($fetch) {
1019 foreach my $p (sort keys %$fetch) {
1020 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1021 my $lr = $gs->rev_db_max;
1022 if (defined $lr) {
1023 $base = $lr if ($lr < $base);
1025 push @gs, $gs;
1029 ($base, $head) = parse_revision_argument($base, $head);
1030 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1033 sub read_all_remotes {
1034 my $r = {};
1035 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1036 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1037 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1038 $local_ref =~ s{^/}{};
1039 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1040 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1041 $r->{$1}->{url} = $2;
1042 } elsif (m!^(.+)\.(branches|tags)=
1043 (.*):refs/remotes/(.+)\s*$/!x) {
1044 my ($p, $g) = ($3, $4);
1045 my $rs = $r->{$1}->{$2} = {
1046 t => $2,
1047 remote => $1,
1048 path => Git::SVN::GlobSpec->new($p),
1049 ref => Git::SVN::GlobSpec->new($g) };
1050 if (length($rs->{ref}->{right}) != 0) {
1051 die "The '*' glob character must be the last ",
1052 "character of '$g'\n";
1059 sub init_vars {
1060 if (defined $_repack) {
1061 $_repack = 1000 if ($_repack <= 0);
1062 $_repack_nr = $_repack;
1063 $_repack_flags ||= '-d';
1067 sub verify_remotes_sanity {
1068 return unless -d $ENV{GIT_DIR};
1069 my %seen;
1070 foreach (command(qw/config -l/)) {
1071 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1072 if ($seen{$1}) {
1073 die "Remote ref refs/remote/$1 is tracked by",
1074 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1075 "Please resolve this ambiguity in ",
1076 "your git configuration file before ",
1077 "continuing\n";
1079 $seen{$1} = $_;
1084 # we allow more chars than remotes2config.sh...
1085 sub sanitize_remote_name {
1086 my ($name) = @_;
1087 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1088 $name;
1091 sub find_existing_remote {
1092 my ($url, $remotes) = @_;
1093 return undef if $no_reuse_existing;
1094 my $existing;
1095 foreach my $repo_id (keys %$remotes) {
1096 my $u = $remotes->{$repo_id}->{url} or next;
1097 next if $u ne $url;
1098 $existing = $repo_id;
1099 last;
1101 $existing;
1104 sub init_remote_config {
1105 my ($self, $url, $no_write) = @_;
1106 $url =~ s!/+$!!; # strip trailing slash
1107 my $r = read_all_remotes();
1108 my $existing = find_existing_remote($url, $r);
1109 if ($existing) {
1110 unless ($no_write) {
1111 print STDERR "Using existing ",
1112 "[svn-remote \"$existing\"]\n";
1114 $self->{repo_id} = $existing;
1115 } elsif ($_minimize_url) {
1116 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1117 $existing = find_existing_remote($min_url, $r);
1118 if ($existing) {
1119 unless ($no_write) {
1120 print STDERR "Using existing ",
1121 "[svn-remote \"$existing\"]\n";
1123 $self->{repo_id} = $existing;
1125 if ($min_url ne $url) {
1126 unless ($no_write) {
1127 print STDERR "Using higher level of URL: ",
1128 "$url => $min_url\n";
1130 my $old_path = $self->{path};
1131 $self->{path} = $url;
1132 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1133 if (length $old_path) {
1134 $self->{path} .= "/$old_path";
1136 $url = $min_url;
1139 my $orig_url;
1140 if (!$existing) {
1141 # verify that we aren't overwriting anything:
1142 $orig_url = eval {
1143 command_oneline('config', '--get',
1144 "svn-remote.$self->{repo_id}.url")
1146 if ($orig_url && ($orig_url ne $url)) {
1147 die "svn-remote.$self->{repo_id}.url already set: ",
1148 "$orig_url\nwanted to set to: $url\n";
1151 my ($xrepo_id, $xpath) = find_ref($self->refname);
1152 if (defined $xpath) {
1153 die "svn-remote.$xrepo_id.fetch already set to track ",
1154 "$xpath:refs/remotes/", $self->refname, "\n";
1156 unless ($no_write) {
1157 command_noisy('config',
1158 "svn-remote.$self->{repo_id}.url", $url);
1159 $self->{path} =~ s{^/}{};
1160 command_noisy('config', '--add',
1161 "svn-remote.$self->{repo_id}.fetch",
1162 "$self->{path}:".$self->refname);
1164 $self->{url} = $url;
1167 sub find_by_url { # repos_root and, path are optional
1168 my ($class, $full_url, $repos_root, $path) = @_;
1170 return undef unless defined $full_url;
1171 remove_username($full_url);
1172 remove_username($repos_root) if defined $repos_root;
1173 my $remotes = read_all_remotes();
1174 if (defined $full_url && defined $repos_root && !defined $path) {
1175 $path = $full_url;
1176 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1178 foreach my $repo_id (keys %$remotes) {
1179 my $u = $remotes->{$repo_id}->{url} or next;
1180 remove_username($u);
1181 next if defined $repos_root && $repos_root ne $u;
1183 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1184 foreach (qw/branches tags/) {
1185 resolve_local_globs($u, $fetch,
1186 $remotes->{$repo_id}->{$_});
1188 my $p = $path;
1189 unless (defined $p) {
1190 $p = $full_url;
1191 $p =~ s#^\Q$u\E(?:/|$)## or next;
1193 foreach my $f (keys %$fetch) {
1194 next if $f ne $p;
1195 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1198 undef;
1201 sub init {
1202 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1203 my $self = _new($class, $repo_id, $ref_id, $path);
1204 if (defined $url) {
1205 $self->init_remote_config($url, $no_write);
1207 $self;
1210 sub find_ref {
1211 my ($ref_id) = @_;
1212 foreach (command(qw/config -l/)) {
1213 next unless m!^svn-remote\.(.+)\.fetch=
1214 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1215 my ($repo_id, $path, $ref) = ($1, $2, $3);
1216 if ($ref eq $ref_id) {
1217 $path = '' if ($path =~ m#^\./?#);
1218 return ($repo_id, $path);
1221 (undef, undef, undef);
1224 sub new {
1225 my ($class, $ref_id, $repo_id, $path) = @_;
1226 if (defined $ref_id && !defined $repo_id && !defined $path) {
1227 ($repo_id, $path) = find_ref($ref_id);
1228 if (!defined $repo_id) {
1229 die "Could not find a \"svn-remote.*.fetch\" key ",
1230 "in the repository configuration matching: ",
1231 "refs/remotes/$ref_id\n";
1234 my $self = _new($class, $repo_id, $ref_id, $path);
1235 if (!defined $self->{path} || !length $self->{path}) {
1236 my $fetch = command_oneline('config', '--get',
1237 "svn-remote.$repo_id.fetch",
1238 ":refs/remotes/$ref_id\$") or
1239 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1240 "\":refs/remotes/$ref_id\$\" in config\n";
1241 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1243 $self->{url} = command_oneline('config', '--get',
1244 "svn-remote.$repo_id.url") or
1245 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1246 $self->rebuild;
1247 $self;
1250 sub refname {
1251 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1253 # It cannot end with a slash /, we'll throw up on this because
1254 # SVN can't have directories with a slash in their name, either:
1255 if ($refname =~ m{/$}) {
1256 die "ref: '$refname' ends with a trailing slash, this is ",
1257 "not permitted by git nor Subversion\n";
1260 # It cannot have ASCII control character space, tilde ~, caret ^,
1261 # colon :, question-mark ?, asterisk *, space, or open bracket [
1262 # anywhere.
1264 # Additionally, % must be escaped because it is used for escaping
1265 # and we want our escaped refname to be reversible
1266 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1268 # no slash-separated component can begin with a dot .
1269 # /.* becomes /%2E*
1270 $refname =~ s{/\.}{/%2E}g;
1272 # It cannot have two consecutive dots .. anywhere
1273 # .. becomes %2E%2E
1274 $refname =~ s{\.\.}{%2E%2E}g;
1276 return $refname;
1279 sub desanitize_refname {
1280 my ($refname) = @_;
1281 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1282 return $refname;
1285 sub svm_uuid {
1286 my ($self) = @_;
1287 return $self->{svm}->{uuid} if $self->svm;
1288 $self->ra;
1289 unless ($self->{svm}) {
1290 die "SVM UUID not cached, and reading remotely failed\n";
1292 $self->{svm}->{uuid};
1295 sub svm {
1296 my ($self) = @_;
1297 return $self->{svm} if $self->{svm};
1298 my $svm;
1299 # see if we have it in our config, first:
1300 eval {
1301 my $section = "svn-remote.$self->{repo_id}";
1302 $svm = {
1303 source => tmp_config('--get', "$section.svm-source"),
1304 uuid => tmp_config('--get', "$section.svm-uuid"),
1305 replace => tmp_config('--get', "$section.svm-replace"),
1308 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1309 $self->{svm} = $svm;
1311 $self->{svm};
1314 sub _set_svm_vars {
1315 my ($self, $ra) = @_;
1316 return $ra if $self->svm;
1318 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1319 "(svm:source, svm:uuid) ",
1320 "from the following URLs:\n" );
1321 sub read_svm_props {
1322 my ($self, $ra, $path, $r) = @_;
1323 my $props = ($ra->get_dir($path, $r))[2];
1324 my $src = $props->{'svm:source'};
1325 my $uuid = $props->{'svm:uuid'};
1326 return undef if (!$src || !$uuid);
1328 chomp($src, $uuid);
1330 $uuid =~ m{^[0-9a-f\-]{30,}$}
1331 or die "doesn't look right - svm:uuid is '$uuid'\n";
1333 # the '!' is used to mark the repos_root!/relative/path
1334 $src =~ s{/?!/?}{/};
1335 $src =~ s{/+$}{}; # no trailing slashes please
1336 # username is of no interest
1337 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1339 my $replace = $ra->{url};
1340 $replace .= "/$path" if length $path;
1342 my $section = "svn-remote.$self->{repo_id}";
1343 tmp_config("$section.svm-source", $src);
1344 tmp_config("$section.svm-replace", $replace);
1345 tmp_config("$section.svm-uuid", $uuid);
1346 $self->{svm} = {
1347 source => $src,
1348 uuid => $uuid,
1349 replace => $replace
1353 my $r = $ra->get_latest_revnum;
1354 my $path = $self->{path};
1355 my %tried;
1356 while (length $path) {
1357 unless ($tried{"$self->{url}/$path"}) {
1358 return $ra if $self->read_svm_props($ra, $path, $r);
1359 $tried{"$self->{url}/$path"} = 1;
1361 $path =~ s#/?[^/]+$##;
1363 die "Path: '$path' should be ''\n" if $path ne '';
1364 return $ra if $self->read_svm_props($ra, $path, $r);
1365 $tried{"$self->{url}/$path"} = 1;
1367 if ($ra->{repos_root} eq $self->{url}) {
1368 die @err, (map { " $_\n" } keys %tried), "\n";
1371 # nope, make sure we're connected to the repository root:
1372 my $ok;
1373 my @tried_b;
1374 $path = $ra->{svn_path};
1375 $ra = Git::SVN::Ra->new($ra->{repos_root});
1376 while (length $path) {
1377 unless ($tried{"$ra->{url}/$path"}) {
1378 $ok = $self->read_svm_props($ra, $path, $r);
1379 last if $ok;
1380 $tried{"$ra->{url}/$path"} = 1;
1382 $path =~ s#/?[^/]+$##;
1384 die "Path: '$path' should be ''\n" if $path ne '';
1385 $ok ||= $self->read_svm_props($ra, $path, $r);
1386 $tried{"$ra->{url}/$path"} = 1;
1387 if (!$ok) {
1388 die @err, (map { " $_\n" } keys %tried), "\n";
1390 Git::SVN::Ra->new($self->{url});
1393 sub svnsync {
1394 my ($self) = @_;
1395 return $self->{svnsync} if $self->{svnsync};
1397 if ($self->no_metadata) {
1398 die "Can't have both 'noMetadata' and ",
1399 "'useSvnsyncProps' options set!\n";
1401 if ($self->rewrite_root) {
1402 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1403 "options set!\n";
1406 my $svnsync;
1407 # see if we have it in our config, first:
1408 eval {
1409 my $section = "svn-remote.$self->{repo_id}";
1410 $svnsync = {
1411 url => tmp_config('--get', "$section.svnsync-url"),
1412 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1415 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1416 return $self->{svnsync} = $svnsync;
1419 my $err = "useSvnsyncProps set, but failed to read " .
1420 "svnsync property: svn:sync-from-";
1421 my $rp = $self->ra->rev_proplist(0);
1423 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1424 $url =~ m{^[a-z\+]+://} or
1425 die "doesn't look right - svn:sync-from-url is '$url'\n";
1427 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1428 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1429 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1431 my $section = "svn-remote.$self->{repo_id}";
1432 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1433 tmp_config('--add', "$section.svnsync-url", $url);
1434 return $self->{svnsync} = { url => $url, uuid => $uuid };
1437 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1438 # remote lookup (useful for 'git svn log').
1439 sub ra_uuid {
1440 my ($self) = @_;
1441 unless ($self->{ra_uuid}) {
1442 my $key = "svn-remote.$self->{repo_id}.uuid";
1443 my $uuid = eval { tmp_config('--get', $key) };
1444 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1445 $self->{ra_uuid} = $uuid;
1446 } else {
1447 die "ra_uuid called without URL\n" unless $self->{url};
1448 $self->{ra_uuid} = $self->ra->get_uuid;
1449 tmp_config('--add', $key, $self->{ra_uuid});
1452 $self->{ra_uuid};
1455 sub ra {
1456 my ($self) = shift;
1457 my $ra = Git::SVN::Ra->new($self->{url});
1458 if ($self->use_svm_props && !$self->{svm}) {
1459 if ($self->no_metadata) {
1460 die "Can't have both 'noMetadata' and ",
1461 "'useSvmProps' options set!\n";
1462 } elsif ($self->use_svnsync_props) {
1463 die "Can't have both 'useSvnsyncProps' and ",
1464 "'useSvmProps' options set!\n";
1466 $ra = $self->_set_svm_vars($ra);
1467 $self->{-want_revprops} = 1;
1469 $ra;
1472 sub rel_path {
1473 my ($self) = @_;
1474 my $repos_root = $self->ra->{repos_root};
1475 return $self->{path} if ($self->{url} eq $repos_root);
1476 my $url = $self->{url} .
1477 (length $self->{path} ? "/$self->{path}" : $self->{path});
1478 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1479 $url;
1482 sub traverse_ignore {
1483 my ($self, $fh, $path, $r) = @_;
1484 $path =~ s#^/+##g;
1485 my $ra = $self->ra;
1486 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1487 my $p = $path;
1488 $p =~ s#^\Q$self->{path}\E(/|$)##;
1489 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1490 if (my $s = $props->{'svn:ignore'}) {
1491 $s =~ s/[\r\n]+/\n/g;
1492 chomp $s;
1493 if (length $p == 0) {
1494 $s =~ s#\n#\n/$p#g;
1495 print $fh "/$s\n";
1496 } else {
1497 $s =~ s#\n#\n/$p/#g;
1498 print $fh "/$p/$s\n";
1501 foreach (sort keys %$dirent) {
1502 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1503 $self->traverse_ignore($fh, "$path/$_", $r);
1507 sub last_rev { ($_[0]->last_rev_commit)[0] }
1508 sub last_commit { ($_[0]->last_rev_commit)[1] }
1510 # returns the newest SVN revision number and newest commit SHA1
1511 sub last_rev_commit {
1512 my ($self) = @_;
1513 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1514 return ($self->{last_rev}, $self->{last_commit});
1516 my $c = ::verify_ref($self->refname.'^0');
1517 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1518 my $rev = (::cmt_metadata($c))[1];
1519 if (defined $rev) {
1520 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1521 return ($rev, $c);
1524 my $db_path = $self->db_path;
1525 unless (-e $db_path) {
1526 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1527 return (undef, undef);
1529 my $offset = -41; # from tail
1530 my $rl;
1531 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1532 sysseek($fh, $offset, 2); # don't care for errors
1533 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1534 chomp $rl;
1535 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1536 $offset -= 41;
1537 sysseek($fh, $offset, 2); # don't care for errors
1538 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1539 chomp $rl;
1541 if ($c && $c ne $rl) {
1542 die "$db_path and ", $self->refname,
1543 " inconsistent!:\n$c != $rl\n";
1545 my $rev = sysseek($fh, 0, 1) or croak $!;
1546 $rev = ($rev - 41) / 41;
1547 close $fh or croak $!;
1548 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1549 return ($rev, $c);
1552 sub get_fetch_range {
1553 my ($self, $min, $max) = @_;
1554 $max ||= $self->ra->get_latest_revnum;
1555 $min ||= $self->rev_db_max;
1556 (++$min, $max);
1559 sub tmp_config {
1560 my (@args) = @_;
1561 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1562 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1563 if (! -f $config && -f $old_def_config) {
1564 rename $old_def_config, $config or
1565 die "Failed rename $old_def_config => $config: $!\n";
1567 my $old_config = $ENV{GIT_CONFIG};
1568 $ENV{GIT_CONFIG} = $config;
1569 $@ = undef;
1570 my @ret = eval {
1571 unless (-f $config) {
1572 mkfile($config);
1573 open my $fh, '>', $config or
1574 die "Can't open $config: $!\n";
1575 print $fh "; This file is used internally by ",
1576 "git-svn\n" or die
1577 "Couldn't write to $config: $!\n";
1578 print $fh "; You should not have to edit it\n" or
1579 die "Couldn't write to $config: $!\n";
1580 close $fh or die "Couldn't close $config: $!\n";
1582 command('config', @args);
1584 my $err = $@;
1585 if (defined $old_config) {
1586 $ENV{GIT_CONFIG} = $old_config;
1587 } else {
1588 delete $ENV{GIT_CONFIG};
1590 die $err if $err;
1591 wantarray ? @ret : $ret[0];
1594 sub tmp_index_do {
1595 my ($self, $sub) = @_;
1596 my $old_index = $ENV{GIT_INDEX_FILE};
1597 $ENV{GIT_INDEX_FILE} = $self->{index};
1598 $@ = undef;
1599 my @ret = eval {
1600 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1601 mkpath([$dir]) unless -d $dir;
1602 &$sub;
1604 my $err = $@;
1605 if (defined $old_index) {
1606 $ENV{GIT_INDEX_FILE} = $old_index;
1607 } else {
1608 delete $ENV{GIT_INDEX_FILE};
1610 die $err if $err;
1611 wantarray ? @ret : $ret[0];
1614 sub assert_index_clean {
1615 my ($self, $treeish) = @_;
1617 $self->tmp_index_do(sub {
1618 command_noisy('read-tree', $treeish) unless -e $self->{index};
1619 my $x = command_oneline('write-tree');
1620 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1621 /^tree ($::sha1)/mo);
1622 return if $y eq $x;
1624 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1625 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1626 command_noisy('read-tree', $treeish);
1627 $x = command_oneline('write-tree');
1628 if ($y ne $x) {
1629 ::fatal "trees ($treeish) $y != $x\n",
1630 "Something is seriously wrong...\n";
1635 sub get_commit_parents {
1636 my ($self, $log_entry) = @_;
1637 my (%seen, @ret, @tmp);
1638 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1639 if (my $ip = $self->{inject_parents}) {
1640 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1641 push @tmp, $commit;
1644 if (my $cur = ::verify_ref($self->refname.'^0')) {
1645 push @tmp, $cur;
1647 if (my $ipd = $self->{inject_parents_dcommit}) {
1648 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1649 push @tmp, @$commit;
1652 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1653 while (my $p = shift @tmp) {
1654 next if $seen{$p};
1655 $seen{$p} = 1;
1656 push @ret, $p;
1657 # MAXPARENT is defined to 16 in commit-tree.c:
1658 last if @ret >= 16;
1660 if (@tmp) {
1661 die "r$log_entry->{revision}: No room for parents:\n\t",
1662 join("\n\t", @tmp), "\n";
1664 @ret;
1667 sub rewrite_root {
1668 my ($self) = @_;
1669 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1670 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1671 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1672 if ($rwr) {
1673 $rwr =~ s#/+$##;
1674 if ($rwr !~ m#^[a-z\+]+://#) {
1675 die "$rwr is not a valid URL (key: $k)\n";
1678 $self->{-rewrite_root} = $rwr;
1681 sub metadata_url {
1682 my ($self) = @_;
1683 ($self->rewrite_root || $self->{url}) .
1684 (length $self->{path} ? '/' . $self->{path} : '');
1687 sub full_url {
1688 my ($self) = @_;
1689 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1692 sub do_git_commit {
1693 my ($self, $log_entry) = @_;
1694 my $lr = $self->last_rev;
1695 if (defined $lr && $lr >= $log_entry->{revision}) {
1696 die "Last fetched revision of ", $self->refname,
1697 " was r$lr, but we are about to fetch: ",
1698 "r$log_entry->{revision}!\n";
1700 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1701 croak "$log_entry->{revision} = $c already exists! ",
1702 "Why are we refetching it?\n";
1704 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1705 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1706 $log_entry->{email};
1707 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1709 my $tree = $log_entry->{tree};
1710 if (!defined $tree) {
1711 $tree = $self->tmp_index_do(sub {
1712 command_oneline('write-tree') });
1714 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1716 my @exec = ('git-commit-tree', $tree);
1717 foreach ($self->get_commit_parents($log_entry)) {
1718 push @exec, '-p', $_;
1720 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1721 or croak $!;
1722 print $msg_fh $log_entry->{log} or croak $!;
1723 unless ($self->no_metadata) {
1724 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1725 or croak $!;
1727 $msg_fh->flush == 0 or croak $!;
1728 close $msg_fh or croak $!;
1729 chomp(my $commit = do { local $/; <$out_fh> });
1730 close $out_fh or croak $!;
1731 waitpid $pid, 0;
1732 croak $? if $?;
1733 if ($commit !~ /^$::sha1$/o) {
1734 die "Failed to commit, invalid sha1: $commit\n";
1737 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1739 $self->{last_rev} = $log_entry->{revision};
1740 $self->{last_commit} = $commit;
1741 print "r$log_entry->{revision}";
1742 if (defined $log_entry->{svm_revision}) {
1743 print " (\@$log_entry->{svm_revision})";
1744 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1745 0, $self->svm_uuid);
1747 print " = $commit ($self->{ref_id})\n";
1748 if (defined $_repack && (--$_repack_nr == 0)) {
1749 $_repack_nr = $_repack;
1750 # repack doesn't use any arguments with spaces in them, does it?
1751 print "Running git repack $_repack_flags ...\n";
1752 command_noisy('repack', split(/\s+/, $_repack_flags));
1753 print "Done repacking\n";
1755 return $commit;
1758 sub match_paths {
1759 my ($self, $paths, $r) = @_;
1760 return 1 if $self->{path} eq '';
1761 if (my $path = $paths->{"/$self->{path}"}) {
1762 return ($path->{action} eq 'D') ? 0 : 1;
1764 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1765 if (grep /$self->{path_regex}/, keys %$paths) {
1766 return 1;
1768 my $c = '';
1769 foreach (split m#/#, $self->{path}) {
1770 $c .= "/$_";
1771 next unless ($paths->{$c} &&
1772 ($paths->{$c}->{action} =~ /^[AR]$/));
1773 if ($self->ra->check_path($self->{path}, $r) ==
1774 $SVN::Node::dir) {
1775 return 1;
1778 return 0;
1781 sub find_parent_branch {
1782 my ($self, $paths, $rev) = @_;
1783 return undef unless $self->follow_parent;
1784 unless (defined $paths) {
1785 my $err_handler = $SVN::Error::handler;
1786 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1787 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1788 $paths =
1789 Git::SVN::Ra::dup_changed_paths($_[0]) });
1790 $SVN::Error::handler = $err_handler;
1792 return undef unless defined $paths;
1794 # look for a parent from another branch:
1795 my @b_path_components = split m#/#, $self->rel_path;
1796 my @a_path_components;
1797 my $i;
1798 while (@b_path_components) {
1799 $i = $paths->{'/'.join('/', @b_path_components)};
1800 last if $i && defined $i->{copyfrom_path};
1801 unshift(@a_path_components, pop(@b_path_components));
1803 return undef unless defined $i && defined $i->{copyfrom_path};
1804 my $branch_from = $i->{copyfrom_path};
1805 if (@a_path_components) {
1806 print STDERR "branch_from: $branch_from => ";
1807 $branch_from .= '/'.join('/', @a_path_components);
1808 print STDERR $branch_from, "\n";
1810 my $r = $i->{copyfrom_rev};
1811 my $repos_root = $self->ra->{repos_root};
1812 my $url = $self->ra->{url};
1813 my $new_url = $repos_root . $branch_from;
1814 print STDERR "Found possible branch point: ",
1815 "$new_url => ", $self->full_url, ", $r\n";
1816 $branch_from =~ s#^/##;
1817 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1818 unless ($gs) {
1819 my $ref_id = $self->{ref_id};
1820 $ref_id =~ s/\@\d+$//;
1821 $ref_id .= "\@$r";
1822 # just grow a tail if we're not unique enough :x
1823 $ref_id .= '-' while find_ref($ref_id);
1824 print STDERR "Initializing parent: $ref_id\n";
1825 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1827 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1828 if (!defined $r0 || !defined $parent) {
1829 my ($base, $head) = parse_revision_argument(0, $r);
1830 if ($base <= $r) {
1831 $gs->fetch($base, $r);
1833 ($r0, $parent) = $gs->last_rev_commit;
1835 if (defined $r0 && defined $parent) {
1836 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1837 my $ed;
1838 if ($self->ra->can_do_switch) {
1839 $self->assert_index_clean($parent);
1840 print STDERR "Following parent with do_switch\n";
1841 # do_switch works with svn/trunk >= r22312, but that
1842 # is not included with SVN 1.4.3 (the latest version
1843 # at the moment), so we can't rely on it
1844 $self->{last_commit} = $parent;
1845 $ed = SVN::Git::Fetcher->new($self);
1846 $gs->ra->gs_do_switch($r0, $rev, $gs,
1847 $self->full_url, $ed)
1848 or die "SVN connection failed somewhere...\n";
1849 } else {
1850 print STDERR "Following parent with do_update\n";
1851 $ed = SVN::Git::Fetcher->new($self);
1852 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1853 or die "SVN connection failed somewhere...\n";
1855 print STDERR "Successfully followed parent\n";
1856 return $self->make_log_entry($rev, [$parent], $ed);
1858 return undef;
1861 sub do_fetch {
1862 my ($self, $paths, $rev) = @_;
1863 my $ed;
1864 my ($last_rev, @parents);
1865 if (my $lc = $self->last_commit) {
1866 # we can have a branch that was deleted, then re-added
1867 # under the same name but copied from another path, in
1868 # which case we'll have multiple parents (we don't
1869 # want to break the original ref, nor lose copypath info):
1870 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1871 push @{$log_entry->{parents}}, $lc;
1872 return $log_entry;
1874 $ed = SVN::Git::Fetcher->new($self);
1875 $last_rev = $self->{last_rev};
1876 $ed->{c} = $lc;
1877 @parents = ($lc);
1878 } else {
1879 $last_rev = $rev;
1880 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1881 return $log_entry;
1883 $ed = SVN::Git::Fetcher->new($self);
1885 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1886 die "SVN connection failed somewhere...\n";
1888 $self->make_log_entry($rev, \@parents, $ed);
1891 sub get_untracked {
1892 my ($self, $ed) = @_;
1893 my @out;
1894 my $h = $ed->{empty};
1895 foreach (sort keys %$h) {
1896 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1897 push @out, " $act: " . uri_encode($_);
1898 warn "W: $act: $_\n";
1900 foreach my $t (qw/dir_prop file_prop/) {
1901 $h = $ed->{$t} or next;
1902 foreach my $path (sort keys %$h) {
1903 my $ppath = $path eq '' ? '.' : $path;
1904 foreach my $prop (sort keys %{$h->{$path}}) {
1905 next if $SKIP_PROP{$prop};
1906 my $v = $h->{$path}->{$prop};
1907 my $t_ppath_prop = "$t: " .
1908 uri_encode($ppath) . ' ' .
1909 uri_encode($prop);
1910 if (defined $v) {
1911 push @out, " +$t_ppath_prop " .
1912 uri_encode($v);
1913 } else {
1914 push @out, " -$t_ppath_prop";
1919 foreach my $t (qw/absent_file absent_directory/) {
1920 $h = $ed->{$t} or next;
1921 foreach my $parent (sort keys %$h) {
1922 foreach my $path (sort @{$h->{$parent}}) {
1923 push @out, " $t: " .
1924 uri_encode("$parent/$path");
1925 warn "W: $t: $parent/$path ",
1926 "Insufficient permissions?\n";
1930 \@out;
1933 sub parse_svn_date {
1934 my $date = shift || return '+0000 1970-01-01 00:00:00';
1935 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1936 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1937 croak "Unable to parse date: $date\n";
1938 "+0000 $Y-$m-$d $H:$M:$S";
1941 sub check_author {
1942 my ($author) = @_;
1943 if (!defined $author || length $author == 0) {
1944 $author = '(no author)';
1946 if (defined $::_authors && ! defined $::users{$author}) {
1947 die "Author: $author not defined in $::_authors file\n";
1949 $author;
1952 sub make_log_entry {
1953 my ($self, $rev, $parents, $ed) = @_;
1954 my $untracked = $self->get_untracked($ed);
1956 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1957 print $un "r$rev\n" or croak $!;
1958 print $un $_, "\n" foreach @$untracked;
1959 my %log_entry = ( parents => $parents || [], revision => $rev,
1960 log => '');
1962 my $headrev;
1963 my $logged = delete $self->{logged_rev_props};
1964 if (!$logged || $self->{-want_revprops}) {
1965 my $rp = $self->ra->rev_proplist($rev);
1966 foreach (sort keys %$rp) {
1967 my $v = $rp->{$_};
1968 if (/^svn:(author|date|log)$/) {
1969 $log_entry{$1} = $v;
1970 } elsif ($_ eq 'svm:headrev') {
1971 $headrev = $v;
1972 } else {
1973 print $un " rev_prop: ", uri_encode($_), ' ',
1974 uri_encode($v), "\n";
1977 } else {
1978 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1980 close $un or croak $!;
1982 $log_entry{date} = parse_svn_date($log_entry{date});
1983 $log_entry{log} .= "\n";
1984 my $author = $log_entry{author} = check_author($log_entry{author});
1985 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1986 : ($author, undef);
1987 if (defined $headrev && $self->use_svm_props) {
1988 if ($self->rewrite_root) {
1989 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1990 "options set!\n";
1992 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1993 # we don't want "SVM: initializing mirror for junk" ...
1994 return undef if $r == 0;
1995 my $svm = $self->svm;
1996 if ($uuid ne $svm->{uuid}) {
1997 die "UUID mismatch on SVM path:\n",
1998 "expected: $svm->{uuid}\n",
1999 " got: $uuid\n";
2001 my $full_url = $self->full_url;
2002 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2003 die "Failed to replace '$svm->{replace}' with ",
2004 "'$svm->{source}' in $full_url\n";
2005 # throw away username for storing in records
2006 remove_username($full_url);
2007 $log_entry{metadata} = "$full_url\@$r $uuid";
2008 $log_entry{svm_revision} = $r;
2009 $email ||= "$author\@$uuid"
2010 } elsif ($self->use_svnsync_props) {
2011 my $full_url = $self->svnsync->{url};
2012 $full_url .= "/$self->{path}" if length $self->{path};
2013 remove_username($full_url);
2014 my $uuid = $self->svnsync->{uuid};
2015 $log_entry{metadata} = "$full_url\@$rev $uuid";
2016 $email ||= "$author\@$uuid"
2017 } else {
2018 my $url = $self->metadata_url;
2019 remove_username($url);
2020 $log_entry{metadata} = "$url\@$rev " .
2021 $self->ra->get_uuid;
2022 $email ||= "$author\@" . $self->ra->get_uuid;
2024 $log_entry{name} = $name;
2025 $log_entry{email} = $email;
2026 \%log_entry;
2029 sub fetch {
2030 my ($self, $min_rev, $max_rev, @parents) = @_;
2031 my ($last_rev, $last_commit) = $self->last_rev_commit;
2032 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2033 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2036 sub set_tree_cb {
2037 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2038 $self->{inject_parents} = { $rev => $tree };
2039 $self->fetch(undef, undef);
2042 sub set_tree {
2043 my ($self, $tree) = (shift, shift);
2044 my $log_entry = ::get_commit_entry($tree);
2045 unless ($self->{last_rev}) {
2046 fatal("Must have an existing revision to commit\n");
2048 my %ed_opts = ( r => $self->{last_rev},
2049 log => $log_entry->{log},
2050 ra => $self->ra,
2051 tree_a => $self->{last_commit},
2052 tree_b => $tree,
2053 editor_cb => sub {
2054 $self->set_tree_cb($log_entry, $tree, @_) },
2055 svn_path => $self->{path} );
2056 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2057 print "No changes\nr$self->{last_rev} = $tree\n";
2061 sub rebuild {
2062 my ($self) = @_;
2063 my $db_path = $self->db_path;
2064 return if (-e $db_path && ! -z $db_path);
2065 return unless ::verify_ref($self->refname.'^0');
2066 if (-f $self->{db_root}) {
2067 rename $self->{db_root}, $db_path or die
2068 "rename $self->{db_root} => $db_path failed: $!\n";
2069 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2070 symlink $base, $self->{db_root} or die
2071 "symlink $base => $self->{db_root} failed: $!\n";
2072 return;
2074 print "Rebuilding $db_path ...\n";
2075 my ($log, $ctx) = command_output_pipe("log", $self->refname);
2076 my $latest;
2077 my $full_url = $self->full_url;
2078 remove_username($full_url);
2079 my $svn_uuid;
2080 my $c;
2081 while (<$log>) {
2082 if ( m{^commit ($::sha1)$} ) {
2083 $c = $1;
2084 next;
2086 next unless s{^\s*(git-svn-id:)}{$1};
2087 my ($url, $rev, $uuid) = ::extract_metadata($_);
2088 remove_username($url);
2090 # ignore merges (from set-tree)
2091 next if (!defined $rev || !$uuid);
2093 # if we merged or otherwise started elsewhere, this is
2094 # how we break out of it
2095 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2096 ($full_url && $url && ($url ne $full_url))) {
2097 next;
2099 $latest ||= $rev;
2100 $svn_uuid ||= $uuid;
2102 $self->rev_db_set($rev, $c);
2103 print "r$rev = $c\n";
2105 command_close_pipe($log, $ctx);
2106 print "Done rebuilding $db_path\n";
2109 # rev_db:
2110 # Tie::File seems to be prone to offset errors if revisions get sparse,
2111 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2112 # one of my favorite modules is out :< Next up would be one of the DBM
2113 # modules, but I'm not sure which is most portable... So I'll just
2114 # go with something that's plain-text, but still capable of
2115 # being randomly accessed. So here's my ultra-simple fixed-width
2116 # database. All records are 40 characters + "\n", so it's easy to seek
2117 # to a revision: (41 * rev) is the byte offset.
2118 # A record of 40 0s denotes an empty revision.
2119 # And yes, it's still pretty fast (faster than Tie::File).
2120 # These files are disposable unless noMetadata or useSvmProps is set
2122 sub _rev_db_set {
2123 my ($fh, $rev, $commit) = @_;
2124 my $offset = $rev * 41;
2125 # assume that append is the common case:
2126 seek $fh, 0, 2 or croak $!;
2127 my $pos = tell $fh;
2128 if ($pos < $offset) {
2129 for (1 .. (($offset - $pos) / 41)) {
2130 print $fh (('0' x 40),"\n") or croak $!;
2133 seek $fh, $offset, 0 or croak $!;
2134 print $fh $commit,"\n" or croak $!;
2137 sub mkfile {
2138 my ($path) = @_;
2139 unless (-e $path) {
2140 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2141 mkpath([$dir]) unless -d $dir;
2142 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2143 close $fh or die "Couldn't close (create) $path: $!\n";
2147 sub rev_db_set {
2148 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2149 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2150 my $db = $self->db_path($uuid);
2151 my $db_lock = "$db.lock";
2152 my $sig;
2153 if ($update_ref) {
2154 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2155 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2157 mkfile($db);
2159 $LOCKFILES{$db_lock} = 1;
2160 my $sync;
2161 # both of these options make our .rev_db file very, very important
2162 # and we can't afford to lose it because rebuild() won't work
2163 if ($self->use_svm_props || $self->no_metadata) {
2164 $sync = 1;
2165 copy($db, $db_lock) or die "rev_db_set(@_): ",
2166 "Failed to copy: ",
2167 "$db => $db_lock ($!)\n";
2168 } else {
2169 rename $db, $db_lock or die "rev_db_set(@_): ",
2170 "Failed to rename: ",
2171 "$db => $db_lock ($!)\n";
2173 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2174 _rev_db_set($fh, $rev, $commit);
2175 if ($sync) {
2176 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2177 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2179 close $fh or croak $!;
2180 if ($update_ref) {
2181 $_head = $self;
2182 command_noisy('update-ref', '-m', "r$rev",
2183 $self->refname, $commit);
2185 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2186 "$db_lock => $db ($!)\n";
2187 delete $LOCKFILES{$db_lock};
2188 if ($update_ref) {
2189 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2190 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2191 kill $sig, $$ if defined $sig;
2195 sub rev_db_max {
2196 my ($self) = @_;
2197 $self->rebuild;
2198 my $db_path = $self->db_path;
2199 my @stat = stat $db_path or return 0;
2200 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2201 my $max = $stat[7] / 41;
2202 (($max > 0) ? $max - 1 : 0);
2205 sub rev_db_get {
2206 my ($self, $rev, $uuid) = @_;
2207 my $ret;
2208 my $offset = $rev * 41;
2209 my $db_path = $self->db_path($uuid);
2210 return undef unless -e $db_path;
2211 open my $fh, '<', $db_path or croak $!;
2212 if (sysseek($fh, $offset, 0) == $offset) {
2213 my $read = sysread($fh, $ret, 40);
2214 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2216 close $fh or croak $!;
2217 $ret;
2220 sub find_rev_before {
2221 my ($self, $rev, $eq_ok) = @_;
2222 --$rev unless $eq_ok;
2223 while ($rev > 0) {
2224 if (my $c = $self->rev_db_get($rev)) {
2225 return ($rev, $c);
2227 --$rev;
2229 return (undef, undef);
2232 sub _new {
2233 my ($class, $repo_id, $ref_id, $path) = @_;
2234 unless (defined $repo_id && length $repo_id) {
2235 $repo_id = $Git::SVN::default_repo_id;
2237 unless (defined $ref_id && length $ref_id) {
2238 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2240 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2241 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2242 $_[3] = $path = '' unless (defined $path);
2243 mkpath(["$ENV{GIT_DIR}/svn"]);
2244 bless {
2245 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2246 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2247 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2250 sub db_path {
2251 my ($self, $uuid) = @_;
2252 $uuid ||= $self->ra_uuid;
2253 "$self->{db_root}.$uuid";
2256 sub uri_encode {
2257 my ($f) = @_;
2258 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2262 sub remove_username {
2263 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2266 package Git::SVN::Prompt;
2267 use strict;
2268 use warnings;
2269 require SVN::Core;
2270 use vars qw/$_no_auth_cache $_username/;
2272 sub simple {
2273 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2274 $may_save = undef if $_no_auth_cache;
2275 $default_username = $_username if defined $_username;
2276 if (defined $default_username && length $default_username) {
2277 if (defined $realm && length $realm) {
2278 print STDERR "Authentication realm: $realm\n";
2279 STDERR->flush;
2281 $cred->username($default_username);
2282 } else {
2283 username($cred, $realm, $may_save, $pool);
2285 $cred->password(_read_password("Password for '" .
2286 $cred->username . "': ", $realm));
2287 $cred->may_save($may_save);
2288 $SVN::_Core::SVN_NO_ERROR;
2291 sub ssl_server_trust {
2292 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2293 $may_save = undef if $_no_auth_cache;
2294 print STDERR "Error validating server certificate for '$realm':\n";
2295 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2296 print STDERR " - The certificate is not issued by a trusted ",
2297 "authority. Use the\n",
2298 " fingerprint to validate the certificate manually!\n";
2300 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2301 print STDERR " - The certificate hostname does not match.\n";
2303 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2304 print STDERR " - The certificate is not yet valid.\n";
2306 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2307 print STDERR " - The certificate has expired.\n";
2309 if ($failures & $SVN::Auth::SSL::OTHER) {
2310 print STDERR " - The certificate has an unknown error.\n";
2312 printf STDERR
2313 "Certificate information:\n".
2314 " - Hostname: %s\n".
2315 " - Valid: from %s until %s\n".
2316 " - Issuer: %s\n".
2317 " - Fingerprint: %s\n",
2318 map $cert_info->$_, qw(hostname valid_from valid_until
2319 issuer_dname fingerprint);
2320 my $choice;
2321 prompt:
2322 print STDERR $may_save ?
2323 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2324 "(R)eject or accept (t)emporarily? ";
2325 STDERR->flush;
2326 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2327 if ($choice =~ /^t$/i) {
2328 $cred->may_save(undef);
2329 } elsif ($choice =~ /^r$/i) {
2330 return -1;
2331 } elsif ($may_save && $choice =~ /^p$/i) {
2332 $cred->may_save($may_save);
2333 } else {
2334 goto prompt;
2336 $cred->accepted_failures($failures);
2337 $SVN::_Core::SVN_NO_ERROR;
2340 sub ssl_client_cert {
2341 my ($cred, $realm, $may_save, $pool) = @_;
2342 $may_save = undef if $_no_auth_cache;
2343 print STDERR "Client certificate filename: ";
2344 STDERR->flush;
2345 chomp(my $filename = <STDIN>);
2346 $cred->cert_file($filename);
2347 $cred->may_save($may_save);
2348 $SVN::_Core::SVN_NO_ERROR;
2351 sub ssl_client_cert_pw {
2352 my ($cred, $realm, $may_save, $pool) = @_;
2353 $may_save = undef if $_no_auth_cache;
2354 $cred->password(_read_password("Password: ", $realm));
2355 $cred->may_save($may_save);
2356 $SVN::_Core::SVN_NO_ERROR;
2359 sub username {
2360 my ($cred, $realm, $may_save, $pool) = @_;
2361 $may_save = undef if $_no_auth_cache;
2362 if (defined $realm && length $realm) {
2363 print STDERR "Authentication realm: $realm\n";
2365 my $username;
2366 if (defined $_username) {
2367 $username = $_username;
2368 } else {
2369 print STDERR "Username: ";
2370 STDERR->flush;
2371 chomp($username = <STDIN>);
2373 $cred->username($username);
2374 $cred->may_save($may_save);
2375 $SVN::_Core::SVN_NO_ERROR;
2378 sub _read_password {
2379 my ($prompt, $realm) = @_;
2380 print STDERR $prompt;
2381 STDERR->flush;
2382 require Term::ReadKey;
2383 Term::ReadKey::ReadMode('noecho');
2384 my $password = '';
2385 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2386 last if $key =~ /[\012\015]/; # \n\r
2387 $password .= $key;
2389 Term::ReadKey::ReadMode('restore');
2390 print STDERR "\n";
2391 STDERR->flush;
2392 $password;
2395 package main;
2398 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2399 $SVN::Node::dir.$SVN::Node::unknown.
2400 $SVN::Node::none.$SVN::Node::file.
2401 $SVN::Node::dir.$SVN::Node::unknown.
2402 $SVN::Auth::SSL::CNMISMATCH.
2403 $SVN::Auth::SSL::NOTYETVALID.
2404 $SVN::Auth::SSL::EXPIRED.
2405 $SVN::Auth::SSL::UNKNOWNCA.
2406 $SVN::Auth::SSL::OTHER;
2409 package SVN::Git::Fetcher;
2410 use vars qw/@ISA/;
2411 use strict;
2412 use warnings;
2413 use Carp qw/croak/;
2414 use IO::File qw//;
2415 use Digest::MD5;
2417 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2418 sub new {
2419 my ($class, $git_svn) = @_;
2420 my $self = SVN::Delta::Editor->new;
2421 bless $self, $class;
2422 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2423 $self->{empty} = {};
2424 $self->{dir_prop} = {};
2425 $self->{file_prop} = {};
2426 $self->{absent_dir} = {};
2427 $self->{absent_file} = {};
2428 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2429 $self;
2432 sub set_path_strip {
2433 my ($self, $path) = @_;
2434 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2437 sub open_root {
2438 { path => '' };
2441 sub open_directory {
2442 my ($self, $path, $pb, $rev) = @_;
2443 { path => $path };
2446 sub git_path {
2447 my ($self, $path) = @_;
2448 if ($self->{path_strip}) {
2449 $path =~ s!$self->{path_strip}!! or
2450 die "Failed to strip path '$path' ($self->{path_strip})\n";
2452 $path;
2455 sub delete_entry {
2456 my ($self, $path, $rev, $pb) = @_;
2458 my $gpath = $self->git_path($path);
2459 return undef if ($gpath eq '');
2461 # remove entire directories.
2462 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2463 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2464 -r --name-only -z/,
2465 $self->{c}, '--', $gpath);
2466 local $/ = "\0";
2467 while (<$ls>) {
2468 chomp;
2469 $self->{gii}->remove($_);
2470 print "\tD\t$_\n" unless $::_q;
2472 print "\tD\t$gpath/\n" unless $::_q;
2473 command_close_pipe($ls, $ctx);
2474 $self->{empty}->{$path} = 0
2475 } else {
2476 $self->{gii}->remove($gpath);
2477 print "\tD\t$gpath\n" unless $::_q;
2479 undef;
2482 sub open_file {
2483 my ($self, $path, $pb, $rev) = @_;
2484 my $gpath = $self->git_path($path);
2485 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2486 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2487 unless (defined $mode && defined $blob) {
2488 die "$path was not found in commit $self->{c} (r$rev)\n";
2490 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2491 pool => SVN::Pool->new, action => 'M' };
2494 sub add_file {
2495 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2496 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2497 delete $self->{empty}->{$dir};
2498 { path => $path, mode_a => 100644, mode_b => 100644,
2499 pool => SVN::Pool->new, action => 'A' };
2502 sub add_directory {
2503 my ($self, $path, $cp_path, $cp_rev) = @_;
2504 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2505 delete $self->{empty}->{$dir};
2506 $self->{empty}->{$path} = 1;
2507 { path => $path };
2510 sub change_dir_prop {
2511 my ($self, $db, $prop, $value) = @_;
2512 $self->{dir_prop}->{$db->{path}} ||= {};
2513 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2514 undef;
2517 sub absent_directory {
2518 my ($self, $path, $pb) = @_;
2519 $self->{absent_dir}->{$pb->{path}} ||= [];
2520 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2521 undef;
2524 sub absent_file {
2525 my ($self, $path, $pb) = @_;
2526 $self->{absent_file}->{$pb->{path}} ||= [];
2527 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2528 undef;
2531 sub change_file_prop {
2532 my ($self, $fb, $prop, $value) = @_;
2533 if ($prop eq 'svn:executable') {
2534 if ($fb->{mode_b} != 120000) {
2535 $fb->{mode_b} = defined $value ? 100755 : 100644;
2537 } elsif ($prop eq 'svn:special') {
2538 $fb->{mode_b} = defined $value ? 120000 : 100644;
2539 } else {
2540 $self->{file_prop}->{$fb->{path}} ||= {};
2541 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2543 undef;
2546 sub apply_textdelta {
2547 my ($self, $fb, $exp) = @_;
2548 my $fh = IO::File->new_tmpfile;
2549 $fh->autoflush(1);
2550 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2551 # (but $base does not,) so dup() it for reading in close_file
2552 open my $dup, '<&', $fh or croak $!;
2553 my $base = IO::File->new_tmpfile;
2554 $base->autoflush(1);
2555 if ($fb->{blob}) {
2556 defined (my $pid = fork) or croak $!;
2557 if (!$pid) {
2558 open STDOUT, '>&', $base or croak $!;
2559 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2560 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2562 waitpid $pid, 0;
2563 croak $? if $?;
2565 if (defined $exp) {
2566 seek $base, 0, 0 or croak $!;
2567 my $md5 = Digest::MD5->new;
2568 $md5->addfile($base);
2569 my $got = $md5->hexdigest;
2570 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2571 "expected: $exp\n",
2572 " got: $got\n" if ($got ne $exp);
2575 seek $base, 0, 0 or croak $!;
2576 $fb->{fh} = $dup;
2577 $fb->{base} = $base;
2578 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2581 sub close_file {
2582 my ($self, $fb, $exp) = @_;
2583 my $hash;
2584 my $path = $self->git_path($fb->{path});
2585 if (my $fh = $fb->{fh}) {
2586 if (defined $exp) {
2587 seek($fh, 0, 0) or croak $!;
2588 my $md5 = Digest::MD5->new;
2589 $md5->addfile($fh);
2590 my $got = $md5->hexdigest;
2591 if ($got ne $exp) {
2592 die "Checksum mismatch: $path\n",
2593 "expected: $exp\n got: $got\n";
2596 sysseek($fh, 0, 0) or croak $!;
2597 if ($fb->{mode_b} == 120000) {
2598 sysread($fh, my $buf, 5) == 5 or croak $!;
2599 $buf eq 'link ' or die "$path has mode 120000",
2600 "but is not a link\n";
2602 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2603 if (!$pid) {
2604 open STDIN, '<&', $fh or croak $!;
2605 exec qw/git-hash-object -w --stdin/ or croak $!;
2607 chomp($hash = do { local $/; <$out> });
2608 close $out or croak $!;
2609 close $fh or croak $!;
2610 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2611 close $fb->{base} or croak $!;
2612 } else {
2613 $hash = $fb->{blob} or die "no blob information\n";
2615 $fb->{pool}->clear;
2616 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2617 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2618 undef;
2621 sub abort_edit {
2622 my $self = shift;
2623 $self->{nr} = $self->{gii}->{nr};
2624 delete $self->{gii};
2625 $self->SUPER::abort_edit(@_);
2628 sub close_edit {
2629 my $self = shift;
2630 $self->{git_commit_ok} = 1;
2631 $self->{nr} = $self->{gii}->{nr};
2632 delete $self->{gii};
2633 $self->SUPER::close_edit(@_);
2636 package SVN::Git::Editor;
2637 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2638 use strict;
2639 use warnings;
2640 use Carp qw/croak/;
2641 use IO::File;
2642 use Digest::MD5;
2644 sub new {
2645 my ($class, $opts) = @_;
2646 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2647 die "$_ required!\n" unless (defined $opts->{$_});
2650 my $pool = SVN::Pool->new;
2651 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2652 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2653 $opts->{r}, $mods);
2655 # $opts->{ra} functions should not be used after this:
2656 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2657 $opts->{editor_cb}, $pool);
2658 my $self = SVN::Delta::Editor->new(@ce, $pool);
2659 bless $self, $class;
2660 foreach (qw/svn_path r tree_a tree_b/) {
2661 $self->{$_} = $opts->{$_};
2663 $self->{url} = $opts->{ra}->{url};
2664 $self->{mods} = $mods;
2665 $self->{types} = $types;
2666 $self->{pool} = $pool;
2667 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2668 $self->{rm} = { };
2669 $self->{path_prefix} = length $self->{svn_path} ?
2670 "$self->{svn_path}/" : '';
2671 return $self;
2674 sub generate_diff {
2675 my ($tree_a, $tree_b) = @_;
2676 my @diff_tree = qw(diff-tree -z -r);
2677 if ($_cp_similarity) {
2678 push @diff_tree, "-C$_cp_similarity";
2679 } else {
2680 push @diff_tree, '-C';
2682 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2683 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2684 push @diff_tree, $tree_a, $tree_b;
2685 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2686 local $/ = "\0";
2687 my $state = 'meta';
2688 my @mods;
2689 while (<$diff_fh>) {
2690 chomp $_; # this gets rid of the trailing "\0"
2691 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2692 $::sha1\s($::sha1)\s
2693 ([MTCRAD])\d*$/xo) {
2694 push @mods, { mode_a => $1, mode_b => $2,
2695 sha1_b => $3, chg => $4 };
2696 if ($4 =~ /^(?:C|R)$/) {
2697 $state = 'file_a';
2698 } else {
2699 $state = 'file_b';
2701 } elsif ($state eq 'file_a') {
2702 my $x = $mods[$#mods] or croak "Empty array\n";
2703 if ($x->{chg} !~ /^(?:C|R)$/) {
2704 croak "Error parsing $_, $x->{chg}\n";
2706 $x->{file_a} = $_;
2707 $state = 'file_b';
2708 } elsif ($state eq 'file_b') {
2709 my $x = $mods[$#mods] or croak "Empty array\n";
2710 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2711 croak "Error parsing $_, $x->{chg}\n";
2713 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2714 croak "Error parsing $_, $x->{chg}\n";
2716 $x->{file_b} = $_;
2717 $state = 'meta';
2718 } else {
2719 croak "Error parsing $_\n";
2722 command_close_pipe($diff_fh, $ctx);
2723 \@mods;
2726 sub check_diff_paths {
2727 my ($ra, $pfx, $rev, $mods) = @_;
2728 my %types;
2729 $pfx .= '/' if length $pfx;
2731 sub type_diff_paths {
2732 my ($ra, $types, $path, $rev) = @_;
2733 my @p = split m#/+#, $path;
2734 my $c = shift @p;
2735 unless (defined $types->{$c}) {
2736 $types->{$c} = $ra->check_path($c, $rev);
2738 while (@p) {
2739 $c .= '/' . shift @p;
2740 next if defined $types->{$c};
2741 $types->{$c} = $ra->check_path($c, $rev);
2745 foreach my $m (@$mods) {
2746 foreach my $f (qw/file_a file_b/) {
2747 next unless defined $m->{$f};
2748 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2749 if (length $pfx.$dir && ! defined $types{$dir}) {
2750 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2754 \%types;
2757 sub split_path {
2758 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2761 sub repo_path {
2762 my ($self, $path) = @_;
2763 $self->{path_prefix}.(defined $path ? $path : '');
2766 sub url_path {
2767 my ($self, $path) = @_;
2768 if ($self->{url} =~ m#^https?://#) {
2769 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2771 $self->{url} . '/' . $self->repo_path($path);
2774 sub rmdirs {
2775 my ($self) = @_;
2776 my $rm = $self->{rm};
2777 delete $rm->{''}; # we never delete the url we're tracking
2778 return unless %$rm;
2780 foreach (keys %$rm) {
2781 my @d = split m#/#, $_;
2782 my $c = shift @d;
2783 $rm->{$c} = 1;
2784 while (@d) {
2785 $c .= '/' . shift @d;
2786 $rm->{$c} = 1;
2789 delete $rm->{$self->{svn_path}};
2790 delete $rm->{''}; # we never delete the url we're tracking
2791 return unless %$rm;
2793 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2794 $self->{tree_b});
2795 local $/ = "\0";
2796 while (<$fh>) {
2797 chomp;
2798 my @dn = split m#/#, $_;
2799 while (pop @dn) {
2800 delete $rm->{join '/', @dn};
2802 unless (%$rm) {
2803 close $fh;
2804 return;
2807 command_close_pipe($fh, $ctx);
2809 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2810 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2811 $self->close_directory($bat->{$d}, $p);
2812 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2813 print "\tD+\t$d/\n" unless $::_q;
2814 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2815 delete $bat->{$d};
2819 sub open_or_add_dir {
2820 my ($self, $full_path, $baton) = @_;
2821 my $t = $self->{types}->{$full_path};
2822 if (!defined $t) {
2823 die "$full_path not known in r$self->{r} or we have a bug!\n";
2825 if ($t == $SVN::Node::none) {
2826 return $self->add_directory($full_path, $baton,
2827 undef, -1, $self->{pool});
2828 } elsif ($t == $SVN::Node::dir) {
2829 return $self->open_directory($full_path, $baton,
2830 $self->{r}, $self->{pool});
2832 print STDERR "$full_path already exists in repository at ",
2833 "r$self->{r} and it is not a directory (",
2834 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2835 exit 1;
2838 sub ensure_path {
2839 my ($self, $path) = @_;
2840 my $bat = $self->{bat};
2841 my $repo_path = $self->repo_path($path);
2842 return $bat->{''} unless (length $repo_path);
2843 my @p = split m#/+#, $repo_path;
2844 my $c = shift @p;
2845 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2846 while (@p) {
2847 my $c0 = $c;
2848 $c .= '/' . shift @p;
2849 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2851 return $bat->{$c};
2854 sub A {
2855 my ($self, $m) = @_;
2856 my ($dir, $file) = split_path($m->{file_b});
2857 my $pbat = $self->ensure_path($dir);
2858 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2859 undef, -1);
2860 print "\tA\t$m->{file_b}\n" unless $::_q;
2861 $self->chg_file($fbat, $m);
2862 $self->close_file($fbat,undef,$self->{pool});
2865 sub C {
2866 my ($self, $m) = @_;
2867 my ($dir, $file) = split_path($m->{file_b});
2868 my $pbat = $self->ensure_path($dir);
2869 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2870 $self->url_path($m->{file_a}), $self->{r});
2871 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2872 $self->chg_file($fbat, $m);
2873 $self->close_file($fbat,undef,$self->{pool});
2876 sub delete_entry {
2877 my ($self, $path, $pbat) = @_;
2878 my $rpath = $self->repo_path($path);
2879 my ($dir, $file) = split_path($rpath);
2880 $self->{rm}->{$dir} = 1;
2881 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2884 sub R {
2885 my ($self, $m) = @_;
2886 my ($dir, $file) = split_path($m->{file_b});
2887 my $pbat = $self->ensure_path($dir);
2888 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2889 $self->url_path($m->{file_a}), $self->{r});
2890 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2891 $self->chg_file($fbat, $m);
2892 $self->close_file($fbat,undef,$self->{pool});
2894 ($dir, $file) = split_path($m->{file_a});
2895 $pbat = $self->ensure_path($dir);
2896 $self->delete_entry($m->{file_a}, $pbat);
2899 sub M {
2900 my ($self, $m) = @_;
2901 my ($dir, $file) = split_path($m->{file_b});
2902 my $pbat = $self->ensure_path($dir);
2903 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2904 $pbat,$self->{r},$self->{pool});
2905 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2906 $self->chg_file($fbat, $m);
2907 $self->close_file($fbat,undef,$self->{pool});
2910 sub T { shift->M(@_) }
2912 sub change_file_prop {
2913 my ($self, $fbat, $pname, $pval) = @_;
2914 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2917 sub chg_file {
2918 my ($self, $fbat, $m) = @_;
2919 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2920 $self->change_file_prop($fbat,'svn:executable','*');
2921 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2922 $self->change_file_prop($fbat,'svn:executable',undef);
2924 my $fh = IO::File->new_tmpfile or croak $!;
2925 if ($m->{mode_b} =~ /^120/) {
2926 print $fh 'link ' or croak $!;
2927 $self->change_file_prop($fbat,'svn:special','*');
2928 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2929 $self->change_file_prop($fbat,'svn:special',undef);
2931 defined(my $pid = fork) or croak $!;
2932 if (!$pid) {
2933 open STDOUT, '>&', $fh or croak $!;
2934 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2936 waitpid $pid, 0;
2937 croak $? if $?;
2938 $fh->flush == 0 or croak $!;
2939 seek $fh, 0, 0 or croak $!;
2941 my $md5 = Digest::MD5->new;
2942 $md5->addfile($fh) or croak $!;
2943 seek $fh, 0, 0 or croak $!;
2945 my $exp = $md5->hexdigest;
2946 my $pool = SVN::Pool->new;
2947 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2948 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2949 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2950 $pool->clear;
2952 close $fh or croak $!;
2955 sub D {
2956 my ($self, $m) = @_;
2957 my ($dir, $file) = split_path($m->{file_b});
2958 my $pbat = $self->ensure_path($dir);
2959 print "\tD\t$m->{file_b}\n" unless $::_q;
2960 $self->delete_entry($m->{file_b}, $pbat);
2963 sub close_edit {
2964 my ($self) = @_;
2965 my ($p,$bat) = ($self->{pool}, $self->{bat});
2966 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2967 next if $_ eq '';
2968 $self->close_directory($bat->{$_}, $p);
2970 $self->close_directory($bat->{''}, $p);
2971 $self->SUPER::close_edit($p);
2972 $p->clear;
2975 sub abort_edit {
2976 my ($self) = @_;
2977 $self->SUPER::abort_edit($self->{pool});
2980 sub DESTROY {
2981 my $self = shift;
2982 $self->SUPER::DESTROY(@_);
2983 $self->{pool}->clear;
2986 # this drives the editor
2987 sub apply_diff {
2988 my ($self) = @_;
2989 my $mods = $self->{mods};
2990 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2991 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2992 my $f = $m->{chg};
2993 if (defined $o{$f}) {
2994 $self->$f($m);
2995 } else {
2996 fatal("Invalid change type: $f\n");
2999 $self->rmdirs if $_rmdir;
3000 if (@$mods == 0) {
3001 $self->abort_edit;
3002 } else {
3003 $self->close_edit;
3005 return scalar @$mods;
3008 package Git::SVN::Ra;
3009 use vars qw/@ISA $config_dir $_log_window_size/;
3010 use strict;
3011 use warnings;
3012 my ($can_do_switch, %ignored_err, $RA);
3014 BEGIN {
3015 # enforce temporary pool usage for some simple functions
3016 no strict 'refs';
3017 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3018 my $SUPER = "SUPER::$f";
3019 *$f = sub {
3020 my $self = shift;
3021 my $pool = SVN::Pool->new;
3022 my @ret = $self->$SUPER(@_,$pool);
3023 $pool->clear;
3024 wantarray ? @ret : $ret[0];
3029 sub new {
3030 my ($class, $url) = @_;
3031 $url =~ s!/+$!!;
3032 return $RA if ($RA && $RA->{url} eq $url);
3034 SVN::_Core::svn_config_ensure($config_dir, undef);
3035 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3036 SVN::Client::get_simple_provider(),
3037 SVN::Client::get_ssl_server_trust_file_provider(),
3038 SVN::Client::get_simple_prompt_provider(
3039 \&Git::SVN::Prompt::simple, 2),
3040 SVN::Client::get_ssl_client_cert_file_provider(),
3041 SVN::Client::get_ssl_client_cert_prompt_provider(
3042 \&Git::SVN::Prompt::ssl_client_cert, 2),
3043 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3044 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3045 SVN::Client::get_username_provider(),
3046 SVN::Client::get_ssl_server_trust_prompt_provider(
3047 \&Git::SVN::Prompt::ssl_server_trust),
3048 SVN::Client::get_username_prompt_provider(
3049 \&Git::SVN::Prompt::username, 2),
3051 my $config = SVN::Core::config_get_config($config_dir);
3052 $RA = undef;
3053 my $self = SVN::Ra->new(url => $url, auth => $baton,
3054 config => $config,
3055 pool => SVN::Pool->new,
3056 auth_provider_callbacks => $callbacks);
3057 $self->{svn_path} = $url;
3058 $self->{repos_root} = $self->get_repos_root;
3059 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3060 $self->{cache} = { check_path => { r => 0, data => {} },
3061 get_dir => { r => 0, data => {} } };
3062 $RA = bless $self, $class;
3065 sub check_path {
3066 my ($self, $path, $r) = @_;
3067 my $cache = $self->{cache}->{check_path};
3068 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3069 return $cache->{data}->{$path};
3071 my $pool = SVN::Pool->new;
3072 my $t = $self->SUPER::check_path($path, $r, $pool);
3073 $pool->clear;
3074 if ($r != $cache->{r}) {
3075 %{$cache->{data}} = ();
3076 $cache->{r} = $r;
3078 $cache->{data}->{$path} = $t;
3081 sub get_dir {
3082 my ($self, $dir, $r) = @_;
3083 my $cache = $self->{cache}->{get_dir};
3084 if ($r == $cache->{r}) {
3085 if (my $x = $cache->{data}->{$dir}) {
3086 return wantarray ? @$x : $x->[0];
3089 my $pool = SVN::Pool->new;
3090 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3091 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3092 $pool->clear;
3093 if ($r != $cache->{r}) {
3094 %{$cache->{data}} = ();
3095 $cache->{r} = $r;
3097 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3098 wantarray ? (\%dirents, $r, $props) : \%dirents;
3101 sub DESTROY {
3102 # do not call the real DESTROY since we store ourselves in $RA
3105 sub get_log {
3106 my ($self, @args) = @_;
3107 my $pool = SVN::Pool->new;
3108 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3109 my $ret = $self->SUPER::get_log(@args, $pool);
3110 $pool->clear;
3111 $ret;
3114 sub get_commit_editor {
3115 my ($self, $log, $cb, $pool) = @_;
3116 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3117 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3120 sub gs_do_update {
3121 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3122 my $new = ($rev_a == $rev_b);
3123 my $path = $gs->{path};
3125 if ($new && -e $gs->{index}) {
3126 unlink $gs->{index} or die
3127 "Couldn't unlink index: $gs->{index}: $!\n";
3129 my $pool = SVN::Pool->new;
3130 $editor->set_path_strip($path);
3131 my (@pc) = split m#/#, $path;
3132 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3133 1, $editor, $pool);
3134 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3136 # Since we can't rely on svn_ra_reparent being available, we'll
3137 # just have to do some magic with set_path to make it so
3138 # we only want a partial path.
3139 my $sp = '';
3140 my $final = join('/', @pc);
3141 while (@pc) {
3142 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3143 $sp .= '/' if length $sp;
3144 $sp .= shift @pc;
3146 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3148 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3150 $reporter->finish_report($pool);
3151 $pool->clear;
3152 $editor->{git_commit_ok};
3155 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3156 # svn_ra_reparent didn't work before 1.4)
3157 sub gs_do_switch {
3158 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3159 my $path = $gs->{path};
3160 my $pool = SVN::Pool->new;
3162 my $full_url = $self->{url};
3163 my $old_url = $full_url;
3164 $full_url .= "/$path" if length $path;
3165 my ($ra, $reparented);
3166 if ($old_url ne $full_url) {
3167 if ($old_url !~ m#^svn(\+ssh)?://#) {
3168 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3169 $pool);
3170 $self->{url} = $full_url;
3171 $reparented = 1;
3172 } else {
3173 $ra = Git::SVN::Ra->new($full_url);
3176 $ra ||= $self;
3177 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3178 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3179 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3180 $reporter->finish_report($pool);
3182 if ($reparented) {
3183 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3184 $self->{url} = $old_url;
3187 $pool->clear;
3188 $editor->{git_commit_ok};
3191 sub longest_common_path {
3192 my ($gsv, $globs) = @_;
3193 my %common;
3194 my $common_max = scalar @$gsv;
3196 foreach my $gs (@$gsv) {
3197 my @tmp = split m#/#, $gs->{path};
3198 my $p = '';
3199 foreach (@tmp) {
3200 $p .= length($p) ? "/$_" : $_;
3201 $common{$p} ||= 0;
3202 $common{$p}++;
3205 $globs ||= [];
3206 $common_max += scalar @$globs;
3207 foreach my $glob (@$globs) {
3208 my @tmp = split m#/#, $glob->{path}->{left};
3209 my $p = '';
3210 foreach (@tmp) {
3211 $p .= length($p) ? "/$_" : $_;
3212 $common{$p} ||= 0;
3213 $common{$p}++;
3217 my $longest_path = '';
3218 foreach (sort {length $b <=> length $a} keys %common) {
3219 if ($common{$_} == $common_max) {
3220 $longest_path = $_;
3221 last;
3224 $longest_path;
3227 sub gs_fetch_loop_common {
3228 my ($self, $base, $head, $gsv, $globs) = @_;
3229 return if ($base > $head);
3230 my $inc = $_log_window_size;
3231 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3232 my $longest_path = longest_common_path($gsv, $globs);
3233 while (1) {
3234 my %revs;
3235 my $err;
3236 my $err_handler = $SVN::Error::handler;
3237 $SVN::Error::handler = sub {
3238 ($err) = @_;
3239 skip_unknown_revs($err);
3241 sub _cb {
3242 my ($paths, $r, $author, $date, $log) = @_;
3243 [ dup_changed_paths($paths),
3244 { author => $author, date => $date, log => $log } ];
3246 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3247 sub { $revs{$_[1]} = _cb(@_) });
3248 if ($err && $max >= $head) {
3249 print STDERR "Path '$longest_path' ",
3250 "was probably deleted:\n",
3251 $err->expanded_message,
3252 "\nWill attempt to follow ",
3253 "revisions r$min .. r$max ",
3254 "committed before the deletion\n";
3255 my $hi = $max;
3256 while (--$hi >= $min) {
3257 my $ok;
3258 $self->get_log([$longest_path], $min, $hi,
3259 0, 1, 1, sub {
3260 $ok ||= $_[1];
3261 $revs{$_[1]} = _cb(@_) });
3262 if ($ok) {
3263 print STDERR "r$min .. r$ok OK\n";
3264 last;
3268 $SVN::Error::handler = $err_handler;
3270 my %exists = map { $_->{path} => $_ } @$gsv;
3271 foreach my $r (sort {$a <=> $b} keys %revs) {
3272 my ($paths, $logged) = @{$revs{$r}};
3274 foreach my $gs ($self->match_globs(\%exists, $paths,
3275 $globs, $r)) {
3276 if ($gs->rev_db_max >= $r) {
3277 next;
3279 next unless $gs->match_paths($paths, $r);
3280 $gs->{logged_rev_props} = $logged;
3281 if (my $last_commit = $gs->last_commit) {
3282 $gs->assert_index_clean($last_commit);
3284 my $log_entry = $gs->do_fetch($paths, $r);
3285 if ($log_entry) {
3286 $gs->do_git_commit($log_entry);
3289 foreach my $g (@$globs) {
3290 my $k = "svn-remote.$g->{remote}." .
3291 "$g->{t}-maxRev";
3292 Git::SVN::tmp_config($k, $r);
3295 # pre-fill the .rev_db since it'll eventually get filled in
3296 # with '0' x40 if something new gets committed
3297 foreach my $gs (@$gsv) {
3298 next if defined $gs->rev_db_get($max);
3299 $gs->rev_db_set($max, 0 x40);
3301 foreach my $g (@$globs) {
3302 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3303 Git::SVN::tmp_config($k, $max);
3305 last if $max >= $head;
3306 $min = $max + 1;
3307 $max += $inc;
3308 $max = $head if ($max > $head);
3312 sub match_globs {
3313 my ($self, $exists, $paths, $globs, $r) = @_;
3315 sub get_dir_check {
3316 my ($self, $exists, $g, $r) = @_;
3317 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3318 return unless scalar @x == 3;
3319 my $dirents = $x[0];
3320 foreach my $de (keys %$dirents) {
3321 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3322 my $p = $g->{path}->full_path($de);
3323 next if $exists->{$p};
3324 next if (length $g->{path}->{right} &&
3325 ($self->check_path($p, $r) !=
3326 $SVN::Node::dir));
3327 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3328 $g->{ref}->full_path($de), 1);
3331 foreach my $g (@$globs) {
3332 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3333 if ($path->{action} =~ /^[AR]$/) {
3334 get_dir_check($self, $exists, $g, $r);
3337 foreach (keys %$paths) {
3338 if (/$g->{path}->{left_regex}/ &&
3339 !/$g->{path}->{regex}/) {
3340 next if $paths->{$_}->{action} !~ /^[AR]$/;
3341 get_dir_check($self, $exists, $g, $r);
3343 next unless /$g->{path}->{regex}/;
3344 my $p = $1;
3345 my $pathname = $g->{path}->full_path($p);
3346 next if $exists->{$pathname};
3347 next if ($self->check_path($pathname, $r) !=
3348 $SVN::Node::dir);
3349 $exists->{$pathname} = Git::SVN->init(
3350 $self->{url}, $pathname, undef,
3351 $g->{ref}->full_path($p), 1);
3353 my $c = '';
3354 foreach (split m#/#, $g->{path}->{left}) {
3355 $c .= "/$_";
3356 next unless ($paths->{$c} &&
3357 ($paths->{$c}->{action} =~ /^[AR]$/));
3358 get_dir_check($self, $exists, $g, $r);
3361 values %$exists;
3364 sub minimize_url {
3365 my ($self) = @_;
3366 return $self->{url} if ($self->{url} eq $self->{repos_root});
3367 my $url = $self->{repos_root};
3368 my @components = split(m!/!, $self->{svn_path});
3369 my $c = '';
3370 do {
3371 $url .= "/$c" if length $c;
3372 eval { (ref $self)->new($url)->get_latest_revnum };
3373 } while ($@ && ($c = shift @components));
3374 $url;
3377 sub can_do_switch {
3378 my $self = shift;
3379 unless (defined $can_do_switch) {
3380 my $pool = SVN::Pool->new;
3381 my $rep = eval {
3382 $self->do_switch(1, '', 0, $self->{url},
3383 SVN::Delta::Editor->new, $pool);
3385 if ($@) {
3386 $can_do_switch = 0;
3387 } else {
3388 $rep->abort_report($pool);
3389 $can_do_switch = 1;
3391 $pool->clear;
3393 $can_do_switch;
3396 sub skip_unknown_revs {
3397 my ($err) = @_;
3398 my $errno = $err->apr_err();
3399 # Maybe the branch we're tracking didn't
3400 # exist when the repo started, so it's
3401 # not an error if it doesn't, just continue
3403 # Wonderfully consistent library, eh?
3404 # 160013 - svn:// and file://
3405 # 175002 - http(s)://
3406 # 175007 - http(s):// (this repo required authorization, too...)
3407 # More codes may be discovered later...
3408 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3409 my $err_key = $err->expanded_message;
3410 # revision numbers change every time, filter them out
3411 $err_key =~ s/\d+/\0/g;
3412 $err_key = "$errno\0$err_key";
3413 unless ($ignored_err{$err_key}) {
3414 warn "W: Ignoring error from SVN, path probably ",
3415 "does not exist: ($errno): ",
3416 $err->expanded_message,"\n";
3417 $ignored_err{$err_key} = 1;
3419 return;
3421 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3424 # svn_log_changed_path_t objects passed to get_log are likely to be
3425 # overwritten even if only the refs are copied to an external variable,
3426 # so we should dup the structures in their entirety. Using an externally
3427 # passed pool (instead of our temporary and quickly cleared pool in
3428 # Git::SVN::Ra) does not help matters at all...
3429 sub dup_changed_paths {
3430 my ($paths) = @_;
3431 return undef unless $paths;
3432 my %ret;
3433 foreach my $p (keys %$paths) {
3434 my $i = $paths->{$p};
3435 my %s = map { $_ => $i->$_ }
3436 qw/copyfrom_path copyfrom_rev action/;
3437 $ret{$p} = \%s;
3439 \%ret;
3442 package Git::SVN::Log;
3443 use strict;
3444 use warnings;
3445 use POSIX qw/strftime/;
3446 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3447 %rusers $show_commit $incremental/;
3448 my $l_fmt;
3450 sub cmt_showable {
3451 my ($c) = @_;
3452 return 1 if defined $c->{r};
3454 # big commit message got truncated by the 16k pretty buffer in rev-list
3455 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3456 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3457 @{$c->{l}} = ();
3458 my @log = command(qw/cat-file commit/, $c->{c});
3460 # shift off the headers
3461 shift @log while ($log[0] ne '');
3462 shift @log;
3464 # TODO: make $c->{l} not have a trailing newline in the future
3465 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3467 (undef, $c->{r}, undef) = ::extract_metadata(
3468 (grep(/^git-svn-id: /, @log))[-1]);
3470 return defined $c->{r};
3473 sub log_use_color {
3474 return 1 if $color;
3475 my ($dc, $dcvar);
3476 $dcvar = 'color.diff';
3477 $dc = `git-config --get $dcvar`;
3478 if ($dc eq '') {
3479 # nothing at all; fallback to "diff.color"
3480 $dcvar = 'diff.color';
3481 $dc = `git-config --get $dcvar`;
3483 chomp($dc);
3484 if ($dc eq 'auto') {
3485 my $pc;
3486 $pc = `git-config --get color.pager`;
3487 if ($pc eq '') {
3488 # does not have it -- fallback to pager.color
3489 $pc = `git-config --bool --get pager.color`;
3491 else {
3492 $pc = `git-config --bool --get color.pager`;
3493 if ($?) {
3494 $pc = 'false';
3497 chomp($pc);
3498 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3499 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3501 return 0;
3503 return 0 if $dc eq 'never';
3504 return 1 if $dc eq 'always';
3505 chomp($dc = `git-config --bool --get $dcvar`);
3506 return ($dc eq 'true');
3509 sub git_svn_log_cmd {
3510 my ($r_min, $r_max, @args) = @_;
3511 my $head = 'HEAD';
3512 my (@files, @log_opts);
3513 foreach my $x (@args) {
3514 if ($x eq '--' || @files) {
3515 push @files, $x;
3516 } else {
3517 if (::verify_ref("$x^0")) {
3518 $head = $x;
3519 } else {
3520 push @log_opts, $x;
3525 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3526 $gs ||= Git::SVN->_new;
3527 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3528 $gs->refname);
3529 push @cmd, '-r' unless $non_recursive;
3530 push @cmd, qw/--raw --name-status/ if $verbose;
3531 push @cmd, '--color' if log_use_color();
3532 push @cmd, @log_opts;
3533 if (defined $r_max && $r_max == $r_min) {
3534 push @cmd, '--max-count=1';
3535 if (my $c = $gs->rev_db_get($r_max)) {
3536 push @cmd, $c;
3538 } elsif (defined $r_max) {
3539 my ($c_min, $c_max);
3540 $c_max = $gs->rev_db_get($r_max);
3541 $c_min = $gs->rev_db_get($r_min);
3542 if (defined $c_min && defined $c_max) {
3543 if ($r_max > $r_max) {
3544 push @cmd, "$c_min..$c_max";
3545 } else {
3546 push @cmd, "$c_max..$c_min";
3548 } elsif ($r_max > $r_min) {
3549 push @cmd, $c_max;
3550 } else {
3551 push @cmd, $c_min;
3554 return (@cmd, @files);
3557 # adapted from pager.c
3558 sub config_pager {
3559 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3560 if (!defined $pager) {
3561 $pager = 'less';
3562 } elsif (length $pager == 0 || $pager eq 'cat') {
3563 $pager = undef;
3567 sub run_pager {
3568 return unless -t *STDOUT;
3569 pipe my $rfd, my $wfd or return;
3570 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3571 if (!$pid) {
3572 open STDOUT, '>&', $wfd or
3573 ::fatal "Can't redirect to stdout: $!\n";
3574 return;
3576 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3577 $ENV{LESS} ||= 'FRSX';
3578 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3581 sub tz_to_s_offset {
3582 my ($tz) = @_;
3583 $tz =~ s/(\d\d)$//;
3584 return ($1 * 60) + ($tz * 3600);
3587 sub get_author_info {
3588 my ($dest, $author, $t, $tz) = @_;
3589 $author =~ s/(?:^\s*|\s*$)//g;
3590 $dest->{a_raw} = $author;
3591 my $au;
3592 if ($::_authors) {
3593 $au = $rusers{$author} || undef;
3595 if (!$au) {
3596 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3598 $dest->{t} = $t;
3599 $dest->{tz} = $tz;
3600 $dest->{a} = $au;
3601 # Date::Parse isn't in the standard Perl distro :(
3602 if ($tz =~ s/^\+//) {
3603 $t += tz_to_s_offset($tz);
3604 } elsif ($tz =~ s/^\-//) {
3605 $t -= tz_to_s_offset($tz);
3607 $dest->{t_utc} = $t;
3610 sub process_commit {
3611 my ($c, $r_min, $r_max, $defer) = @_;
3612 if (defined $r_min && defined $r_max) {
3613 if ($r_min == $c->{r} && $r_min == $r_max) {
3614 show_commit($c);
3615 return 0;
3617 return 1 if $r_min == $r_max;
3618 if ($r_min < $r_max) {
3619 # we need to reverse the print order
3620 return 0 if (defined $limit && --$limit < 0);
3621 push @$defer, $c;
3622 return 1;
3624 if ($r_min != $r_max) {
3625 return 1 if ($r_min < $c->{r});
3626 return 1 if ($r_max > $c->{r});
3629 return 0 if (defined $limit && --$limit < 0);
3630 show_commit($c);
3631 return 1;
3634 sub show_commit {
3635 my $c = shift;
3636 if ($oneline) {
3637 my $x = "\n";
3638 if (my $l = $c->{l}) {
3639 while ($l->[0] =~ /^\s*$/) { shift @$l }
3640 $x = $l->[0];
3642 $l_fmt ||= 'A' . length($c->{r});
3643 print 'r',pack($l_fmt, $c->{r}),' | ';
3644 print "$c->{c} | " if $show_commit;
3645 print $x;
3646 } else {
3647 show_commit_normal($c);
3651 sub show_commit_changed_paths {
3652 my ($c) = @_;
3653 return unless $c->{changed};
3654 print "Changed paths:\n", @{$c->{changed}};
3657 sub show_commit_normal {
3658 my ($c) = @_;
3659 print '-' x72, "\nr$c->{r} | ";
3660 print "$c->{c} | " if $show_commit;
3661 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3662 localtime($c->{t_utc})), ' | ';
3663 my $nr_line = 0;
3665 if (my $l = $c->{l}) {
3666 while ($l->[$#$l] eq "\n" && $#$l > 0
3667 && $l->[($#$l - 1)] eq "\n") {
3668 pop @$l;
3670 $nr_line = scalar @$l;
3671 if (!$nr_line) {
3672 print "1 line\n\n\n";
3673 } else {
3674 if ($nr_line == 1) {
3675 $nr_line = '1 line';
3676 } else {
3677 $nr_line .= ' lines';
3679 print $nr_line, "\n";
3680 show_commit_changed_paths($c);
3681 print "\n";
3682 print $_ foreach @$l;
3684 } else {
3685 print "1 line\n";
3686 show_commit_changed_paths($c);
3687 print "\n";
3690 foreach my $x (qw/raw stat diff/) {
3691 if ($c->{$x}) {
3692 print "\n";
3693 print $_ foreach @{$c->{$x}}
3698 sub cmd_show_log {
3699 my (@args) = @_;
3700 my ($r_min, $r_max);
3701 my $r_last = -1; # prevent dupes
3702 if (defined $TZ) {
3703 $ENV{TZ} = $TZ;
3704 } else {
3705 delete $ENV{TZ};
3707 if (defined $::_revision) {
3708 if ($::_revision =~ /^(\d+):(\d+)$/) {
3709 ($r_min, $r_max) = ($1, $2);
3710 } elsif ($::_revision =~ /^\d+$/) {
3711 $r_min = $r_max = $::_revision;
3712 } else {
3713 ::fatal "-r$::_revision is not supported, use ",
3714 "standard \'git log\' arguments instead\n";
3718 config_pager();
3719 @args = git_svn_log_cmd($r_min, $r_max, @args);
3720 my $log = command_output_pipe(@args);
3721 run_pager();
3722 my (@k, $c, $d, $stat);
3723 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3724 while (<$log>) {
3725 if (/^${esc_color}commit ($::sha1_short)/o) {
3726 my $cmt = $1;
3727 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3728 $r_last = $c->{r};
3729 process_commit($c, $r_min, $r_max, \@k) or
3730 goto out;
3732 $d = undef;
3733 $c = { c => $cmt };
3734 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3735 get_author_info($c, $1, $2, $3);
3736 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3737 # ignore
3738 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3739 push @{$c->{raw}}, $_;
3740 } elsif (/^${esc_color}[ACRMDT]\t/) {
3741 # we could add $SVN->{svn_path} here, but that requires
3742 # remote access at the moment (repo_path_split)...
3743 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3744 push @{$c->{changed}}, $_;
3745 } elsif (/^${esc_color}diff /o) {
3746 $d = 1;
3747 push @{$c->{diff}}, $_;
3748 } elsif ($d) {
3749 push @{$c->{diff}}, $_;
3750 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3751 $esc_color*[\+\-]*$esc_color$/x) {
3752 $stat = 1;
3753 push @{$c->{stat}}, $_;
3754 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3755 push @{$c->{stat}}, $_;
3756 $stat = undef;
3757 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3758 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3759 } elsif (s/^${esc_color} //o) {
3760 push @{$c->{l}}, $_;
3763 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3764 $r_last = $c->{r};
3765 process_commit($c, $r_min, $r_max, \@k);
3767 if (@k) {
3768 my $swap = $r_max;
3769 $r_max = $r_min;
3770 $r_min = $swap;
3771 process_commit($_, $r_min, $r_max) foreach reverse @k;
3773 out:
3774 close $log;
3775 print '-' x72,"\n" unless $incremental || $oneline;
3778 package Git::SVN::Migration;
3779 # these version numbers do NOT correspond to actual version numbers
3780 # of git nor git-svn. They are just relative.
3782 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3784 # v1 layout: .git/$id/info/url, refs/remotes/$id
3786 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3788 # v3 layout: .git/svn/$id, refs/remotes/$id
3789 # - info/url may remain for backwards compatibility
3790 # - this is what we migrate up to this layout automatically,
3791 # - this will be used by git svn init on single branches
3792 # v3.1 layout (auto migrated):
3793 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3794 # for backwards compatibility
3796 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3797 # - this is only created for newly multi-init-ed
3798 # repositories. Similar in spirit to the
3799 # --use-separate-remotes option in git-clone (now default)
3800 # - we do not automatically migrate to this (following
3801 # the example set by core git)
3802 use strict;
3803 use warnings;
3804 use Carp qw/croak/;
3805 use File::Path qw/mkpath/;
3806 use File::Basename qw/dirname basename/;
3807 use vars qw/$_minimize/;
3809 sub migrate_from_v0 {
3810 my $git_dir = $ENV{GIT_DIR};
3811 return undef unless -d $git_dir;
3812 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3813 my $migrated = 0;
3814 while (<$fh>) {
3815 chomp;
3816 my ($id, $orig_ref) = ($_, $_);
3817 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3818 next unless -f "$git_dir/$id/info/url";
3819 my $new_ref = "refs/remotes/$id";
3820 if (::verify_ref("$new_ref^0")) {
3821 print STDERR "W: $orig_ref is probably an old ",
3822 "branch used by an ancient version of ",
3823 "git-svn.\n",
3824 "However, $new_ref also exists.\n",
3825 "We will not be able ",
3826 "to use this branch until this ",
3827 "ambiguity is resolved.\n";
3828 next;
3830 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3831 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3832 command_noisy('update-ref', $new_ref, $orig_ref);
3833 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3834 $migrated++;
3836 command_close_pipe($fh, $ctx);
3837 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3838 $migrated;
3841 sub migrate_from_v1 {
3842 my $git_dir = $ENV{GIT_DIR};
3843 my $migrated = 0;
3844 return $migrated unless -d $git_dir;
3845 my $svn_dir = "$git_dir/svn";
3847 # just in case somebody used 'svn' as their $id at some point...
3848 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3850 print STDERR "Migrating from a git-svn v1 layout...\n";
3851 mkpath([$svn_dir]);
3852 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3853 "$svn_dir\n\t(required for this version ",
3854 "($::VERSION) of git-svn) does not. exist\n";
3855 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3856 while (<$fh>) {
3857 my $x = $_;
3858 next unless $x =~ s#^refs/remotes/##;
3859 chomp $x;
3860 next unless -f "$git_dir/$x/info/url";
3861 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3862 next unless $u;
3863 my $dn = dirname("$git_dir/svn/$x");
3864 mkpath([$dn]) unless -d $dn;
3865 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3866 mkpath(["$git_dir/svn/svn"]);
3867 print STDERR " - $git_dir/$x/info => ",
3868 "$git_dir/svn/$x/info\n";
3869 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3870 croak "$!: $x";
3871 # don't worry too much about these, they probably
3872 # don't exist with repos this old (save for index,
3873 # and we can easily regenerate that)
3874 foreach my $f (qw/unhandled.log index .rev_db/) {
3875 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3877 } else {
3878 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3879 rename "$git_dir/$x", "$git_dir/svn/$x" or
3880 croak "$!: $x";
3882 $migrated++;
3884 command_close_pipe($fh, $ctx);
3885 print STDERR "Done migrating from a git-svn v1 layout\n";
3886 $migrated;
3889 sub read_old_urls {
3890 my ($l_map, $pfx, $path) = @_;
3891 my @dir;
3892 foreach (<$path/*>) {
3893 if (-r "$_/info/url") {
3894 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3895 my $ref_id = $pfx . basename $_;
3896 my $url = ::file_to_s("$_/info/url");
3897 $l_map->{$ref_id} = $url;
3898 } elsif (-d $_) {
3899 push @dir, $_;
3902 foreach (@dir) {
3903 my $x = $_;
3904 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3905 read_old_urls($l_map, $x, $_);
3909 sub migrate_from_v2 {
3910 my @cfg = command(qw/config -l/);
3911 return if grep /^svn-remote\..+\.url=/, @cfg;
3912 my %l_map;
3913 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3914 my $migrated = 0;
3916 foreach my $ref_id (sort keys %l_map) {
3917 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3918 if ($@) {
3919 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3921 $migrated++;
3923 $migrated;
3926 sub minimize_connections {
3927 my $r = Git::SVN::read_all_remotes();
3928 my $new_urls = {};
3929 my $root_repos = {};
3930 foreach my $repo_id (keys %$r) {
3931 my $url = $r->{$repo_id}->{url} or next;
3932 my $fetch = $r->{$repo_id}->{fetch} or next;
3933 my $ra = Git::SVN::Ra->new($url);
3935 # skip existing cases where we already connect to the root
3936 if (($ra->{url} eq $ra->{repos_root}) ||
3937 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3938 $repo_id)) {
3939 $root_repos->{$ra->{url}} = $repo_id;
3940 next;
3943 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3944 my $root_path = $ra->{url};
3945 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3946 foreach my $path (keys %$fetch) {
3947 my $ref_id = $fetch->{$path};
3948 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3950 # make sure we can read when connecting to
3951 # a higher level of a repository
3952 my ($last_rev, undef) = $gs->last_rev_commit;
3953 if (!defined $last_rev) {
3954 $last_rev = eval {
3955 $root_ra->get_latest_revnum;
3957 next if $@;
3959 my $new = $root_path;
3960 $new .= length $path ? "/$path" : '';
3961 eval {
3962 $root_ra->get_log([$new], $last_rev, $last_rev,
3963 0, 0, 1, sub { });
3965 next if $@;
3966 $new_urls->{$ra->{repos_root}}->{$new} =
3967 { ref_id => $ref_id,
3968 old_repo_id => $repo_id,
3969 old_path => $path };
3973 my @emptied;
3974 foreach my $url (keys %$new_urls) {
3975 # see if we can re-use an existing [svn-remote "repo_id"]
3976 # instead of creating a(n ugly) new section:
3977 my $repo_id = $root_repos->{$url} ||
3978 Git::SVN::sanitize_remote_name($url);
3980 my $fetch = $new_urls->{$url};
3981 foreach my $path (keys %$fetch) {
3982 my $x = $fetch->{$path};
3983 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3984 my $pfx = "svn-remote.$x->{old_repo_id}";
3986 my $old_fetch = quotemeta("$x->{old_path}:".
3987 "refs/remotes/$x->{ref_id}");
3988 command_noisy(qw/config --unset/,
3989 "$pfx.fetch", '^'. $old_fetch . '$');
3990 delete $r->{$x->{old_repo_id}}->
3991 {fetch}->{$x->{old_path}};
3992 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3993 command_noisy(qw/config --unset/,
3994 "$pfx.url");
3995 push @emptied, $x->{old_repo_id}
3999 if (@emptied) {
4000 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4001 "$ENV{GIT_DIR}/config";
4002 print STDERR <<EOF;
4003 The following [svn-remote] sections in your config file ($file) are empty
4004 and can be safely removed:
4006 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4010 sub migration_check {
4011 migrate_from_v0();
4012 migrate_from_v1();
4013 migrate_from_v2();
4014 minimize_connections() if $_minimize;
4017 package Git::IndexInfo;
4018 use strict;
4019 use warnings;
4020 use Git qw/command_input_pipe command_close_pipe/;
4022 sub new {
4023 my ($class) = @_;
4024 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4025 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4028 sub remove {
4029 my ($self, $path) = @_;
4030 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4031 return ++$self->{nr};
4033 undef;
4036 sub update {
4037 my ($self, $mode, $hash, $path) = @_;
4038 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4039 return ++$self->{nr};
4041 undef;
4044 sub DESTROY {
4045 my ($self) = @_;
4046 command_close_pipe($self->{gui}, $self->{ctx});
4049 package Git::SVN::GlobSpec;
4050 use strict;
4051 use warnings;
4053 sub new {
4054 my ($class, $glob) = @_;
4055 my $re = $glob;
4056 $re =~ s!/+$!!g; # no need for trailing slashes
4057 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4058 my ($left, $right) = ($1, $2);
4059 if ($nr > 1) {
4060 die "Only one '*' wildcard expansion ",
4061 "is supported (got $nr): '$glob'\n";
4062 } elsif ($nr == 0) {
4063 die "One '*' is needed for glob: '$glob'\n";
4065 $re = quotemeta($left) . $re . quotemeta($right);
4066 if (length $left && !($left =~ s!/+$!!g)) {
4067 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4069 if (length $right && !($right =~ s!^/+!!g)) {
4070 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4072 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4073 bless { left => $left, right => $right, left_regex => $left_re,
4074 regex => qr/$re/, glob => $glob }, $class;
4077 sub full_path {
4078 my ($self, $path) = @_;
4079 return (length $self->{left} ? "$self->{left}/" : '') .
4080 $path . (length $self->{right} ? "/$self->{right}" : '');
4083 __END__
4085 Data structures:
4088 $remotes = { # returned by read_all_remotes()
4089 'svn' => {
4090 # svn-remote.svn.url=https://svn.musicpd.org
4091 url => 'https://svn.musicpd.org',
4092 # svn-remote.svn.fetch=mpd/trunk:trunk
4093 fetch => {
4094 'mpd/trunk' => 'trunk',
4096 # svn-remote.svn.tags=mpd/tags/*:tags/*
4097 tags => {
4098 path => {
4099 left => 'mpd/tags',
4100 right => '',
4101 regex => qr!mpd/tags/([^/]+)$!,
4102 glob => 'tags/*',
4104 ref => {
4105 left => 'tags',
4106 right => '',
4107 regex => qr!tags/([^/]+)$!,
4108 glob => 'tags/*',
4114 $log_entry hashref as returned by libsvn_log_entry()
4116 log => 'whitespace-formatted log entry
4117 ', # trailing newline is preserved
4118 revision => '8', # integer
4119 date => '2004-02-24T17:01:44.108345Z', # commit date
4120 author => 'committer name'
4124 # this is generated by generate_diff();
4125 @mods = array of diff-index line hashes, each element represents one line
4126 of diff-index output
4128 diff-index line ($m hash)
4130 mode_a => first column of diff-index output, no leading ':',
4131 mode_b => second column of diff-index output,
4132 sha1_b => sha1sum of the final blob,
4133 chg => change type [MCRADT],
4134 file_a => original file name of a file (iff chg is 'C' or 'R')
4135 file_b => new/current file name of a file (any chg)
4139 # retval of read_url_paths{,_all}();
4140 $l_map = {
4141 # repository root url
4142 'https://svn.musicpd.org' => {
4143 # repository path # GIT_SVN_ID
4144 'mpd/trunk' => 'trunk',
4145 'mpd/tags/0.11.5' => 'tags/0.11.5',
4149 Notes:
4150 I don't trust the each() function on unless I created %hash myself
4151 because the internal iterator may not have started at base.