Use strbuf API in cache-tree.c
[git.git] / git-svn.perl
blobd3c8cd0b8e3cfb97c6deb2453097c6f2e16e3bcf
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 if ($_no_rebase && scalar(@$linear_refs) > 1) {
388 warn "Attempting to commit more than one change while ",
389 "--no-rebase is enabled.\n",
390 "If these changes depend on each other, re-running ",
391 "without --no-rebase will be required."
393 foreach my $d (@$linear_refs) {
394 unless (defined $last_rev) {
395 (undef, $last_rev, undef) = cmt_metadata("$d~1");
396 unless (defined $last_rev) {
397 fatal "Unable to extract revision information ",
398 "from commit $d~1\n";
401 if ($_dry_run) {
402 print "diff-tree $d~1 $d\n";
403 } else {
404 my $cmt_rev;
405 my %ed_opts = ( r => $last_rev,
406 log => get_commit_entry($d)->{log},
407 ra => Git::SVN::Ra->new($gs->full_url),
408 tree_a => "$d~1",
409 tree_b => $d,
410 editor_cb => sub {
411 print "Committed r$_[0]\n";
412 $cmt_rev = $_[0];
414 svn_path => '');
415 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
416 print "No changes\n$d~1 == $d\n";
417 } elsif ($parents->{$d} && @{$parents->{$d}}) {
418 $gs->{inject_parents_dcommit}->{$cmt_rev} =
419 $parents->{$d};
421 $_fetch_all ? $gs->fetch_all : $gs->fetch;
422 next if $_no_rebase;
424 # we always want to rebase against the current HEAD,
425 # not any head that was passed to us
426 my @diff = command('diff-tree', 'HEAD',
427 $gs->refname, '--');
428 my @finish;
429 if (@diff) {
430 @finish = rebase_cmd();
431 print STDERR "W: HEAD and ", $gs->refname,
432 " differ, using @finish:\n",
433 "@diff";
434 } else {
435 print "No changes between current HEAD and ",
436 $gs->refname,
437 "\nResetting to the latest ",
438 $gs->refname, "\n";
439 @finish = qw/reset --mixed/;
441 command_noisy(@finish, $gs->refname);
442 $last_rev = $cmt_rev;
447 sub cmd_find_rev {
448 my $revision_or_hash = shift;
449 my $result;
450 if ($revision_or_hash =~ /^r\d+$/) {
451 my $head = shift;
452 $head ||= 'HEAD';
453 my @refs;
454 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
455 unless ($gs) {
456 die "Unable to determine upstream SVN information from ",
457 "$head history\n";
459 my $desired_revision = substr($revision_or_hash, 1);
460 $result = $gs->rev_db_get($desired_revision);
461 } else {
462 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
463 $result = $rev;
465 print "$result\n" if $result;
468 sub cmd_rebase {
469 command_noisy(qw/update-index --refresh/);
470 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
471 unless ($gs) {
472 die "Unable to determine upstream SVN information from ",
473 "working tree history\n";
475 if (command(qw/diff-index HEAD --/)) {
476 print STDERR "Cannot rebase with uncommited changes:\n";
477 command_noisy('status');
478 exit 1;
480 unless ($_local) {
481 $_fetch_all ? $gs->fetch_all : $gs->fetch;
483 command_noisy(rebase_cmd(), $gs->refname);
486 sub cmd_show_ignore {
487 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
488 $gs ||= Git::SVN->new;
489 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
490 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
493 sub cmd_multi_init {
494 my $url = shift;
495 unless (defined $_trunk || defined $_branches || defined $_tags) {
496 usage(1);
499 # there are currently some bugs that prevent multi-init/multi-fetch
500 # setups from working well without this.
501 $Git::SVN::_minimize_url = 1;
503 $_prefix = '' unless defined $_prefix;
504 if (defined $url) {
505 $url =~ s#/+$##;
506 init_subdir(@_);
508 do_git_init_db();
509 if (defined $_trunk) {
510 my $trunk_ref = $_prefix . 'trunk';
511 # try both old-style and new-style lookups:
512 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
513 unless ($gs_trunk) {
514 my ($trunk_url, $trunk_path) =
515 complete_svn_url($url, $_trunk);
516 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
517 undef, $trunk_ref);
520 return unless defined $_branches || defined $_tags;
521 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
522 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
523 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
526 sub cmd_multi_fetch {
527 my $remotes = Git::SVN::read_all_remotes();
528 foreach my $repo_id (sort keys %$remotes) {
529 if ($remotes->{$repo_id}->{url}) {
530 Git::SVN::fetch_all($repo_id, $remotes);
535 # this command is special because it requires no metadata
536 sub cmd_commit_diff {
537 my ($ta, $tb, $url) = @_;
538 my $usage = "Usage: $0 commit-diff -r<revision> ".
539 "<tree-ish> <tree-ish> [<URL>]\n";
540 fatal($usage) if (!defined $ta || !defined $tb);
541 my $svn_path;
542 if (!defined $url) {
543 my $gs = eval { Git::SVN->new };
544 if (!$gs) {
545 fatal("Needed URL or usable git-svn --id in ",
546 "the command-line\n", $usage);
548 $url = $gs->{url};
549 $svn_path = $gs->{path};
551 unless (defined $_revision) {
552 fatal("-r|--revision is a required argument\n", $usage);
554 if (defined $_message && defined $_file) {
555 fatal("Both --message/-m and --file/-F specified ",
556 "for the commit message.\n",
557 "I have no idea what you mean\n");
559 if (defined $_file) {
560 $_message = file_to_s($_file);
561 } else {
562 $_message ||= get_commit_entry($tb)->{log};
564 my $ra ||= Git::SVN::Ra->new($url);
565 $svn_path ||= $ra->{svn_path};
566 my $r = $_revision;
567 if ($r eq 'HEAD') {
568 $r = $ra->get_latest_revnum;
569 } elsif ($r !~ /^\d+$/) {
570 die "revision argument: $r not understood by git-svn\n";
572 my %ed_opts = ( r => $r,
573 log => $_message,
574 ra => $ra,
575 tree_a => $ta,
576 tree_b => $tb,
577 editor_cb => sub { print "Committed r$_[0]\n" },
578 svn_path => $svn_path );
579 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
580 print "No changes\n$ta == $tb\n";
584 ########################### utility functions #########################
586 sub rebase_cmd {
587 my @cmd = qw/rebase/;
588 push @cmd, '-v' if $_verbose;
589 push @cmd, qw/--merge/ if $_merge;
590 push @cmd, "--strategy=$_strategy" if $_strategy;
591 @cmd;
594 sub post_fetch_checkout {
595 return if $_no_checkout;
596 my $gs = $Git::SVN::_head or return;
597 return if verify_ref('refs/heads/master^0');
599 my $valid_head = verify_ref('HEAD^0');
600 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
601 return if ($valid_head || !verify_ref('HEAD^0'));
603 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
604 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
605 return if -f $index;
607 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
608 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
609 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
610 print STDERR "Checked out HEAD:\n ",
611 $gs->full_url, " r", $gs->last_rev, "\n";
614 sub complete_svn_url {
615 my ($url, $path) = @_;
616 $path =~ s#/+$##;
617 if ($path !~ m#^[a-z\+]+://#) {
618 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
619 fatal("E: '$path' is not a complete URL ",
620 "and a separate URL is not specified\n");
622 return ($url, $path);
624 return ($path, '');
627 sub complete_url_ls_init {
628 my ($ra, $repo_path, $switch, $pfx) = @_;
629 unless ($repo_path) {
630 print STDERR "W: $switch not specified\n";
631 return;
633 $repo_path =~ s#/+$##;
634 if ($repo_path =~ m#^[a-z\+]+://#) {
635 $ra = Git::SVN::Ra->new($repo_path);
636 $repo_path = '';
637 } else {
638 $repo_path =~ s#^/+##;
639 unless ($ra) {
640 fatal("E: '$repo_path' is not a complete URL ",
641 "and a separate URL is not specified\n");
644 my $url = $ra->{url};
645 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
646 my $k = "svn-remote.$gs->{repo_id}.url";
647 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
648 if ($orig_url && ($orig_url ne $gs->{url})) {
649 die "$k already set: $orig_url\n",
650 "wanted to set to: $gs->{url}\n";
652 command_oneline('config', $k, $gs->{url}) unless $orig_url;
653 my $remote_path = "$ra->{svn_path}/$repo_path/*";
654 $remote_path =~ s#/+#/#g;
655 $remote_path =~ s#^/##g;
656 my ($n) = ($switch =~ /^--(\w+)/);
657 if (length $pfx && $pfx !~ m#/$#) {
658 die "--prefix='$pfx' must have a trailing slash '/'\n";
660 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
661 "$remote_path:refs/remotes/$pfx*");
664 sub verify_ref {
665 my ($ref) = @_;
666 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
667 { STDERR => 0 }); };
670 sub get_tree_from_treeish {
671 my ($treeish) = @_;
672 # $treeish can be a symbolic ref, too:
673 my $type = command_oneline(qw/cat-file -t/, $treeish);
674 my $expected;
675 while ($type eq 'tag') {
676 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
678 if ($type eq 'commit') {
679 $expected = (grep /^tree /, command(qw/cat-file commit/,
680 $treeish))[0];
681 ($expected) = ($expected =~ /^tree ($sha1)$/o);
682 die "Unable to get tree from $treeish\n" unless $expected;
683 } elsif ($type eq 'tree') {
684 $expected = $treeish;
685 } else {
686 die "$treeish is a $type, expected tree, tag or commit\n";
688 return $expected;
691 sub get_commit_entry {
692 my ($treeish) = shift;
693 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
694 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
695 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
696 open my $log_fh, '>', $commit_editmsg or croak $!;
698 my $type = command_oneline(qw/cat-file -t/, $treeish);
699 if ($type eq 'commit' || $type eq 'tag') {
700 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
701 $type, $treeish);
702 my $in_msg = 0;
703 while (<$msg_fh>) {
704 if (!$in_msg) {
705 $in_msg = 1 if (/^\s*$/);
706 } elsif (/^git-svn-id: /) {
707 # skip this for now, we regenerate the
708 # correct one on re-fetch anyways
709 # TODO: set *:merge properties or like...
710 } else {
711 print $log_fh $_ or croak $!;
714 command_close_pipe($msg_fh, $ctx);
716 close $log_fh or croak $!;
718 if ($_edit || ($type eq 'tree')) {
719 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
720 # TODO: strip out spaces, comments, like git-commit.sh
721 system($editor, $commit_editmsg);
723 rename $commit_editmsg, $commit_msg or croak $!;
724 open $log_fh, '<', $commit_msg or croak $!;
725 { local $/; chomp($log_entry{log} = <$log_fh>); }
726 close $log_fh or croak $!;
727 unlink $commit_msg;
728 \%log_entry;
731 sub s_to_file {
732 my ($str, $file, $mode) = @_;
733 open my $fd,'>',$file or croak $!;
734 print $fd $str,"\n" or croak $!;
735 close $fd or croak $!;
736 chmod ($mode &~ umask, $file) if (defined $mode);
739 sub file_to_s {
740 my $file = shift;
741 open my $fd,'<',$file or croak "$!: file: $file\n";
742 local $/;
743 my $ret = <$fd>;
744 close $fd or croak $!;
745 $ret =~ s/\s*$//s;
746 return $ret;
749 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
750 sub load_authors {
751 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
752 my $log = $cmd eq 'log';
753 while (<$authors>) {
754 chomp;
755 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
756 my ($user, $name, $email) = ($1, $2, $3);
757 if ($log) {
758 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
759 } else {
760 $users{$user} = [$name, $email];
763 close $authors or croak $!;
766 # convert GetOpt::Long specs for use by git-config
767 sub read_repo_config {
768 return unless -d $ENV{GIT_DIR};
769 my $opts = shift;
770 my @config_only;
771 foreach my $o (keys %$opts) {
772 # if we have mixedCase and a long option-only, then
773 # it's a config-only variable that we don't need for
774 # the command-line.
775 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
776 my $v = $opts->{$o};
777 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
778 $key =~ s/-//g;
779 my $arg = 'git-config';
780 $arg .= ' --int' if ($o =~ /[:=]i$/);
781 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
782 if (ref $v eq 'ARRAY') {
783 chomp(my @tmp = `$arg --get-all svn.$key`);
784 @$v = @tmp if @tmp;
785 } else {
786 chomp(my $tmp = `$arg --get svn.$key`);
787 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
788 $$v = $tmp;
792 delete @$opts{@config_only} if @config_only;
795 sub extract_metadata {
796 my $id = shift or return (undef, undef, undef);
797 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
798 \s([a-f\d\-]+)$/x);
799 if (!defined $rev || !$uuid || !$url) {
800 # some of the original repositories I made had
801 # identifiers like this:
802 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
804 return ($url, $rev, $uuid);
807 sub cmt_metadata {
808 return extract_metadata((grep(/^git-svn-id: /,
809 command(qw/cat-file commit/, shift)))[-1]);
812 sub working_head_info {
813 my ($head, $refs) = @_;
814 my ($fh, $ctx) = command_output_pipe('log', '--no-color', $head);
815 my $hash;
816 my %max;
817 while (<$fh>) {
818 if ( m{^commit ($::sha1)$} ) {
819 unshift @$refs, $hash if $hash and $refs;
820 $hash = $1;
821 next;
823 next unless s{^\s*(git-svn-id:)}{$1};
824 my ($url, $rev, $uuid) = extract_metadata($_);
825 if (defined $url && defined $rev) {
826 next if $max{$url} and $max{$url} < $rev;
827 if (my $gs = Git::SVN->find_by_url($url)) {
828 my $c = $gs->rev_db_get($rev);
829 if ($c && $c eq $hash) {
830 close $fh; # break the pipe
831 return ($url, $rev, $uuid, $gs);
832 } else {
833 $max{$url} ||= $gs->rev_db_max;
838 command_close_pipe($fh, $ctx);
839 (undef, undef, undef, undef);
842 sub read_commit_parents {
843 my ($parents, $c) = @_;
844 my ($fh, $ctx) = command_output_pipe(qw/cat-file commit/, $c);
845 while (<$fh>) {
846 chomp;
847 last if '';
848 /^parent ($sha1)/ or next;
849 push @{$parents->{$c}}, $1;
851 close $fh; # break the pipe
854 sub linearize_history {
855 my ($gs, $refs) = @_;
856 my %parents;
857 foreach my $c (@$refs) {
858 read_commit_parents(\%parents, $c);
861 my @linear_refs;
862 my %skip = ();
863 my $last_svn_commit = $gs->last_commit;
864 foreach my $c (reverse @$refs) {
865 next if $c eq $last_svn_commit;
866 last if $skip{$c};
868 unshift @linear_refs, $c;
869 $skip{$c} = 1;
871 # we only want the first parent to diff against for linear
872 # history, we save the rest to inject when we finalize the
873 # svn commit
874 my $fp_a = verify_ref("$c~1");
875 my $fp_b = shift @{$parents{$c}} if $parents{$c};
876 if (!$fp_a || !$fp_b) {
877 die "Commit $c\n",
878 "has no parent commit, and therefore ",
879 "nothing to diff against.\n",
880 "You should be working from a repository ",
881 "originally created by git-svn\n";
883 if ($fp_a ne $fp_b) {
884 die "$c~1 = $fp_a, however parsing commit $c ",
885 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
888 foreach my $p (@{$parents{$c}}) {
889 $skip{$p} = 1;
892 (\@linear_refs, \%parents);
895 package Git::SVN;
896 use strict;
897 use warnings;
898 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
899 $_repack $_repack_flags $_use_svm_props $_head
900 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
901 use Carp qw/croak/;
902 use File::Path qw/mkpath/;
903 use File::Copy qw/copy/;
904 use IPC::Open3;
906 my $_repack_nr;
907 # properties that we do not log:
908 my %SKIP_PROP;
909 BEGIN {
910 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
911 svn:special svn:executable
912 svn:entry:committed-rev
913 svn:entry:last-author
914 svn:entry:uuid
915 svn:entry:committed-date/;
917 # some options are read globally, but can be overridden locally
918 # per [svn-remote "..."] section. Command-line options will *NOT*
919 # override options set in an [svn-remote "..."] section
920 no strict 'refs';
921 for my $option (qw/follow_parent no_metadata use_svm_props
922 use_svnsync_props/) {
923 my $key = $option;
924 $key =~ tr/_//d;
925 my $prop = "-$option";
926 *$option = sub {
927 my ($self) = @_;
928 return $self->{$prop} if exists $self->{$prop};
929 my $k = "svn-remote.$self->{repo_id}.$key";
930 eval { command_oneline(qw/config --get/, $k) };
931 if ($@) {
932 $self->{$prop} = ${"Git::SVN::_$option"};
933 } else {
934 my $v = command_oneline(qw/config --bool/,$k);
935 $self->{$prop} = $v eq 'false' ? 0 : 1;
937 return $self->{$prop};
942 my %LOCKFILES;
943 END { unlink keys %LOCKFILES if %LOCKFILES }
945 sub resolve_local_globs {
946 my ($url, $fetch, $glob_spec) = @_;
947 return unless defined $glob_spec;
948 my $ref = $glob_spec->{ref};
949 my $path = $glob_spec->{path};
950 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
951 next unless m#^refs/remotes/$ref->{regex}$#;
952 my $p = $1;
953 my $pathname = desanitize_refname($path->full_path($p));
954 my $refname = desanitize_refname($ref->full_path($p));
955 if (my $existing = $fetch->{$pathname}) {
956 if ($existing ne $refname) {
957 die "Refspec conflict:\n",
958 "existing: refs/remotes/$existing\n",
959 " globbed: refs/remotes/$refname\n";
961 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
962 $u =~ s!^\Q$url\E(/|$)!! or die
963 "refs/remotes/$refname: '$url' not found in '$u'\n";
964 if ($pathname ne $u) {
965 warn "W: Refspec glob conflict ",
966 "(ref: refs/remotes/$refname):\n",
967 "expected path: $pathname\n",
968 " real path: $u\n",
969 "Continuing ahead with $u\n";
970 next;
972 } else {
973 $fetch->{$pathname} = $refname;
978 sub parse_revision_argument {
979 my ($base, $head) = @_;
980 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
981 return ($base, $head);
983 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
984 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
985 return ($head, $head) if ($::_revision eq 'HEAD');
986 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
987 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
988 die "revision argument: $::_revision not understood by git-svn\n";
991 sub fetch_all {
992 my ($repo_id, $remotes) = @_;
993 if (ref $repo_id) {
994 my $gs = $repo_id;
995 $repo_id = undef;
996 $repo_id = $gs->{repo_id};
998 $remotes ||= read_all_remotes();
999 my $remote = $remotes->{$repo_id} or
1000 die "[svn-remote \"$repo_id\"] unknown\n";
1001 my $fetch = $remote->{fetch};
1002 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1003 my (@gs, @globs);
1004 my $ra = Git::SVN::Ra->new($url);
1005 my $uuid = $ra->get_uuid;
1006 my $head = $ra->get_latest_revnum;
1007 my $base = defined $fetch ? $head : 0;
1009 # read the max revs for wildcard expansion (branches/*, tags/*)
1010 foreach my $t (qw/branches tags/) {
1011 defined $remote->{$t} or next;
1012 push @globs, $remote->{$t};
1013 my $max_rev = eval { tmp_config(qw/--int --get/,
1014 "svn-remote.$repo_id.${t}-maxRev") };
1015 if (defined $max_rev && ($max_rev < $base)) {
1016 $base = $max_rev;
1017 } elsif (!defined $max_rev) {
1018 $base = 0;
1022 if ($fetch) {
1023 foreach my $p (sort keys %$fetch) {
1024 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1025 my $lr = $gs->rev_db_max;
1026 if (defined $lr) {
1027 $base = $lr if ($lr < $base);
1029 push @gs, $gs;
1033 ($base, $head) = parse_revision_argument($base, $head);
1034 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1037 sub read_all_remotes {
1038 my $r = {};
1039 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1040 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1041 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1042 $local_ref =~ s{^/}{};
1043 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1044 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1045 $r->{$1}->{url} = $2;
1046 } elsif (m!^(.+)\.(branches|tags)=
1047 (.*):refs/remotes/(.+)\s*$/!x) {
1048 my ($p, $g) = ($3, $4);
1049 my $rs = $r->{$1}->{$2} = {
1050 t => $2,
1051 remote => $1,
1052 path => Git::SVN::GlobSpec->new($p),
1053 ref => Git::SVN::GlobSpec->new($g) };
1054 if (length($rs->{ref}->{right}) != 0) {
1055 die "The '*' glob character must be the last ",
1056 "character of '$g'\n";
1063 sub init_vars {
1064 if (defined $_repack) {
1065 $_repack = 1000 if ($_repack <= 0);
1066 $_repack_nr = $_repack;
1067 $_repack_flags ||= '-d';
1071 sub verify_remotes_sanity {
1072 return unless -d $ENV{GIT_DIR};
1073 my %seen;
1074 foreach (command(qw/config -l/)) {
1075 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1076 if ($seen{$1}) {
1077 die "Remote ref refs/remote/$1 is tracked by",
1078 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1079 "Please resolve this ambiguity in ",
1080 "your git configuration file before ",
1081 "continuing\n";
1083 $seen{$1} = $_;
1088 # we allow more chars than remotes2config.sh...
1089 sub sanitize_remote_name {
1090 my ($name) = @_;
1091 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1092 $name;
1095 sub find_existing_remote {
1096 my ($url, $remotes) = @_;
1097 return undef if $no_reuse_existing;
1098 my $existing;
1099 foreach my $repo_id (keys %$remotes) {
1100 my $u = $remotes->{$repo_id}->{url} or next;
1101 next if $u ne $url;
1102 $existing = $repo_id;
1103 last;
1105 $existing;
1108 sub init_remote_config {
1109 my ($self, $url, $no_write) = @_;
1110 $url =~ s!/+$!!; # strip trailing slash
1111 my $r = read_all_remotes();
1112 my $existing = find_existing_remote($url, $r);
1113 if ($existing) {
1114 unless ($no_write) {
1115 print STDERR "Using existing ",
1116 "[svn-remote \"$existing\"]\n";
1118 $self->{repo_id} = $existing;
1119 } elsif ($_minimize_url) {
1120 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1121 $existing = find_existing_remote($min_url, $r);
1122 if ($existing) {
1123 unless ($no_write) {
1124 print STDERR "Using existing ",
1125 "[svn-remote \"$existing\"]\n";
1127 $self->{repo_id} = $existing;
1129 if ($min_url ne $url) {
1130 unless ($no_write) {
1131 print STDERR "Using higher level of URL: ",
1132 "$url => $min_url\n";
1134 my $old_path = $self->{path};
1135 $self->{path} = $url;
1136 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1137 if (length $old_path) {
1138 $self->{path} .= "/$old_path";
1140 $url = $min_url;
1143 my $orig_url;
1144 if (!$existing) {
1145 # verify that we aren't overwriting anything:
1146 $orig_url = eval {
1147 command_oneline('config', '--get',
1148 "svn-remote.$self->{repo_id}.url")
1150 if ($orig_url && ($orig_url ne $url)) {
1151 die "svn-remote.$self->{repo_id}.url already set: ",
1152 "$orig_url\nwanted to set to: $url\n";
1155 my ($xrepo_id, $xpath) = find_ref($self->refname);
1156 if (defined $xpath) {
1157 die "svn-remote.$xrepo_id.fetch already set to track ",
1158 "$xpath:refs/remotes/", $self->refname, "\n";
1160 unless ($no_write) {
1161 command_noisy('config',
1162 "svn-remote.$self->{repo_id}.url", $url);
1163 $self->{path} =~ s{^/}{};
1164 command_noisy('config', '--add',
1165 "svn-remote.$self->{repo_id}.fetch",
1166 "$self->{path}:".$self->refname);
1168 $self->{url} = $url;
1171 sub find_by_url { # repos_root and, path are optional
1172 my ($class, $full_url, $repos_root, $path) = @_;
1174 return undef unless defined $full_url;
1175 remove_username($full_url);
1176 remove_username($repos_root) if defined $repos_root;
1177 my $remotes = read_all_remotes();
1178 if (defined $full_url && defined $repos_root && !defined $path) {
1179 $path = $full_url;
1180 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1182 foreach my $repo_id (keys %$remotes) {
1183 my $u = $remotes->{$repo_id}->{url} or next;
1184 remove_username($u);
1185 next if defined $repos_root && $repos_root ne $u;
1187 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1188 foreach (qw/branches tags/) {
1189 resolve_local_globs($u, $fetch,
1190 $remotes->{$repo_id}->{$_});
1192 my $p = $path;
1193 unless (defined $p) {
1194 $p = $full_url;
1195 $p =~ s#^\Q$u\E(?:/|$)## or next;
1197 foreach my $f (keys %$fetch) {
1198 next if $f ne $p;
1199 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1202 undef;
1205 sub init {
1206 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1207 my $self = _new($class, $repo_id, $ref_id, $path);
1208 if (defined $url) {
1209 $self->init_remote_config($url, $no_write);
1211 $self;
1214 sub find_ref {
1215 my ($ref_id) = @_;
1216 foreach (command(qw/config -l/)) {
1217 next unless m!^svn-remote\.(.+)\.fetch=
1218 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1219 my ($repo_id, $path, $ref) = ($1, $2, $3);
1220 if ($ref eq $ref_id) {
1221 $path = '' if ($path =~ m#^\./?#);
1222 return ($repo_id, $path);
1225 (undef, undef, undef);
1228 sub new {
1229 my ($class, $ref_id, $repo_id, $path) = @_;
1230 if (defined $ref_id && !defined $repo_id && !defined $path) {
1231 ($repo_id, $path) = find_ref($ref_id);
1232 if (!defined $repo_id) {
1233 die "Could not find a \"svn-remote.*.fetch\" key ",
1234 "in the repository configuration matching: ",
1235 "refs/remotes/$ref_id\n";
1238 my $self = _new($class, $repo_id, $ref_id, $path);
1239 if (!defined $self->{path} || !length $self->{path}) {
1240 my $fetch = command_oneline('config', '--get',
1241 "svn-remote.$repo_id.fetch",
1242 ":refs/remotes/$ref_id\$") or
1243 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1244 "\":refs/remotes/$ref_id\$\" in config\n";
1245 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1247 $self->{url} = command_oneline('config', '--get',
1248 "svn-remote.$repo_id.url") or
1249 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1250 $self->rebuild;
1251 $self;
1254 sub refname {
1255 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1257 # It cannot end with a slash /, we'll throw up on this because
1258 # SVN can't have directories with a slash in their name, either:
1259 if ($refname =~ m{/$}) {
1260 die "ref: '$refname' ends with a trailing slash, this is ",
1261 "not permitted by git nor Subversion\n";
1264 # It cannot have ASCII control character space, tilde ~, caret ^,
1265 # colon :, question-mark ?, asterisk *, space, or open bracket [
1266 # anywhere.
1268 # Additionally, % must be escaped because it is used for escaping
1269 # and we want our escaped refname to be reversible
1270 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1272 # no slash-separated component can begin with a dot .
1273 # /.* becomes /%2E*
1274 $refname =~ s{/\.}{/%2E}g;
1276 # It cannot have two consecutive dots .. anywhere
1277 # .. becomes %2E%2E
1278 $refname =~ s{\.\.}{%2E%2E}g;
1280 return $refname;
1283 sub desanitize_refname {
1284 my ($refname) = @_;
1285 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1286 return $refname;
1289 sub svm_uuid {
1290 my ($self) = @_;
1291 return $self->{svm}->{uuid} if $self->svm;
1292 $self->ra;
1293 unless ($self->{svm}) {
1294 die "SVM UUID not cached, and reading remotely failed\n";
1296 $self->{svm}->{uuid};
1299 sub svm {
1300 my ($self) = @_;
1301 return $self->{svm} if $self->{svm};
1302 my $svm;
1303 # see if we have it in our config, first:
1304 eval {
1305 my $section = "svn-remote.$self->{repo_id}";
1306 $svm = {
1307 source => tmp_config('--get', "$section.svm-source"),
1308 uuid => tmp_config('--get', "$section.svm-uuid"),
1309 replace => tmp_config('--get', "$section.svm-replace"),
1312 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1313 $self->{svm} = $svm;
1315 $self->{svm};
1318 sub _set_svm_vars {
1319 my ($self, $ra) = @_;
1320 return $ra if $self->svm;
1322 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1323 "(svm:source, svm:uuid) ",
1324 "from the following URLs:\n" );
1325 sub read_svm_props {
1326 my ($self, $ra, $path, $r) = @_;
1327 my $props = ($ra->get_dir($path, $r))[2];
1328 my $src = $props->{'svm:source'};
1329 my $uuid = $props->{'svm:uuid'};
1330 return undef if (!$src || !$uuid);
1332 chomp($src, $uuid);
1334 $uuid =~ m{^[0-9a-f\-]{30,}$}
1335 or die "doesn't look right - svm:uuid is '$uuid'\n";
1337 # the '!' is used to mark the repos_root!/relative/path
1338 $src =~ s{/?!/?}{/};
1339 $src =~ s{/+$}{}; # no trailing slashes please
1340 # username is of no interest
1341 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1343 my $replace = $ra->{url};
1344 $replace .= "/$path" if length $path;
1346 my $section = "svn-remote.$self->{repo_id}";
1347 tmp_config("$section.svm-source", $src);
1348 tmp_config("$section.svm-replace", $replace);
1349 tmp_config("$section.svm-uuid", $uuid);
1350 $self->{svm} = {
1351 source => $src,
1352 uuid => $uuid,
1353 replace => $replace
1357 my $r = $ra->get_latest_revnum;
1358 my $path = $self->{path};
1359 my %tried;
1360 while (length $path) {
1361 unless ($tried{"$self->{url}/$path"}) {
1362 return $ra if $self->read_svm_props($ra, $path, $r);
1363 $tried{"$self->{url}/$path"} = 1;
1365 $path =~ s#/?[^/]+$##;
1367 die "Path: '$path' should be ''\n" if $path ne '';
1368 return $ra if $self->read_svm_props($ra, $path, $r);
1369 $tried{"$self->{url}/$path"} = 1;
1371 if ($ra->{repos_root} eq $self->{url}) {
1372 die @err, (map { " $_\n" } keys %tried), "\n";
1375 # nope, make sure we're connected to the repository root:
1376 my $ok;
1377 my @tried_b;
1378 $path = $ra->{svn_path};
1379 $ra = Git::SVN::Ra->new($ra->{repos_root});
1380 while (length $path) {
1381 unless ($tried{"$ra->{url}/$path"}) {
1382 $ok = $self->read_svm_props($ra, $path, $r);
1383 last if $ok;
1384 $tried{"$ra->{url}/$path"} = 1;
1386 $path =~ s#/?[^/]+$##;
1388 die "Path: '$path' should be ''\n" if $path ne '';
1389 $ok ||= $self->read_svm_props($ra, $path, $r);
1390 $tried{"$ra->{url}/$path"} = 1;
1391 if (!$ok) {
1392 die @err, (map { " $_\n" } keys %tried), "\n";
1394 Git::SVN::Ra->new($self->{url});
1397 sub svnsync {
1398 my ($self) = @_;
1399 return $self->{svnsync} if $self->{svnsync};
1401 if ($self->no_metadata) {
1402 die "Can't have both 'noMetadata' and ",
1403 "'useSvnsyncProps' options set!\n";
1405 if ($self->rewrite_root) {
1406 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1407 "options set!\n";
1410 my $svnsync;
1411 # see if we have it in our config, first:
1412 eval {
1413 my $section = "svn-remote.$self->{repo_id}";
1414 $svnsync = {
1415 url => tmp_config('--get', "$section.svnsync-url"),
1416 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1419 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1420 return $self->{svnsync} = $svnsync;
1423 my $err = "useSvnsyncProps set, but failed to read " .
1424 "svnsync property: svn:sync-from-";
1425 my $rp = $self->ra->rev_proplist(0);
1427 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1428 $url =~ m{^[a-z\+]+://} or
1429 die "doesn't look right - svn:sync-from-url is '$url'\n";
1431 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1432 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1433 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1435 my $section = "svn-remote.$self->{repo_id}";
1436 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1437 tmp_config('--add', "$section.svnsync-url", $url);
1438 return $self->{svnsync} = { url => $url, uuid => $uuid };
1441 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1442 # remote lookup (useful for 'git svn log').
1443 sub ra_uuid {
1444 my ($self) = @_;
1445 unless ($self->{ra_uuid}) {
1446 my $key = "svn-remote.$self->{repo_id}.uuid";
1447 my $uuid = eval { tmp_config('--get', $key) };
1448 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1449 $self->{ra_uuid} = $uuid;
1450 } else {
1451 die "ra_uuid called without URL\n" unless $self->{url};
1452 $self->{ra_uuid} = $self->ra->get_uuid;
1453 tmp_config('--add', $key, $self->{ra_uuid});
1456 $self->{ra_uuid};
1459 sub ra {
1460 my ($self) = shift;
1461 my $ra = Git::SVN::Ra->new($self->{url});
1462 if ($self->use_svm_props && !$self->{svm}) {
1463 if ($self->no_metadata) {
1464 die "Can't have both 'noMetadata' and ",
1465 "'useSvmProps' options set!\n";
1466 } elsif ($self->use_svnsync_props) {
1467 die "Can't have both 'useSvnsyncProps' and ",
1468 "'useSvmProps' options set!\n";
1470 $ra = $self->_set_svm_vars($ra);
1471 $self->{-want_revprops} = 1;
1473 $ra;
1476 sub rel_path {
1477 my ($self) = @_;
1478 my $repos_root = $self->ra->{repos_root};
1479 return $self->{path} if ($self->{url} eq $repos_root);
1480 my $url = $self->{url} .
1481 (length $self->{path} ? "/$self->{path}" : $self->{path});
1482 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1483 $url;
1486 sub traverse_ignore {
1487 my ($self, $fh, $path, $r) = @_;
1488 $path =~ s#^/+##g;
1489 my $ra = $self->ra;
1490 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1491 my $p = $path;
1492 $p =~ s#^\Q$self->{path}\E(/|$)##;
1493 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1494 if (my $s = $props->{'svn:ignore'}) {
1495 $s =~ s/[\r\n]+/\n/g;
1496 chomp $s;
1497 if (length $p == 0) {
1498 $s =~ s#\n#\n/$p#g;
1499 print $fh "/$s\n";
1500 } else {
1501 $s =~ s#\n#\n/$p/#g;
1502 print $fh "/$p/$s\n";
1505 foreach (sort keys %$dirent) {
1506 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1507 $self->traverse_ignore($fh, "$path/$_", $r);
1511 sub last_rev { ($_[0]->last_rev_commit)[0] }
1512 sub last_commit { ($_[0]->last_rev_commit)[1] }
1514 # returns the newest SVN revision number and newest commit SHA1
1515 sub last_rev_commit {
1516 my ($self) = @_;
1517 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1518 return ($self->{last_rev}, $self->{last_commit});
1520 my $c = ::verify_ref($self->refname.'^0');
1521 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1522 my $rev = (::cmt_metadata($c))[1];
1523 if (defined $rev) {
1524 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1525 return ($rev, $c);
1528 my $db_path = $self->db_path;
1529 unless (-e $db_path) {
1530 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1531 return (undef, undef);
1533 my $offset = -41; # from tail
1534 my $rl;
1535 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1536 sysseek($fh, $offset, 2); # don't care for errors
1537 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1538 chomp $rl;
1539 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1540 $offset -= 41;
1541 sysseek($fh, $offset, 2); # don't care for errors
1542 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1543 chomp $rl;
1545 if ($c && $c ne $rl) {
1546 die "$db_path and ", $self->refname,
1547 " inconsistent!:\n$c != $rl\n";
1549 my $rev = sysseek($fh, 0, 1) or croak $!;
1550 $rev = ($rev - 41) / 41;
1551 close $fh or croak $!;
1552 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1553 return ($rev, $c);
1556 sub get_fetch_range {
1557 my ($self, $min, $max) = @_;
1558 $max ||= $self->ra->get_latest_revnum;
1559 $min ||= $self->rev_db_max;
1560 (++$min, $max);
1563 sub tmp_config {
1564 my (@args) = @_;
1565 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1566 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1567 if (! -f $config && -f $old_def_config) {
1568 rename $old_def_config, $config or
1569 die "Failed rename $old_def_config => $config: $!\n";
1571 my $old_config = $ENV{GIT_CONFIG};
1572 $ENV{GIT_CONFIG} = $config;
1573 $@ = undef;
1574 my @ret = eval {
1575 unless (-f $config) {
1576 mkfile($config);
1577 open my $fh, '>', $config or
1578 die "Can't open $config: $!\n";
1579 print $fh "; This file is used internally by ",
1580 "git-svn\n" or die
1581 "Couldn't write to $config: $!\n";
1582 print $fh "; You should not have to edit it\n" or
1583 die "Couldn't write to $config: $!\n";
1584 close $fh or die "Couldn't close $config: $!\n";
1586 command('config', @args);
1588 my $err = $@;
1589 if (defined $old_config) {
1590 $ENV{GIT_CONFIG} = $old_config;
1591 } else {
1592 delete $ENV{GIT_CONFIG};
1594 die $err if $err;
1595 wantarray ? @ret : $ret[0];
1598 sub tmp_index_do {
1599 my ($self, $sub) = @_;
1600 my $old_index = $ENV{GIT_INDEX_FILE};
1601 $ENV{GIT_INDEX_FILE} = $self->{index};
1602 $@ = undef;
1603 my @ret = eval {
1604 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1605 mkpath([$dir]) unless -d $dir;
1606 &$sub;
1608 my $err = $@;
1609 if (defined $old_index) {
1610 $ENV{GIT_INDEX_FILE} = $old_index;
1611 } else {
1612 delete $ENV{GIT_INDEX_FILE};
1614 die $err if $err;
1615 wantarray ? @ret : $ret[0];
1618 sub assert_index_clean {
1619 my ($self, $treeish) = @_;
1621 $self->tmp_index_do(sub {
1622 command_noisy('read-tree', $treeish) unless -e $self->{index};
1623 my $x = command_oneline('write-tree');
1624 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1625 /^tree ($::sha1)/mo);
1626 return if $y eq $x;
1628 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1629 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1630 command_noisy('read-tree', $treeish);
1631 $x = command_oneline('write-tree');
1632 if ($y ne $x) {
1633 ::fatal "trees ($treeish) $y != $x\n",
1634 "Something is seriously wrong...\n";
1639 sub get_commit_parents {
1640 my ($self, $log_entry) = @_;
1641 my (%seen, @ret, @tmp);
1642 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1643 if (my $ip = $self->{inject_parents}) {
1644 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1645 push @tmp, $commit;
1648 if (my $cur = ::verify_ref($self->refname.'^0')) {
1649 push @tmp, $cur;
1651 if (my $ipd = $self->{inject_parents_dcommit}) {
1652 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1653 push @tmp, @$commit;
1656 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1657 while (my $p = shift @tmp) {
1658 next if $seen{$p};
1659 $seen{$p} = 1;
1660 push @ret, $p;
1661 # MAXPARENT is defined to 16 in commit-tree.c:
1662 last if @ret >= 16;
1664 if (@tmp) {
1665 die "r$log_entry->{revision}: No room for parents:\n\t",
1666 join("\n\t", @tmp), "\n";
1668 @ret;
1671 sub rewrite_root {
1672 my ($self) = @_;
1673 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1674 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1675 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1676 if ($rwr) {
1677 $rwr =~ s#/+$##;
1678 if ($rwr !~ m#^[a-z\+]+://#) {
1679 die "$rwr is not a valid URL (key: $k)\n";
1682 $self->{-rewrite_root} = $rwr;
1685 sub metadata_url {
1686 my ($self) = @_;
1687 ($self->rewrite_root || $self->{url}) .
1688 (length $self->{path} ? '/' . $self->{path} : '');
1691 sub full_url {
1692 my ($self) = @_;
1693 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1696 sub do_git_commit {
1697 my ($self, $log_entry) = @_;
1698 my $lr = $self->last_rev;
1699 if (defined $lr && $lr >= $log_entry->{revision}) {
1700 die "Last fetched revision of ", $self->refname,
1701 " was r$lr, but we are about to fetch: ",
1702 "r$log_entry->{revision}!\n";
1704 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1705 croak "$log_entry->{revision} = $c already exists! ",
1706 "Why are we refetching it?\n";
1708 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1709 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1710 $log_entry->{email};
1711 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1713 my $tree = $log_entry->{tree};
1714 if (!defined $tree) {
1715 $tree = $self->tmp_index_do(sub {
1716 command_oneline('write-tree') });
1718 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1720 my @exec = ('git-commit-tree', $tree);
1721 foreach ($self->get_commit_parents($log_entry)) {
1722 push @exec, '-p', $_;
1724 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1725 or croak $!;
1726 print $msg_fh $log_entry->{log} or croak $!;
1727 unless ($self->no_metadata) {
1728 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1729 or croak $!;
1731 $msg_fh->flush == 0 or croak $!;
1732 close $msg_fh or croak $!;
1733 chomp(my $commit = do { local $/; <$out_fh> });
1734 close $out_fh or croak $!;
1735 waitpid $pid, 0;
1736 croak $? if $?;
1737 if ($commit !~ /^$::sha1$/o) {
1738 die "Failed to commit, invalid sha1: $commit\n";
1741 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1743 $self->{last_rev} = $log_entry->{revision};
1744 $self->{last_commit} = $commit;
1745 print "r$log_entry->{revision}";
1746 if (defined $log_entry->{svm_revision}) {
1747 print " (\@$log_entry->{svm_revision})";
1748 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1749 0, $self->svm_uuid);
1751 print " = $commit ($self->{ref_id})\n";
1752 if (defined $_repack && (--$_repack_nr == 0)) {
1753 $_repack_nr = $_repack;
1754 # repack doesn't use any arguments with spaces in them, does it?
1755 print "Running git repack $_repack_flags ...\n";
1756 command_noisy('repack', split(/\s+/, $_repack_flags));
1757 print "Done repacking\n";
1759 return $commit;
1762 sub match_paths {
1763 my ($self, $paths, $r) = @_;
1764 return 1 if $self->{path} eq '';
1765 if (my $path = $paths->{"/$self->{path}"}) {
1766 return ($path->{action} eq 'D') ? 0 : 1;
1768 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1769 if (grep /$self->{path_regex}/, keys %$paths) {
1770 return 1;
1772 my $c = '';
1773 foreach (split m#/#, $self->{path}) {
1774 $c .= "/$_";
1775 next unless ($paths->{$c} &&
1776 ($paths->{$c}->{action} =~ /^[AR]$/));
1777 if ($self->ra->check_path($self->{path}, $r) ==
1778 $SVN::Node::dir) {
1779 return 1;
1782 return 0;
1785 sub find_parent_branch {
1786 my ($self, $paths, $rev) = @_;
1787 return undef unless $self->follow_parent;
1788 unless (defined $paths) {
1789 my $err_handler = $SVN::Error::handler;
1790 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1791 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1792 $paths =
1793 Git::SVN::Ra::dup_changed_paths($_[0]) });
1794 $SVN::Error::handler = $err_handler;
1796 return undef unless defined $paths;
1798 # look for a parent from another branch:
1799 my @b_path_components = split m#/#, $self->rel_path;
1800 my @a_path_components;
1801 my $i;
1802 while (@b_path_components) {
1803 $i = $paths->{'/'.join('/', @b_path_components)};
1804 last if $i && defined $i->{copyfrom_path};
1805 unshift(@a_path_components, pop(@b_path_components));
1807 return undef unless defined $i && defined $i->{copyfrom_path};
1808 my $branch_from = $i->{copyfrom_path};
1809 if (@a_path_components) {
1810 print STDERR "branch_from: $branch_from => ";
1811 $branch_from .= '/'.join('/', @a_path_components);
1812 print STDERR $branch_from, "\n";
1814 my $r = $i->{copyfrom_rev};
1815 my $repos_root = $self->ra->{repos_root};
1816 my $url = $self->ra->{url};
1817 my $new_url = $repos_root . $branch_from;
1818 print STDERR "Found possible branch point: ",
1819 "$new_url => ", $self->full_url, ", $r\n";
1820 $branch_from =~ s#^/##;
1821 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1822 unless ($gs) {
1823 my $ref_id = $self->{ref_id};
1824 $ref_id =~ s/\@\d+$//;
1825 $ref_id .= "\@$r";
1826 # just grow a tail if we're not unique enough :x
1827 $ref_id .= '-' while find_ref($ref_id);
1828 print STDERR "Initializing parent: $ref_id\n";
1829 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1831 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1832 if (!defined $r0 || !defined $parent) {
1833 my ($base, $head) = parse_revision_argument(0, $r);
1834 if ($base <= $r) {
1835 $gs->fetch($base, $r);
1837 ($r0, $parent) = $gs->last_rev_commit;
1839 if (defined $r0 && defined $parent) {
1840 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1841 my $ed;
1842 if ($self->ra->can_do_switch) {
1843 $self->assert_index_clean($parent);
1844 print STDERR "Following parent with do_switch\n";
1845 # do_switch works with svn/trunk >= r22312, but that
1846 # is not included with SVN 1.4.3 (the latest version
1847 # at the moment), so we can't rely on it
1848 $self->{last_commit} = $parent;
1849 $ed = SVN::Git::Fetcher->new($self);
1850 $gs->ra->gs_do_switch($r0, $rev, $gs,
1851 $self->full_url, $ed)
1852 or die "SVN connection failed somewhere...\n";
1853 } else {
1854 print STDERR "Following parent with do_update\n";
1855 $ed = SVN::Git::Fetcher->new($self);
1856 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1857 or die "SVN connection failed somewhere...\n";
1859 print STDERR "Successfully followed parent\n";
1860 return $self->make_log_entry($rev, [$parent], $ed);
1862 return undef;
1865 sub do_fetch {
1866 my ($self, $paths, $rev) = @_;
1867 my $ed;
1868 my ($last_rev, @parents);
1869 if (my $lc = $self->last_commit) {
1870 # we can have a branch that was deleted, then re-added
1871 # under the same name but copied from another path, in
1872 # which case we'll have multiple parents (we don't
1873 # want to break the original ref, nor lose copypath info):
1874 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1875 push @{$log_entry->{parents}}, $lc;
1876 return $log_entry;
1878 $ed = SVN::Git::Fetcher->new($self);
1879 $last_rev = $self->{last_rev};
1880 $ed->{c} = $lc;
1881 @parents = ($lc);
1882 } else {
1883 $last_rev = $rev;
1884 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1885 return $log_entry;
1887 $ed = SVN::Git::Fetcher->new($self);
1889 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1890 die "SVN connection failed somewhere...\n";
1892 $self->make_log_entry($rev, \@parents, $ed);
1895 sub get_untracked {
1896 my ($self, $ed) = @_;
1897 my @out;
1898 my $h = $ed->{empty};
1899 foreach (sort keys %$h) {
1900 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1901 push @out, " $act: " . uri_encode($_);
1902 warn "W: $act: $_\n";
1904 foreach my $t (qw/dir_prop file_prop/) {
1905 $h = $ed->{$t} or next;
1906 foreach my $path (sort keys %$h) {
1907 my $ppath = $path eq '' ? '.' : $path;
1908 foreach my $prop (sort keys %{$h->{$path}}) {
1909 next if $SKIP_PROP{$prop};
1910 my $v = $h->{$path}->{$prop};
1911 my $t_ppath_prop = "$t: " .
1912 uri_encode($ppath) . ' ' .
1913 uri_encode($prop);
1914 if (defined $v) {
1915 push @out, " +$t_ppath_prop " .
1916 uri_encode($v);
1917 } else {
1918 push @out, " -$t_ppath_prop";
1923 foreach my $t (qw/absent_file absent_directory/) {
1924 $h = $ed->{$t} or next;
1925 foreach my $parent (sort keys %$h) {
1926 foreach my $path (sort @{$h->{$parent}}) {
1927 push @out, " $t: " .
1928 uri_encode("$parent/$path");
1929 warn "W: $t: $parent/$path ",
1930 "Insufficient permissions?\n";
1934 \@out;
1937 sub parse_svn_date {
1938 my $date = shift || return '+0000 1970-01-01 00:00:00';
1939 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1940 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1941 croak "Unable to parse date: $date\n";
1942 "+0000 $Y-$m-$d $H:$M:$S";
1945 sub check_author {
1946 my ($author) = @_;
1947 if (!defined $author || length $author == 0) {
1948 $author = '(no author)';
1950 if (defined $::_authors && ! defined $::users{$author}) {
1951 die "Author: $author not defined in $::_authors file\n";
1953 $author;
1956 sub make_log_entry {
1957 my ($self, $rev, $parents, $ed) = @_;
1958 my $untracked = $self->get_untracked($ed);
1960 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1961 print $un "r$rev\n" or croak $!;
1962 print $un $_, "\n" foreach @$untracked;
1963 my %log_entry = ( parents => $parents || [], revision => $rev,
1964 log => '');
1966 my $headrev;
1967 my $logged = delete $self->{logged_rev_props};
1968 if (!$logged || $self->{-want_revprops}) {
1969 my $rp = $self->ra->rev_proplist($rev);
1970 foreach (sort keys %$rp) {
1971 my $v = $rp->{$_};
1972 if (/^svn:(author|date|log)$/) {
1973 $log_entry{$1} = $v;
1974 } elsif ($_ eq 'svm:headrev') {
1975 $headrev = $v;
1976 } else {
1977 print $un " rev_prop: ", uri_encode($_), ' ',
1978 uri_encode($v), "\n";
1981 } else {
1982 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1984 close $un or croak $!;
1986 $log_entry{date} = parse_svn_date($log_entry{date});
1987 $log_entry{log} .= "\n";
1988 my $author = $log_entry{author} = check_author($log_entry{author});
1989 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1990 : ($author, undef);
1991 if (defined $headrev && $self->use_svm_props) {
1992 if ($self->rewrite_root) {
1993 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1994 "options set!\n";
1996 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1997 # we don't want "SVM: initializing mirror for junk" ...
1998 return undef if $r == 0;
1999 my $svm = $self->svm;
2000 if ($uuid ne $svm->{uuid}) {
2001 die "UUID mismatch on SVM path:\n",
2002 "expected: $svm->{uuid}\n",
2003 " got: $uuid\n";
2005 my $full_url = $self->full_url;
2006 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2007 die "Failed to replace '$svm->{replace}' with ",
2008 "'$svm->{source}' in $full_url\n";
2009 # throw away username for storing in records
2010 remove_username($full_url);
2011 $log_entry{metadata} = "$full_url\@$r $uuid";
2012 $log_entry{svm_revision} = $r;
2013 $email ||= "$author\@$uuid"
2014 } elsif ($self->use_svnsync_props) {
2015 my $full_url = $self->svnsync->{url};
2016 $full_url .= "/$self->{path}" if length $self->{path};
2017 remove_username($full_url);
2018 my $uuid = $self->svnsync->{uuid};
2019 $log_entry{metadata} = "$full_url\@$rev $uuid";
2020 $email ||= "$author\@$uuid"
2021 } else {
2022 my $url = $self->metadata_url;
2023 remove_username($url);
2024 $log_entry{metadata} = "$url\@$rev " .
2025 $self->ra->get_uuid;
2026 $email ||= "$author\@" . $self->ra->get_uuid;
2028 $log_entry{name} = $name;
2029 $log_entry{email} = $email;
2030 \%log_entry;
2033 sub fetch {
2034 my ($self, $min_rev, $max_rev, @parents) = @_;
2035 my ($last_rev, $last_commit) = $self->last_rev_commit;
2036 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2037 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2040 sub set_tree_cb {
2041 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2042 $self->{inject_parents} = { $rev => $tree };
2043 $self->fetch(undef, undef);
2046 sub set_tree {
2047 my ($self, $tree) = (shift, shift);
2048 my $log_entry = ::get_commit_entry($tree);
2049 unless ($self->{last_rev}) {
2050 fatal("Must have an existing revision to commit\n");
2052 my %ed_opts = ( r => $self->{last_rev},
2053 log => $log_entry->{log},
2054 ra => $self->ra,
2055 tree_a => $self->{last_commit},
2056 tree_b => $tree,
2057 editor_cb => sub {
2058 $self->set_tree_cb($log_entry, $tree, @_) },
2059 svn_path => $self->{path} );
2060 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2061 print "No changes\nr$self->{last_rev} = $tree\n";
2065 sub rebuild {
2066 my ($self) = @_;
2067 my $db_path = $self->db_path;
2068 return if (-e $db_path && ! -z $db_path);
2069 return unless ::verify_ref($self->refname.'^0');
2070 if (-f $self->{db_root}) {
2071 rename $self->{db_root}, $db_path or die
2072 "rename $self->{db_root} => $db_path failed: $!\n";
2073 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2074 symlink $base, $self->{db_root} or die
2075 "symlink $base => $self->{db_root} failed: $!\n";
2076 return;
2078 print "Rebuilding $db_path ...\n";
2079 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2080 my $latest;
2081 my $full_url = $self->full_url;
2082 remove_username($full_url);
2083 my $svn_uuid;
2084 my $c;
2085 while (<$log>) {
2086 if ( m{^commit ($::sha1)$} ) {
2087 $c = $1;
2088 next;
2090 next unless s{^\s*(git-svn-id:)}{$1};
2091 my ($url, $rev, $uuid) = ::extract_metadata($_);
2092 remove_username($url);
2094 # ignore merges (from set-tree)
2095 next if (!defined $rev || !$uuid);
2097 # if we merged or otherwise started elsewhere, this is
2098 # how we break out of it
2099 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2100 ($full_url && $url && ($url ne $full_url))) {
2101 next;
2103 $latest ||= $rev;
2104 $svn_uuid ||= $uuid;
2106 $self->rev_db_set($rev, $c);
2107 print "r$rev = $c\n";
2109 command_close_pipe($log, $ctx);
2110 print "Done rebuilding $db_path\n";
2113 # rev_db:
2114 # Tie::File seems to be prone to offset errors if revisions get sparse,
2115 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2116 # one of my favorite modules is out :< Next up would be one of the DBM
2117 # modules, but I'm not sure which is most portable... So I'll just
2118 # go with something that's plain-text, but still capable of
2119 # being randomly accessed. So here's my ultra-simple fixed-width
2120 # database. All records are 40 characters + "\n", so it's easy to seek
2121 # to a revision: (41 * rev) is the byte offset.
2122 # A record of 40 0s denotes an empty revision.
2123 # And yes, it's still pretty fast (faster than Tie::File).
2124 # These files are disposable unless noMetadata or useSvmProps is set
2126 sub _rev_db_set {
2127 my ($fh, $rev, $commit) = @_;
2128 my $offset = $rev * 41;
2129 # assume that append is the common case:
2130 seek $fh, 0, 2 or croak $!;
2131 my $pos = tell $fh;
2132 if ($pos < $offset) {
2133 for (1 .. (($offset - $pos) / 41)) {
2134 print $fh (('0' x 40),"\n") or croak $!;
2137 seek $fh, $offset, 0 or croak $!;
2138 print $fh $commit,"\n" or croak $!;
2141 sub mkfile {
2142 my ($path) = @_;
2143 unless (-e $path) {
2144 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2145 mkpath([$dir]) unless -d $dir;
2146 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2147 close $fh or die "Couldn't close (create) $path: $!\n";
2151 sub rev_db_set {
2152 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2153 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2154 my $db = $self->db_path($uuid);
2155 my $db_lock = "$db.lock";
2156 my $sig;
2157 if ($update_ref) {
2158 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2159 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2161 mkfile($db);
2163 $LOCKFILES{$db_lock} = 1;
2164 my $sync;
2165 # both of these options make our .rev_db file very, very important
2166 # and we can't afford to lose it because rebuild() won't work
2167 if ($self->use_svm_props || $self->no_metadata) {
2168 $sync = 1;
2169 copy($db, $db_lock) or die "rev_db_set(@_): ",
2170 "Failed to copy: ",
2171 "$db => $db_lock ($!)\n";
2172 } else {
2173 rename $db, $db_lock or die "rev_db_set(@_): ",
2174 "Failed to rename: ",
2175 "$db => $db_lock ($!)\n";
2177 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2178 _rev_db_set($fh, $rev, $commit);
2179 if ($sync) {
2180 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2181 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2183 close $fh or croak $!;
2184 if ($update_ref) {
2185 $_head = $self;
2186 command_noisy('update-ref', '-m', "r$rev",
2187 $self->refname, $commit);
2189 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2190 "$db_lock => $db ($!)\n";
2191 delete $LOCKFILES{$db_lock};
2192 if ($update_ref) {
2193 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2194 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2195 kill $sig, $$ if defined $sig;
2199 sub rev_db_max {
2200 my ($self) = @_;
2201 $self->rebuild;
2202 my $db_path = $self->db_path;
2203 my @stat = stat $db_path or return 0;
2204 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2205 my $max = $stat[7] / 41;
2206 (($max > 0) ? $max - 1 : 0);
2209 sub rev_db_get {
2210 my ($self, $rev, $uuid) = @_;
2211 my $ret;
2212 my $offset = $rev * 41;
2213 my $db_path = $self->db_path($uuid);
2214 return undef unless -e $db_path;
2215 open my $fh, '<', $db_path or croak $!;
2216 if (sysseek($fh, $offset, 0) == $offset) {
2217 my $read = sysread($fh, $ret, 40);
2218 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2220 close $fh or croak $!;
2221 $ret;
2224 sub find_rev_before {
2225 my ($self, $rev, $eq_ok) = @_;
2226 --$rev unless $eq_ok;
2227 while ($rev > 0) {
2228 if (my $c = $self->rev_db_get($rev)) {
2229 return ($rev, $c);
2231 --$rev;
2233 return (undef, undef);
2236 sub _new {
2237 my ($class, $repo_id, $ref_id, $path) = @_;
2238 unless (defined $repo_id && length $repo_id) {
2239 $repo_id = $Git::SVN::default_repo_id;
2241 unless (defined $ref_id && length $ref_id) {
2242 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2244 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2245 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2246 $_[3] = $path = '' unless (defined $path);
2247 mkpath(["$ENV{GIT_DIR}/svn"]);
2248 bless {
2249 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2250 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2251 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2254 sub db_path {
2255 my ($self, $uuid) = @_;
2256 $uuid ||= $self->ra_uuid;
2257 "$self->{db_root}.$uuid";
2260 sub uri_encode {
2261 my ($f) = @_;
2262 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2266 sub remove_username {
2267 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2270 package Git::SVN::Prompt;
2271 use strict;
2272 use warnings;
2273 require SVN::Core;
2274 use vars qw/$_no_auth_cache $_username/;
2276 sub simple {
2277 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2278 $may_save = undef if $_no_auth_cache;
2279 $default_username = $_username if defined $_username;
2280 if (defined $default_username && length $default_username) {
2281 if (defined $realm && length $realm) {
2282 print STDERR "Authentication realm: $realm\n";
2283 STDERR->flush;
2285 $cred->username($default_username);
2286 } else {
2287 username($cred, $realm, $may_save, $pool);
2289 $cred->password(_read_password("Password for '" .
2290 $cred->username . "': ", $realm));
2291 $cred->may_save($may_save);
2292 $SVN::_Core::SVN_NO_ERROR;
2295 sub ssl_server_trust {
2296 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2297 $may_save = undef if $_no_auth_cache;
2298 print STDERR "Error validating server certificate for '$realm':\n";
2299 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2300 print STDERR " - The certificate is not issued by a trusted ",
2301 "authority. Use the\n",
2302 " fingerprint to validate the certificate manually!\n";
2304 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2305 print STDERR " - The certificate hostname does not match.\n";
2307 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2308 print STDERR " - The certificate is not yet valid.\n";
2310 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2311 print STDERR " - The certificate has expired.\n";
2313 if ($failures & $SVN::Auth::SSL::OTHER) {
2314 print STDERR " - The certificate has an unknown error.\n";
2316 printf STDERR
2317 "Certificate information:\n".
2318 " - Hostname: %s\n".
2319 " - Valid: from %s until %s\n".
2320 " - Issuer: %s\n".
2321 " - Fingerprint: %s\n",
2322 map $cert_info->$_, qw(hostname valid_from valid_until
2323 issuer_dname fingerprint);
2324 my $choice;
2325 prompt:
2326 print STDERR $may_save ?
2327 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2328 "(R)eject or accept (t)emporarily? ";
2329 STDERR->flush;
2330 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2331 if ($choice =~ /^t$/i) {
2332 $cred->may_save(undef);
2333 } elsif ($choice =~ /^r$/i) {
2334 return -1;
2335 } elsif ($may_save && $choice =~ /^p$/i) {
2336 $cred->may_save($may_save);
2337 } else {
2338 goto prompt;
2340 $cred->accepted_failures($failures);
2341 $SVN::_Core::SVN_NO_ERROR;
2344 sub ssl_client_cert {
2345 my ($cred, $realm, $may_save, $pool) = @_;
2346 $may_save = undef if $_no_auth_cache;
2347 print STDERR "Client certificate filename: ";
2348 STDERR->flush;
2349 chomp(my $filename = <STDIN>);
2350 $cred->cert_file($filename);
2351 $cred->may_save($may_save);
2352 $SVN::_Core::SVN_NO_ERROR;
2355 sub ssl_client_cert_pw {
2356 my ($cred, $realm, $may_save, $pool) = @_;
2357 $may_save = undef if $_no_auth_cache;
2358 $cred->password(_read_password("Password: ", $realm));
2359 $cred->may_save($may_save);
2360 $SVN::_Core::SVN_NO_ERROR;
2363 sub username {
2364 my ($cred, $realm, $may_save, $pool) = @_;
2365 $may_save = undef if $_no_auth_cache;
2366 if (defined $realm && length $realm) {
2367 print STDERR "Authentication realm: $realm\n";
2369 my $username;
2370 if (defined $_username) {
2371 $username = $_username;
2372 } else {
2373 print STDERR "Username: ";
2374 STDERR->flush;
2375 chomp($username = <STDIN>);
2377 $cred->username($username);
2378 $cred->may_save($may_save);
2379 $SVN::_Core::SVN_NO_ERROR;
2382 sub _read_password {
2383 my ($prompt, $realm) = @_;
2384 print STDERR $prompt;
2385 STDERR->flush;
2386 require Term::ReadKey;
2387 Term::ReadKey::ReadMode('noecho');
2388 my $password = '';
2389 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2390 last if $key =~ /[\012\015]/; # \n\r
2391 $password .= $key;
2393 Term::ReadKey::ReadMode('restore');
2394 print STDERR "\n";
2395 STDERR->flush;
2396 $password;
2399 package main;
2402 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2403 $SVN::Node::dir.$SVN::Node::unknown.
2404 $SVN::Node::none.$SVN::Node::file.
2405 $SVN::Node::dir.$SVN::Node::unknown.
2406 $SVN::Auth::SSL::CNMISMATCH.
2407 $SVN::Auth::SSL::NOTYETVALID.
2408 $SVN::Auth::SSL::EXPIRED.
2409 $SVN::Auth::SSL::UNKNOWNCA.
2410 $SVN::Auth::SSL::OTHER;
2413 package SVN::Git::Fetcher;
2414 use vars qw/@ISA/;
2415 use strict;
2416 use warnings;
2417 use Carp qw/croak/;
2418 use IO::File qw//;
2419 use Digest::MD5;
2421 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2422 sub new {
2423 my ($class, $git_svn) = @_;
2424 my $self = SVN::Delta::Editor->new;
2425 bless $self, $class;
2426 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2427 $self->{empty} = {};
2428 $self->{dir_prop} = {};
2429 $self->{file_prop} = {};
2430 $self->{absent_dir} = {};
2431 $self->{absent_file} = {};
2432 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2433 $self;
2436 sub set_path_strip {
2437 my ($self, $path) = @_;
2438 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2441 sub open_root {
2442 { path => '' };
2445 sub open_directory {
2446 my ($self, $path, $pb, $rev) = @_;
2447 { path => $path };
2450 sub git_path {
2451 my ($self, $path) = @_;
2452 if ($self->{path_strip}) {
2453 $path =~ s!$self->{path_strip}!! or
2454 die "Failed to strip path '$path' ($self->{path_strip})\n";
2456 $path;
2459 sub delete_entry {
2460 my ($self, $path, $rev, $pb) = @_;
2462 my $gpath = $self->git_path($path);
2463 return undef if ($gpath eq '');
2465 # remove entire directories.
2466 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2467 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2468 -r --name-only -z/,
2469 $self->{c}, '--', $gpath);
2470 local $/ = "\0";
2471 while (<$ls>) {
2472 chomp;
2473 $self->{gii}->remove($_);
2474 print "\tD\t$_\n" unless $::_q;
2476 print "\tD\t$gpath/\n" unless $::_q;
2477 command_close_pipe($ls, $ctx);
2478 $self->{empty}->{$path} = 0
2479 } else {
2480 $self->{gii}->remove($gpath);
2481 print "\tD\t$gpath\n" unless $::_q;
2483 undef;
2486 sub open_file {
2487 my ($self, $path, $pb, $rev) = @_;
2488 my $gpath = $self->git_path($path);
2489 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2490 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2491 unless (defined $mode && defined $blob) {
2492 die "$path was not found in commit $self->{c} (r$rev)\n";
2494 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2495 pool => SVN::Pool->new, action => 'M' };
2498 sub add_file {
2499 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2500 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2501 delete $self->{empty}->{$dir};
2502 { path => $path, mode_a => 100644, mode_b => 100644,
2503 pool => SVN::Pool->new, action => 'A' };
2506 sub add_directory {
2507 my ($self, $path, $cp_path, $cp_rev) = @_;
2508 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2509 delete $self->{empty}->{$dir};
2510 $self->{empty}->{$path} = 1;
2511 { path => $path };
2514 sub change_dir_prop {
2515 my ($self, $db, $prop, $value) = @_;
2516 $self->{dir_prop}->{$db->{path}} ||= {};
2517 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2518 undef;
2521 sub absent_directory {
2522 my ($self, $path, $pb) = @_;
2523 $self->{absent_dir}->{$pb->{path}} ||= [];
2524 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2525 undef;
2528 sub absent_file {
2529 my ($self, $path, $pb) = @_;
2530 $self->{absent_file}->{$pb->{path}} ||= [];
2531 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2532 undef;
2535 sub change_file_prop {
2536 my ($self, $fb, $prop, $value) = @_;
2537 if ($prop eq 'svn:executable') {
2538 if ($fb->{mode_b} != 120000) {
2539 $fb->{mode_b} = defined $value ? 100755 : 100644;
2541 } elsif ($prop eq 'svn:special') {
2542 $fb->{mode_b} = defined $value ? 120000 : 100644;
2543 } else {
2544 $self->{file_prop}->{$fb->{path}} ||= {};
2545 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2547 undef;
2550 sub apply_textdelta {
2551 my ($self, $fb, $exp) = @_;
2552 my $fh = IO::File->new_tmpfile;
2553 $fh->autoflush(1);
2554 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2555 # (but $base does not,) so dup() it for reading in close_file
2556 open my $dup, '<&', $fh or croak $!;
2557 my $base = IO::File->new_tmpfile;
2558 $base->autoflush(1);
2559 if ($fb->{blob}) {
2560 defined (my $pid = fork) or croak $!;
2561 if (!$pid) {
2562 open STDOUT, '>&', $base or croak $!;
2563 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2564 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2566 waitpid $pid, 0;
2567 croak $? if $?;
2569 if (defined $exp) {
2570 seek $base, 0, 0 or croak $!;
2571 my $md5 = Digest::MD5->new;
2572 $md5->addfile($base);
2573 my $got = $md5->hexdigest;
2574 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2575 "expected: $exp\n",
2576 " got: $got\n" if ($got ne $exp);
2579 seek $base, 0, 0 or croak $!;
2580 $fb->{fh} = $dup;
2581 $fb->{base} = $base;
2582 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2585 sub close_file {
2586 my ($self, $fb, $exp) = @_;
2587 my $hash;
2588 my $path = $self->git_path($fb->{path});
2589 if (my $fh = $fb->{fh}) {
2590 if (defined $exp) {
2591 seek($fh, 0, 0) or croak $!;
2592 my $md5 = Digest::MD5->new;
2593 $md5->addfile($fh);
2594 my $got = $md5->hexdigest;
2595 if ($got ne $exp) {
2596 die "Checksum mismatch: $path\n",
2597 "expected: $exp\n got: $got\n";
2600 sysseek($fh, 0, 0) or croak $!;
2601 if ($fb->{mode_b} == 120000) {
2602 sysread($fh, my $buf, 5) == 5 or croak $!;
2603 $buf eq 'link ' or die "$path has mode 120000",
2604 "but is not a link\n";
2606 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2607 if (!$pid) {
2608 open STDIN, '<&', $fh or croak $!;
2609 exec qw/git-hash-object -w --stdin/ or croak $!;
2611 chomp($hash = do { local $/; <$out> });
2612 close $out or croak $!;
2613 close $fh or croak $!;
2614 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2615 close $fb->{base} or croak $!;
2616 } else {
2617 $hash = $fb->{blob} or die "no blob information\n";
2619 $fb->{pool}->clear;
2620 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2621 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2622 undef;
2625 sub abort_edit {
2626 my $self = shift;
2627 $self->{nr} = $self->{gii}->{nr};
2628 delete $self->{gii};
2629 $self->SUPER::abort_edit(@_);
2632 sub close_edit {
2633 my $self = shift;
2634 $self->{git_commit_ok} = 1;
2635 $self->{nr} = $self->{gii}->{nr};
2636 delete $self->{gii};
2637 $self->SUPER::close_edit(@_);
2640 package SVN::Git::Editor;
2641 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2642 use strict;
2643 use warnings;
2644 use Carp qw/croak/;
2645 use IO::File;
2646 use Digest::MD5;
2648 sub new {
2649 my ($class, $opts) = @_;
2650 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2651 die "$_ required!\n" unless (defined $opts->{$_});
2654 my $pool = SVN::Pool->new;
2655 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2656 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2657 $opts->{r}, $mods);
2659 # $opts->{ra} functions should not be used after this:
2660 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2661 $opts->{editor_cb}, $pool);
2662 my $self = SVN::Delta::Editor->new(@ce, $pool);
2663 bless $self, $class;
2664 foreach (qw/svn_path r tree_a tree_b/) {
2665 $self->{$_} = $opts->{$_};
2667 $self->{url} = $opts->{ra}->{url};
2668 $self->{mods} = $mods;
2669 $self->{types} = $types;
2670 $self->{pool} = $pool;
2671 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2672 $self->{rm} = { };
2673 $self->{path_prefix} = length $self->{svn_path} ?
2674 "$self->{svn_path}/" : '';
2675 return $self;
2678 sub generate_diff {
2679 my ($tree_a, $tree_b) = @_;
2680 my @diff_tree = qw(diff-tree -z -r);
2681 if ($_cp_similarity) {
2682 push @diff_tree, "-C$_cp_similarity";
2683 } else {
2684 push @diff_tree, '-C';
2686 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2687 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2688 push @diff_tree, $tree_a, $tree_b;
2689 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2690 local $/ = "\0";
2691 my $state = 'meta';
2692 my @mods;
2693 while (<$diff_fh>) {
2694 chomp $_; # this gets rid of the trailing "\0"
2695 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2696 $::sha1\s($::sha1)\s
2697 ([MTCRAD])\d*$/xo) {
2698 push @mods, { mode_a => $1, mode_b => $2,
2699 sha1_b => $3, chg => $4 };
2700 if ($4 =~ /^(?:C|R)$/) {
2701 $state = 'file_a';
2702 } else {
2703 $state = 'file_b';
2705 } elsif ($state eq 'file_a') {
2706 my $x = $mods[$#mods] or croak "Empty array\n";
2707 if ($x->{chg} !~ /^(?:C|R)$/) {
2708 croak "Error parsing $_, $x->{chg}\n";
2710 $x->{file_a} = $_;
2711 $state = 'file_b';
2712 } elsif ($state eq 'file_b') {
2713 my $x = $mods[$#mods] or croak "Empty array\n";
2714 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2715 croak "Error parsing $_, $x->{chg}\n";
2717 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2718 croak "Error parsing $_, $x->{chg}\n";
2720 $x->{file_b} = $_;
2721 $state = 'meta';
2722 } else {
2723 croak "Error parsing $_\n";
2726 command_close_pipe($diff_fh, $ctx);
2727 \@mods;
2730 sub check_diff_paths {
2731 my ($ra, $pfx, $rev, $mods) = @_;
2732 my %types;
2733 $pfx .= '/' if length $pfx;
2735 sub type_diff_paths {
2736 my ($ra, $types, $path, $rev) = @_;
2737 my @p = split m#/+#, $path;
2738 my $c = shift @p;
2739 unless (defined $types->{$c}) {
2740 $types->{$c} = $ra->check_path($c, $rev);
2742 while (@p) {
2743 $c .= '/' . shift @p;
2744 next if defined $types->{$c};
2745 $types->{$c} = $ra->check_path($c, $rev);
2749 foreach my $m (@$mods) {
2750 foreach my $f (qw/file_a file_b/) {
2751 next unless defined $m->{$f};
2752 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2753 if (length $pfx.$dir && ! defined $types{$dir}) {
2754 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2758 \%types;
2761 sub split_path {
2762 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2765 sub repo_path {
2766 my ($self, $path) = @_;
2767 $self->{path_prefix}.(defined $path ? $path : '');
2770 sub url_path {
2771 my ($self, $path) = @_;
2772 if ($self->{url} =~ m#^https?://#) {
2773 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2775 $self->{url} . '/' . $self->repo_path($path);
2778 sub rmdirs {
2779 my ($self) = @_;
2780 my $rm = $self->{rm};
2781 delete $rm->{''}; # we never delete the url we're tracking
2782 return unless %$rm;
2784 foreach (keys %$rm) {
2785 my @d = split m#/#, $_;
2786 my $c = shift @d;
2787 $rm->{$c} = 1;
2788 while (@d) {
2789 $c .= '/' . shift @d;
2790 $rm->{$c} = 1;
2793 delete $rm->{$self->{svn_path}};
2794 delete $rm->{''}; # we never delete the url we're tracking
2795 return unless %$rm;
2797 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2798 $self->{tree_b});
2799 local $/ = "\0";
2800 while (<$fh>) {
2801 chomp;
2802 my @dn = split m#/#, $_;
2803 while (pop @dn) {
2804 delete $rm->{join '/', @dn};
2806 unless (%$rm) {
2807 close $fh;
2808 return;
2811 command_close_pipe($fh, $ctx);
2813 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2814 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2815 $self->close_directory($bat->{$d}, $p);
2816 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2817 print "\tD+\t$d/\n" unless $::_q;
2818 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2819 delete $bat->{$d};
2823 sub open_or_add_dir {
2824 my ($self, $full_path, $baton) = @_;
2825 my $t = $self->{types}->{$full_path};
2826 if (!defined $t) {
2827 die "$full_path not known in r$self->{r} or we have a bug!\n";
2829 if ($t == $SVN::Node::none) {
2830 return $self->add_directory($full_path, $baton,
2831 undef, -1, $self->{pool});
2832 } elsif ($t == $SVN::Node::dir) {
2833 return $self->open_directory($full_path, $baton,
2834 $self->{r}, $self->{pool});
2836 print STDERR "$full_path already exists in repository at ",
2837 "r$self->{r} and it is not a directory (",
2838 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2839 exit 1;
2842 sub ensure_path {
2843 my ($self, $path) = @_;
2844 my $bat = $self->{bat};
2845 my $repo_path = $self->repo_path($path);
2846 return $bat->{''} unless (length $repo_path);
2847 my @p = split m#/+#, $repo_path;
2848 my $c = shift @p;
2849 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2850 while (@p) {
2851 my $c0 = $c;
2852 $c .= '/' . shift @p;
2853 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2855 return $bat->{$c};
2858 sub A {
2859 my ($self, $m) = @_;
2860 my ($dir, $file) = split_path($m->{file_b});
2861 my $pbat = $self->ensure_path($dir);
2862 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2863 undef, -1);
2864 print "\tA\t$m->{file_b}\n" unless $::_q;
2865 $self->chg_file($fbat, $m);
2866 $self->close_file($fbat,undef,$self->{pool});
2869 sub C {
2870 my ($self, $m) = @_;
2871 my ($dir, $file) = split_path($m->{file_b});
2872 my $pbat = $self->ensure_path($dir);
2873 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2874 $self->url_path($m->{file_a}), $self->{r});
2875 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2876 $self->chg_file($fbat, $m);
2877 $self->close_file($fbat,undef,$self->{pool});
2880 sub delete_entry {
2881 my ($self, $path, $pbat) = @_;
2882 my $rpath = $self->repo_path($path);
2883 my ($dir, $file) = split_path($rpath);
2884 $self->{rm}->{$dir} = 1;
2885 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2888 sub R {
2889 my ($self, $m) = @_;
2890 my ($dir, $file) = split_path($m->{file_b});
2891 my $pbat = $self->ensure_path($dir);
2892 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2893 $self->url_path($m->{file_a}), $self->{r});
2894 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2895 $self->chg_file($fbat, $m);
2896 $self->close_file($fbat,undef,$self->{pool});
2898 ($dir, $file) = split_path($m->{file_a});
2899 $pbat = $self->ensure_path($dir);
2900 $self->delete_entry($m->{file_a}, $pbat);
2903 sub M {
2904 my ($self, $m) = @_;
2905 my ($dir, $file) = split_path($m->{file_b});
2906 my $pbat = $self->ensure_path($dir);
2907 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2908 $pbat,$self->{r},$self->{pool});
2909 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2910 $self->chg_file($fbat, $m);
2911 $self->close_file($fbat,undef,$self->{pool});
2914 sub T { shift->M(@_) }
2916 sub change_file_prop {
2917 my ($self, $fbat, $pname, $pval) = @_;
2918 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2921 sub chg_file {
2922 my ($self, $fbat, $m) = @_;
2923 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2924 $self->change_file_prop($fbat,'svn:executable','*');
2925 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2926 $self->change_file_prop($fbat,'svn:executable',undef);
2928 my $fh = IO::File->new_tmpfile or croak $!;
2929 if ($m->{mode_b} =~ /^120/) {
2930 print $fh 'link ' or croak $!;
2931 $self->change_file_prop($fbat,'svn:special','*');
2932 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2933 $self->change_file_prop($fbat,'svn:special',undef);
2935 defined(my $pid = fork) or croak $!;
2936 if (!$pid) {
2937 open STDOUT, '>&', $fh or croak $!;
2938 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2940 waitpid $pid, 0;
2941 croak $? if $?;
2942 $fh->flush == 0 or croak $!;
2943 seek $fh, 0, 0 or croak $!;
2945 my $md5 = Digest::MD5->new;
2946 $md5->addfile($fh) or croak $!;
2947 seek $fh, 0, 0 or croak $!;
2949 my $exp = $md5->hexdigest;
2950 my $pool = SVN::Pool->new;
2951 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2952 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2953 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2954 $pool->clear;
2956 close $fh or croak $!;
2959 sub D {
2960 my ($self, $m) = @_;
2961 my ($dir, $file) = split_path($m->{file_b});
2962 my $pbat = $self->ensure_path($dir);
2963 print "\tD\t$m->{file_b}\n" unless $::_q;
2964 $self->delete_entry($m->{file_b}, $pbat);
2967 sub close_edit {
2968 my ($self) = @_;
2969 my ($p,$bat) = ($self->{pool}, $self->{bat});
2970 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2971 next if $_ eq '';
2972 $self->close_directory($bat->{$_}, $p);
2974 $self->close_directory($bat->{''}, $p);
2975 $self->SUPER::close_edit($p);
2976 $p->clear;
2979 sub abort_edit {
2980 my ($self) = @_;
2981 $self->SUPER::abort_edit($self->{pool});
2984 sub DESTROY {
2985 my $self = shift;
2986 $self->SUPER::DESTROY(@_);
2987 $self->{pool}->clear;
2990 # this drives the editor
2991 sub apply_diff {
2992 my ($self) = @_;
2993 my $mods = $self->{mods};
2994 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2995 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2996 my $f = $m->{chg};
2997 if (defined $o{$f}) {
2998 $self->$f($m);
2999 } else {
3000 fatal("Invalid change type: $f\n");
3003 $self->rmdirs if $_rmdir;
3004 if (@$mods == 0) {
3005 $self->abort_edit;
3006 } else {
3007 $self->close_edit;
3009 return scalar @$mods;
3012 package Git::SVN::Ra;
3013 use vars qw/@ISA $config_dir $_log_window_size/;
3014 use strict;
3015 use warnings;
3016 my ($can_do_switch, %ignored_err, $RA);
3018 BEGIN {
3019 # enforce temporary pool usage for some simple functions
3020 no strict 'refs';
3021 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3022 my $SUPER = "SUPER::$f";
3023 *$f = sub {
3024 my $self = shift;
3025 my $pool = SVN::Pool->new;
3026 my @ret = $self->$SUPER(@_,$pool);
3027 $pool->clear;
3028 wantarray ? @ret : $ret[0];
3033 sub new {
3034 my ($class, $url) = @_;
3035 $url =~ s!/+$!!;
3036 return $RA if ($RA && $RA->{url} eq $url);
3038 SVN::_Core::svn_config_ensure($config_dir, undef);
3039 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3040 SVN::Client::get_simple_provider(),
3041 SVN::Client::get_ssl_server_trust_file_provider(),
3042 SVN::Client::get_simple_prompt_provider(
3043 \&Git::SVN::Prompt::simple, 2),
3044 SVN::Client::get_ssl_client_cert_file_provider(),
3045 SVN::Client::get_ssl_client_cert_prompt_provider(
3046 \&Git::SVN::Prompt::ssl_client_cert, 2),
3047 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3048 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3049 SVN::Client::get_username_provider(),
3050 SVN::Client::get_ssl_server_trust_prompt_provider(
3051 \&Git::SVN::Prompt::ssl_server_trust),
3052 SVN::Client::get_username_prompt_provider(
3053 \&Git::SVN::Prompt::username, 2),
3055 my $config = SVN::Core::config_get_config($config_dir);
3056 $RA = undef;
3057 my $self = SVN::Ra->new(url => $url, auth => $baton,
3058 config => $config,
3059 pool => SVN::Pool->new,
3060 auth_provider_callbacks => $callbacks);
3061 $self->{svn_path} = $url;
3062 $self->{repos_root} = $self->get_repos_root;
3063 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3064 $self->{cache} = { check_path => { r => 0, data => {} },
3065 get_dir => { r => 0, data => {} } };
3066 $RA = bless $self, $class;
3069 sub check_path {
3070 my ($self, $path, $r) = @_;
3071 my $cache = $self->{cache}->{check_path};
3072 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3073 return $cache->{data}->{$path};
3075 my $pool = SVN::Pool->new;
3076 my $t = $self->SUPER::check_path($path, $r, $pool);
3077 $pool->clear;
3078 if ($r != $cache->{r}) {
3079 %{$cache->{data}} = ();
3080 $cache->{r} = $r;
3082 $cache->{data}->{$path} = $t;
3085 sub get_dir {
3086 my ($self, $dir, $r) = @_;
3087 my $cache = $self->{cache}->{get_dir};
3088 if ($r == $cache->{r}) {
3089 if (my $x = $cache->{data}->{$dir}) {
3090 return wantarray ? @$x : $x->[0];
3093 my $pool = SVN::Pool->new;
3094 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3095 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3096 $pool->clear;
3097 if ($r != $cache->{r}) {
3098 %{$cache->{data}} = ();
3099 $cache->{r} = $r;
3101 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3102 wantarray ? (\%dirents, $r, $props) : \%dirents;
3105 sub DESTROY {
3106 # do not call the real DESTROY since we store ourselves in $RA
3109 sub get_log {
3110 my ($self, @args) = @_;
3111 my $pool = SVN::Pool->new;
3112 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3113 my $ret = $self->SUPER::get_log(@args, $pool);
3114 $pool->clear;
3115 $ret;
3118 sub get_commit_editor {
3119 my ($self, $log, $cb, $pool) = @_;
3120 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3121 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3124 sub gs_do_update {
3125 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3126 my $new = ($rev_a == $rev_b);
3127 my $path = $gs->{path};
3129 if ($new && -e $gs->{index}) {
3130 unlink $gs->{index} or die
3131 "Couldn't unlink index: $gs->{index}: $!\n";
3133 my $pool = SVN::Pool->new;
3134 $editor->set_path_strip($path);
3135 my (@pc) = split m#/#, $path;
3136 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3137 1, $editor, $pool);
3138 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3140 # Since we can't rely on svn_ra_reparent being available, we'll
3141 # just have to do some magic with set_path to make it so
3142 # we only want a partial path.
3143 my $sp = '';
3144 my $final = join('/', @pc);
3145 while (@pc) {
3146 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3147 $sp .= '/' if length $sp;
3148 $sp .= shift @pc;
3150 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3152 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3154 $reporter->finish_report($pool);
3155 $pool->clear;
3156 $editor->{git_commit_ok};
3159 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3160 # svn_ra_reparent didn't work before 1.4)
3161 sub gs_do_switch {
3162 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3163 my $path = $gs->{path};
3164 my $pool = SVN::Pool->new;
3166 my $full_url = $self->{url};
3167 my $old_url = $full_url;
3168 $full_url .= "/$path" if length $path;
3169 my ($ra, $reparented);
3170 if ($old_url ne $full_url) {
3171 if ($old_url !~ m#^svn(\+ssh)?://#) {
3172 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3173 $pool);
3174 $self->{url} = $full_url;
3175 $reparented = 1;
3176 } else {
3177 $ra = Git::SVN::Ra->new($full_url);
3180 $ra ||= $self;
3181 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3182 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3183 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3184 $reporter->finish_report($pool);
3186 if ($reparented) {
3187 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3188 $self->{url} = $old_url;
3191 $pool->clear;
3192 $editor->{git_commit_ok};
3195 sub longest_common_path {
3196 my ($gsv, $globs) = @_;
3197 my %common;
3198 my $common_max = scalar @$gsv;
3200 foreach my $gs (@$gsv) {
3201 my @tmp = split m#/#, $gs->{path};
3202 my $p = '';
3203 foreach (@tmp) {
3204 $p .= length($p) ? "/$_" : $_;
3205 $common{$p} ||= 0;
3206 $common{$p}++;
3209 $globs ||= [];
3210 $common_max += scalar @$globs;
3211 foreach my $glob (@$globs) {
3212 my @tmp = split m#/#, $glob->{path}->{left};
3213 my $p = '';
3214 foreach (@tmp) {
3215 $p .= length($p) ? "/$_" : $_;
3216 $common{$p} ||= 0;
3217 $common{$p}++;
3221 my $longest_path = '';
3222 foreach (sort {length $b <=> length $a} keys %common) {
3223 if ($common{$_} == $common_max) {
3224 $longest_path = $_;
3225 last;
3228 $longest_path;
3231 sub gs_fetch_loop_common {
3232 my ($self, $base, $head, $gsv, $globs) = @_;
3233 return if ($base > $head);
3234 my $inc = $_log_window_size;
3235 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3236 my $longest_path = longest_common_path($gsv, $globs);
3237 while (1) {
3238 my %revs;
3239 my $err;
3240 my $err_handler = $SVN::Error::handler;
3241 $SVN::Error::handler = sub {
3242 ($err) = @_;
3243 skip_unknown_revs($err);
3245 sub _cb {
3246 my ($paths, $r, $author, $date, $log) = @_;
3247 [ dup_changed_paths($paths),
3248 { author => $author, date => $date, log => $log } ];
3250 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3251 sub { $revs{$_[1]} = _cb(@_) });
3252 if ($err && $max >= $head) {
3253 print STDERR "Path '$longest_path' ",
3254 "was probably deleted:\n",
3255 $err->expanded_message,
3256 "\nWill attempt to follow ",
3257 "revisions r$min .. r$max ",
3258 "committed before the deletion\n";
3259 my $hi = $max;
3260 while (--$hi >= $min) {
3261 my $ok;
3262 $self->get_log([$longest_path], $min, $hi,
3263 0, 1, 1, sub {
3264 $ok ||= $_[1];
3265 $revs{$_[1]} = _cb(@_) });
3266 if ($ok) {
3267 print STDERR "r$min .. r$ok OK\n";
3268 last;
3272 $SVN::Error::handler = $err_handler;
3274 my %exists = map { $_->{path} => $_ } @$gsv;
3275 foreach my $r (sort {$a <=> $b} keys %revs) {
3276 my ($paths, $logged) = @{$revs{$r}};
3278 foreach my $gs ($self->match_globs(\%exists, $paths,
3279 $globs, $r)) {
3280 if ($gs->rev_db_max >= $r) {
3281 next;
3283 next unless $gs->match_paths($paths, $r);
3284 $gs->{logged_rev_props} = $logged;
3285 if (my $last_commit = $gs->last_commit) {
3286 $gs->assert_index_clean($last_commit);
3288 my $log_entry = $gs->do_fetch($paths, $r);
3289 if ($log_entry) {
3290 $gs->do_git_commit($log_entry);
3293 foreach my $g (@$globs) {
3294 my $k = "svn-remote.$g->{remote}." .
3295 "$g->{t}-maxRev";
3296 Git::SVN::tmp_config($k, $r);
3299 # pre-fill the .rev_db since it'll eventually get filled in
3300 # with '0' x40 if something new gets committed
3301 foreach my $gs (@$gsv) {
3302 next if defined $gs->rev_db_get($max);
3303 $gs->rev_db_set($max, 0 x40);
3305 foreach my $g (@$globs) {
3306 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3307 Git::SVN::tmp_config($k, $max);
3309 last if $max >= $head;
3310 $min = $max + 1;
3311 $max += $inc;
3312 $max = $head if ($max > $head);
3316 sub match_globs {
3317 my ($self, $exists, $paths, $globs, $r) = @_;
3319 sub get_dir_check {
3320 my ($self, $exists, $g, $r) = @_;
3321 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3322 return unless scalar @x == 3;
3323 my $dirents = $x[0];
3324 foreach my $de (keys %$dirents) {
3325 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3326 my $p = $g->{path}->full_path($de);
3327 next if $exists->{$p};
3328 next if (length $g->{path}->{right} &&
3329 ($self->check_path($p, $r) !=
3330 $SVN::Node::dir));
3331 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3332 $g->{ref}->full_path($de), 1);
3335 foreach my $g (@$globs) {
3336 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3337 if ($path->{action} =~ /^[AR]$/) {
3338 get_dir_check($self, $exists, $g, $r);
3341 foreach (keys %$paths) {
3342 if (/$g->{path}->{left_regex}/ &&
3343 !/$g->{path}->{regex}/) {
3344 next if $paths->{$_}->{action} !~ /^[AR]$/;
3345 get_dir_check($self, $exists, $g, $r);
3347 next unless /$g->{path}->{regex}/;
3348 my $p = $1;
3349 my $pathname = $g->{path}->full_path($p);
3350 next if $exists->{$pathname};
3351 next if ($self->check_path($pathname, $r) !=
3352 $SVN::Node::dir);
3353 $exists->{$pathname} = Git::SVN->init(
3354 $self->{url}, $pathname, undef,
3355 $g->{ref}->full_path($p), 1);
3357 my $c = '';
3358 foreach (split m#/#, $g->{path}->{left}) {
3359 $c .= "/$_";
3360 next unless ($paths->{$c} &&
3361 ($paths->{$c}->{action} =~ /^[AR]$/));
3362 get_dir_check($self, $exists, $g, $r);
3365 values %$exists;
3368 sub minimize_url {
3369 my ($self) = @_;
3370 return $self->{url} if ($self->{url} eq $self->{repos_root});
3371 my $url = $self->{repos_root};
3372 my @components = split(m!/!, $self->{svn_path});
3373 my $c = '';
3374 do {
3375 $url .= "/$c" if length $c;
3376 eval { (ref $self)->new($url)->get_latest_revnum };
3377 } while ($@ && ($c = shift @components));
3378 $url;
3381 sub can_do_switch {
3382 my $self = shift;
3383 unless (defined $can_do_switch) {
3384 my $pool = SVN::Pool->new;
3385 my $rep = eval {
3386 $self->do_switch(1, '', 0, $self->{url},
3387 SVN::Delta::Editor->new, $pool);
3389 if ($@) {
3390 $can_do_switch = 0;
3391 } else {
3392 $rep->abort_report($pool);
3393 $can_do_switch = 1;
3395 $pool->clear;
3397 $can_do_switch;
3400 sub skip_unknown_revs {
3401 my ($err) = @_;
3402 my $errno = $err->apr_err();
3403 # Maybe the branch we're tracking didn't
3404 # exist when the repo started, so it's
3405 # not an error if it doesn't, just continue
3407 # Wonderfully consistent library, eh?
3408 # 160013 - svn:// and file://
3409 # 175002 - http(s)://
3410 # 175007 - http(s):// (this repo required authorization, too...)
3411 # More codes may be discovered later...
3412 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3413 my $err_key = $err->expanded_message;
3414 # revision numbers change every time, filter them out
3415 $err_key =~ s/\d+/\0/g;
3416 $err_key = "$errno\0$err_key";
3417 unless ($ignored_err{$err_key}) {
3418 warn "W: Ignoring error from SVN, path probably ",
3419 "does not exist: ($errno): ",
3420 $err->expanded_message,"\n";
3421 $ignored_err{$err_key} = 1;
3423 return;
3425 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3428 # svn_log_changed_path_t objects passed to get_log are likely to be
3429 # overwritten even if only the refs are copied to an external variable,
3430 # so we should dup the structures in their entirety. Using an externally
3431 # passed pool (instead of our temporary and quickly cleared pool in
3432 # Git::SVN::Ra) does not help matters at all...
3433 sub dup_changed_paths {
3434 my ($paths) = @_;
3435 return undef unless $paths;
3436 my %ret;
3437 foreach my $p (keys %$paths) {
3438 my $i = $paths->{$p};
3439 my %s = map { $_ => $i->$_ }
3440 qw/copyfrom_path copyfrom_rev action/;
3441 $ret{$p} = \%s;
3443 \%ret;
3446 package Git::SVN::Log;
3447 use strict;
3448 use warnings;
3449 use POSIX qw/strftime/;
3450 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3451 %rusers $show_commit $incremental/;
3452 my $l_fmt;
3454 sub cmt_showable {
3455 my ($c) = @_;
3456 return 1 if defined $c->{r};
3458 # big commit message got truncated by the 16k pretty buffer in rev-list
3459 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3460 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3461 @{$c->{l}} = ();
3462 my @log = command(qw/cat-file commit/, $c->{c});
3464 # shift off the headers
3465 shift @log while ($log[0] ne '');
3466 shift @log;
3468 # TODO: make $c->{l} not have a trailing newline in the future
3469 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3471 (undef, $c->{r}, undef) = ::extract_metadata(
3472 (grep(/^git-svn-id: /, @log))[-1]);
3474 return defined $c->{r};
3477 sub log_use_color {
3478 return 1 if $color;
3479 my ($dc, $dcvar);
3480 $dcvar = 'color.diff';
3481 $dc = `git-config --get $dcvar`;
3482 if ($dc eq '') {
3483 # nothing at all; fallback to "diff.color"
3484 $dcvar = 'diff.color';
3485 $dc = `git-config --get $dcvar`;
3487 chomp($dc);
3488 if ($dc eq 'auto') {
3489 my $pc;
3490 $pc = `git-config --get color.pager`;
3491 if ($pc eq '') {
3492 # does not have it -- fallback to pager.color
3493 $pc = `git-config --bool --get pager.color`;
3495 else {
3496 $pc = `git-config --bool --get color.pager`;
3497 if ($?) {
3498 $pc = 'false';
3501 chomp($pc);
3502 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3503 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3505 return 0;
3507 return 0 if $dc eq 'never';
3508 return 1 if $dc eq 'always';
3509 chomp($dc = `git-config --bool --get $dcvar`);
3510 return ($dc eq 'true');
3513 sub git_svn_log_cmd {
3514 my ($r_min, $r_max, @args) = @_;
3515 my $head = 'HEAD';
3516 my (@files, @log_opts);
3517 foreach my $x (@args) {
3518 if ($x eq '--' || @files) {
3519 push @files, $x;
3520 } else {
3521 if (::verify_ref("$x^0")) {
3522 $head = $x;
3523 } else {
3524 push @log_opts, $x;
3529 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3530 $gs ||= Git::SVN->_new;
3531 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3532 $gs->refname);
3533 push @cmd, '-r' unless $non_recursive;
3534 push @cmd, qw/--raw --name-status/ if $verbose;
3535 push @cmd, '--color' if log_use_color();
3536 push @cmd, @log_opts;
3537 if (defined $r_max && $r_max == $r_min) {
3538 push @cmd, '--max-count=1';
3539 if (my $c = $gs->rev_db_get($r_max)) {
3540 push @cmd, $c;
3542 } elsif (defined $r_max) {
3543 my ($c_min, $c_max);
3544 $c_max = $gs->rev_db_get($r_max);
3545 $c_min = $gs->rev_db_get($r_min);
3546 if (defined $c_min && defined $c_max) {
3547 if ($r_max > $r_max) {
3548 push @cmd, "$c_min..$c_max";
3549 } else {
3550 push @cmd, "$c_max..$c_min";
3552 } elsif ($r_max > $r_min) {
3553 push @cmd, $c_max;
3554 } else {
3555 push @cmd, $c_min;
3558 return (@cmd, @files);
3561 # adapted from pager.c
3562 sub config_pager {
3563 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3564 if (!defined $pager) {
3565 $pager = 'less';
3566 } elsif (length $pager == 0 || $pager eq 'cat') {
3567 $pager = undef;
3571 sub run_pager {
3572 return unless -t *STDOUT;
3573 pipe my $rfd, my $wfd or return;
3574 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3575 if (!$pid) {
3576 open STDOUT, '>&', $wfd or
3577 ::fatal "Can't redirect to stdout: $!\n";
3578 return;
3580 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3581 $ENV{LESS} ||= 'FRSX';
3582 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3585 sub tz_to_s_offset {
3586 my ($tz) = @_;
3587 $tz =~ s/(\d\d)$//;
3588 return ($1 * 60) + ($tz * 3600);
3591 sub get_author_info {
3592 my ($dest, $author, $t, $tz) = @_;
3593 $author =~ s/(?:^\s*|\s*$)//g;
3594 $dest->{a_raw} = $author;
3595 my $au;
3596 if ($::_authors) {
3597 $au = $rusers{$author} || undef;
3599 if (!$au) {
3600 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3602 $dest->{t} = $t;
3603 $dest->{tz} = $tz;
3604 $dest->{a} = $au;
3605 # Date::Parse isn't in the standard Perl distro :(
3606 if ($tz =~ s/^\+//) {
3607 $t += tz_to_s_offset($tz);
3608 } elsif ($tz =~ s/^\-//) {
3609 $t -= tz_to_s_offset($tz);
3611 $dest->{t_utc} = $t;
3614 sub process_commit {
3615 my ($c, $r_min, $r_max, $defer) = @_;
3616 if (defined $r_min && defined $r_max) {
3617 if ($r_min == $c->{r} && $r_min == $r_max) {
3618 show_commit($c);
3619 return 0;
3621 return 1 if $r_min == $r_max;
3622 if ($r_min < $r_max) {
3623 # we need to reverse the print order
3624 return 0 if (defined $limit && --$limit < 0);
3625 push @$defer, $c;
3626 return 1;
3628 if ($r_min != $r_max) {
3629 return 1 if ($r_min < $c->{r});
3630 return 1 if ($r_max > $c->{r});
3633 return 0 if (defined $limit && --$limit < 0);
3634 show_commit($c);
3635 return 1;
3638 sub show_commit {
3639 my $c = shift;
3640 if ($oneline) {
3641 my $x = "\n";
3642 if (my $l = $c->{l}) {
3643 while ($l->[0] =~ /^\s*$/) { shift @$l }
3644 $x = $l->[0];
3646 $l_fmt ||= 'A' . length($c->{r});
3647 print 'r',pack($l_fmt, $c->{r}),' | ';
3648 print "$c->{c} | " if $show_commit;
3649 print $x;
3650 } else {
3651 show_commit_normal($c);
3655 sub show_commit_changed_paths {
3656 my ($c) = @_;
3657 return unless $c->{changed};
3658 print "Changed paths:\n", @{$c->{changed}};
3661 sub show_commit_normal {
3662 my ($c) = @_;
3663 print '-' x72, "\nr$c->{r} | ";
3664 print "$c->{c} | " if $show_commit;
3665 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3666 localtime($c->{t_utc})), ' | ';
3667 my $nr_line = 0;
3669 if (my $l = $c->{l}) {
3670 while ($l->[$#$l] eq "\n" && $#$l > 0
3671 && $l->[($#$l - 1)] eq "\n") {
3672 pop @$l;
3674 $nr_line = scalar @$l;
3675 if (!$nr_line) {
3676 print "1 line\n\n\n";
3677 } else {
3678 if ($nr_line == 1) {
3679 $nr_line = '1 line';
3680 } else {
3681 $nr_line .= ' lines';
3683 print $nr_line, "\n";
3684 show_commit_changed_paths($c);
3685 print "\n";
3686 print $_ foreach @$l;
3688 } else {
3689 print "1 line\n";
3690 show_commit_changed_paths($c);
3691 print "\n";
3694 foreach my $x (qw/raw stat diff/) {
3695 if ($c->{$x}) {
3696 print "\n";
3697 print $_ foreach @{$c->{$x}}
3702 sub cmd_show_log {
3703 my (@args) = @_;
3704 my ($r_min, $r_max);
3705 my $r_last = -1; # prevent dupes
3706 if (defined $TZ) {
3707 $ENV{TZ} = $TZ;
3708 } else {
3709 delete $ENV{TZ};
3711 if (defined $::_revision) {
3712 if ($::_revision =~ /^(\d+):(\d+)$/) {
3713 ($r_min, $r_max) = ($1, $2);
3714 } elsif ($::_revision =~ /^\d+$/) {
3715 $r_min = $r_max = $::_revision;
3716 } else {
3717 ::fatal "-r$::_revision is not supported, use ",
3718 "standard \'git log\' arguments instead\n";
3722 config_pager();
3723 @args = git_svn_log_cmd($r_min, $r_max, @args);
3724 my $log = command_output_pipe(@args);
3725 run_pager();
3726 my (@k, $c, $d, $stat);
3727 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3728 while (<$log>) {
3729 if (/^${esc_color}commit ($::sha1_short)/o) {
3730 my $cmt = $1;
3731 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3732 $r_last = $c->{r};
3733 process_commit($c, $r_min, $r_max, \@k) or
3734 goto out;
3736 $d = undef;
3737 $c = { c => $cmt };
3738 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3739 get_author_info($c, $1, $2, $3);
3740 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3741 # ignore
3742 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3743 push @{$c->{raw}}, $_;
3744 } elsif (/^${esc_color}[ACRMDT]\t/) {
3745 # we could add $SVN->{svn_path} here, but that requires
3746 # remote access at the moment (repo_path_split)...
3747 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3748 push @{$c->{changed}}, $_;
3749 } elsif (/^${esc_color}diff /o) {
3750 $d = 1;
3751 push @{$c->{diff}}, $_;
3752 } elsif ($d) {
3753 push @{$c->{diff}}, $_;
3754 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3755 $esc_color*[\+\-]*$esc_color$/x) {
3756 $stat = 1;
3757 push @{$c->{stat}}, $_;
3758 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3759 push @{$c->{stat}}, $_;
3760 $stat = undef;
3761 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3762 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3763 } elsif (s/^${esc_color} //o) {
3764 push @{$c->{l}}, $_;
3767 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3768 $r_last = $c->{r};
3769 process_commit($c, $r_min, $r_max, \@k);
3771 if (@k) {
3772 my $swap = $r_max;
3773 $r_max = $r_min;
3774 $r_min = $swap;
3775 process_commit($_, $r_min, $r_max) foreach reverse @k;
3777 out:
3778 close $log;
3779 print '-' x72,"\n" unless $incremental || $oneline;
3782 package Git::SVN::Migration;
3783 # these version numbers do NOT correspond to actual version numbers
3784 # of git nor git-svn. They are just relative.
3786 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3788 # v1 layout: .git/$id/info/url, refs/remotes/$id
3790 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3792 # v3 layout: .git/svn/$id, refs/remotes/$id
3793 # - info/url may remain for backwards compatibility
3794 # - this is what we migrate up to this layout automatically,
3795 # - this will be used by git svn init on single branches
3796 # v3.1 layout (auto migrated):
3797 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3798 # for backwards compatibility
3800 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3801 # - this is only created for newly multi-init-ed
3802 # repositories. Similar in spirit to the
3803 # --use-separate-remotes option in git-clone (now default)
3804 # - we do not automatically migrate to this (following
3805 # the example set by core git)
3806 use strict;
3807 use warnings;
3808 use Carp qw/croak/;
3809 use File::Path qw/mkpath/;
3810 use File::Basename qw/dirname basename/;
3811 use vars qw/$_minimize/;
3813 sub migrate_from_v0 {
3814 my $git_dir = $ENV{GIT_DIR};
3815 return undef unless -d $git_dir;
3816 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3817 my $migrated = 0;
3818 while (<$fh>) {
3819 chomp;
3820 my ($id, $orig_ref) = ($_, $_);
3821 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3822 next unless -f "$git_dir/$id/info/url";
3823 my $new_ref = "refs/remotes/$id";
3824 if (::verify_ref("$new_ref^0")) {
3825 print STDERR "W: $orig_ref is probably an old ",
3826 "branch used by an ancient version of ",
3827 "git-svn.\n",
3828 "However, $new_ref also exists.\n",
3829 "We will not be able ",
3830 "to use this branch until this ",
3831 "ambiguity is resolved.\n";
3832 next;
3834 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3835 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3836 command_noisy('update-ref', $new_ref, $orig_ref);
3837 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3838 $migrated++;
3840 command_close_pipe($fh, $ctx);
3841 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3842 $migrated;
3845 sub migrate_from_v1 {
3846 my $git_dir = $ENV{GIT_DIR};
3847 my $migrated = 0;
3848 return $migrated unless -d $git_dir;
3849 my $svn_dir = "$git_dir/svn";
3851 # just in case somebody used 'svn' as their $id at some point...
3852 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3854 print STDERR "Migrating from a git-svn v1 layout...\n";
3855 mkpath([$svn_dir]);
3856 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3857 "$svn_dir\n\t(required for this version ",
3858 "($::VERSION) of git-svn) does not. exist\n";
3859 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3860 while (<$fh>) {
3861 my $x = $_;
3862 next unless $x =~ s#^refs/remotes/##;
3863 chomp $x;
3864 next unless -f "$git_dir/$x/info/url";
3865 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3866 next unless $u;
3867 my $dn = dirname("$git_dir/svn/$x");
3868 mkpath([$dn]) unless -d $dn;
3869 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3870 mkpath(["$git_dir/svn/svn"]);
3871 print STDERR " - $git_dir/$x/info => ",
3872 "$git_dir/svn/$x/info\n";
3873 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3874 croak "$!: $x";
3875 # don't worry too much about these, they probably
3876 # don't exist with repos this old (save for index,
3877 # and we can easily regenerate that)
3878 foreach my $f (qw/unhandled.log index .rev_db/) {
3879 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3881 } else {
3882 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3883 rename "$git_dir/$x", "$git_dir/svn/$x" or
3884 croak "$!: $x";
3886 $migrated++;
3888 command_close_pipe($fh, $ctx);
3889 print STDERR "Done migrating from a git-svn v1 layout\n";
3890 $migrated;
3893 sub read_old_urls {
3894 my ($l_map, $pfx, $path) = @_;
3895 my @dir;
3896 foreach (<$path/*>) {
3897 if (-r "$_/info/url") {
3898 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3899 my $ref_id = $pfx . basename $_;
3900 my $url = ::file_to_s("$_/info/url");
3901 $l_map->{$ref_id} = $url;
3902 } elsif (-d $_) {
3903 push @dir, $_;
3906 foreach (@dir) {
3907 my $x = $_;
3908 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3909 read_old_urls($l_map, $x, $_);
3913 sub migrate_from_v2 {
3914 my @cfg = command(qw/config -l/);
3915 return if grep /^svn-remote\..+\.url=/, @cfg;
3916 my %l_map;
3917 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3918 my $migrated = 0;
3920 foreach my $ref_id (sort keys %l_map) {
3921 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3922 if ($@) {
3923 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3925 $migrated++;
3927 $migrated;
3930 sub minimize_connections {
3931 my $r = Git::SVN::read_all_remotes();
3932 my $new_urls = {};
3933 my $root_repos = {};
3934 foreach my $repo_id (keys %$r) {
3935 my $url = $r->{$repo_id}->{url} or next;
3936 my $fetch = $r->{$repo_id}->{fetch} or next;
3937 my $ra = Git::SVN::Ra->new($url);
3939 # skip existing cases where we already connect to the root
3940 if (($ra->{url} eq $ra->{repos_root}) ||
3941 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3942 $repo_id)) {
3943 $root_repos->{$ra->{url}} = $repo_id;
3944 next;
3947 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3948 my $root_path = $ra->{url};
3949 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3950 foreach my $path (keys %$fetch) {
3951 my $ref_id = $fetch->{$path};
3952 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3954 # make sure we can read when connecting to
3955 # a higher level of a repository
3956 my ($last_rev, undef) = $gs->last_rev_commit;
3957 if (!defined $last_rev) {
3958 $last_rev = eval {
3959 $root_ra->get_latest_revnum;
3961 next if $@;
3963 my $new = $root_path;
3964 $new .= length $path ? "/$path" : '';
3965 eval {
3966 $root_ra->get_log([$new], $last_rev, $last_rev,
3967 0, 0, 1, sub { });
3969 next if $@;
3970 $new_urls->{$ra->{repos_root}}->{$new} =
3971 { ref_id => $ref_id,
3972 old_repo_id => $repo_id,
3973 old_path => $path };
3977 my @emptied;
3978 foreach my $url (keys %$new_urls) {
3979 # see if we can re-use an existing [svn-remote "repo_id"]
3980 # instead of creating a(n ugly) new section:
3981 my $repo_id = $root_repos->{$url} ||
3982 Git::SVN::sanitize_remote_name($url);
3984 my $fetch = $new_urls->{$url};
3985 foreach my $path (keys %$fetch) {
3986 my $x = $fetch->{$path};
3987 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3988 my $pfx = "svn-remote.$x->{old_repo_id}";
3990 my $old_fetch = quotemeta("$x->{old_path}:".
3991 "refs/remotes/$x->{ref_id}");
3992 command_noisy(qw/config --unset/,
3993 "$pfx.fetch", '^'. $old_fetch . '$');
3994 delete $r->{$x->{old_repo_id}}->
3995 {fetch}->{$x->{old_path}};
3996 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3997 command_noisy(qw/config --unset/,
3998 "$pfx.url");
3999 push @emptied, $x->{old_repo_id}
4003 if (@emptied) {
4004 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4005 "$ENV{GIT_DIR}/config";
4006 print STDERR <<EOF;
4007 The following [svn-remote] sections in your config file ($file) are empty
4008 and can be safely removed:
4010 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4014 sub migration_check {
4015 migrate_from_v0();
4016 migrate_from_v1();
4017 migrate_from_v2();
4018 minimize_connections() if $_minimize;
4021 package Git::IndexInfo;
4022 use strict;
4023 use warnings;
4024 use Git qw/command_input_pipe command_close_pipe/;
4026 sub new {
4027 my ($class) = @_;
4028 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4029 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4032 sub remove {
4033 my ($self, $path) = @_;
4034 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4035 return ++$self->{nr};
4037 undef;
4040 sub update {
4041 my ($self, $mode, $hash, $path) = @_;
4042 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4043 return ++$self->{nr};
4045 undef;
4048 sub DESTROY {
4049 my ($self) = @_;
4050 command_close_pipe($self->{gui}, $self->{ctx});
4053 package Git::SVN::GlobSpec;
4054 use strict;
4055 use warnings;
4057 sub new {
4058 my ($class, $glob) = @_;
4059 my $re = $glob;
4060 $re =~ s!/+$!!g; # no need for trailing slashes
4061 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4062 my ($left, $right) = ($1, $2);
4063 if ($nr > 1) {
4064 die "Only one '*' wildcard expansion ",
4065 "is supported (got $nr): '$glob'\n";
4066 } elsif ($nr == 0) {
4067 die "One '*' is needed for glob: '$glob'\n";
4069 $re = quotemeta($left) . $re . quotemeta($right);
4070 if (length $left && !($left =~ s!/+$!!g)) {
4071 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4073 if (length $right && !($right =~ s!^/+!!g)) {
4074 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4076 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4077 bless { left => $left, right => $right, left_regex => $left_re,
4078 regex => qr/$re/, glob => $glob }, $class;
4081 sub full_path {
4082 my ($self, $path) = @_;
4083 return (length $self->{left} ? "$self->{left}/" : '') .
4084 $path . (length $self->{right} ? "/$self->{right}" : '');
4087 __END__
4089 Data structures:
4092 $remotes = { # returned by read_all_remotes()
4093 'svn' => {
4094 # svn-remote.svn.url=https://svn.musicpd.org
4095 url => 'https://svn.musicpd.org',
4096 # svn-remote.svn.fetch=mpd/trunk:trunk
4097 fetch => {
4098 'mpd/trunk' => 'trunk',
4100 # svn-remote.svn.tags=mpd/tags/*:tags/*
4101 tags => {
4102 path => {
4103 left => 'mpd/tags',
4104 right => '',
4105 regex => qr!mpd/tags/([^/]+)$!,
4106 glob => 'tags/*',
4108 ref => {
4109 left => 'tags',
4110 right => '',
4111 regex => qr!tags/([^/]+)$!,
4112 glob => 'tags/*',
4118 $log_entry hashref as returned by libsvn_log_entry()
4120 log => 'whitespace-formatted log entry
4121 ', # trailing newline is preserved
4122 revision => '8', # integer
4123 date => '2004-02-24T17:01:44.108345Z', # commit date
4124 author => 'committer name'
4128 # this is generated by generate_diff();
4129 @mods = array of diff-index line hashes, each element represents one line
4130 of diff-index output
4132 diff-index line ($m hash)
4134 mode_a => first column of diff-index output, no leading ':',
4135 mode_b => second column of diff-index output,
4136 sha1_b => sha1sum of the final blob,
4137 chg => change type [MCRADT],
4138 file_a => original file name of a file (iff chg is 'C' or 'R')
4139 file_b => new/current file name of a file (any chg)
4143 # retval of read_url_paths{,_all}();
4144 $l_map = {
4145 # repository root url
4146 'https://svn.musicpd.org' => {
4147 # repository path # GIT_SVN_ID
4148 'mpd/trunk' => 'trunk',
4149 'mpd/tags/0.11.5' => 'tags/0.11.5',
4153 Notes:
4154 I don't trust the each() function on unless I created %hash myself
4155 because the internal iterator may not have started at base.