git-svn: bail out on incorrect command-line options
[git/dkf.git] / git-svn.perl
blob6216cade0f0e019457293aff0e1561c4bc0e42f2
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 my $s;
42 foreach (qw/command command_oneline command_noisy command_output_pipe
43 command_input_pipe command_close_pipe/) {
44 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
45 "*Git::SVN::Migration::$_ = ".
46 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
48 eval $s;
51 my ($SVN);
53 $sha1 = qr/[a-f\d]{40}/;
54 $sha1_short = qr/[a-f\d]{4,40}/;
55 my ($_stdin, $_help, $_edit,
56 $_message, $_file,
57 $_template, $_shared,
58 $_version, $_fetch_all,
59 $_merge, $_strategy, $_dry_run, $_local,
60 $_prefix, $_no_checkout, $_verbose);
61 $Git::SVN::_follow_parent = 1;
62 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63 'config-dir=s' => \$Git::SVN::Ra::config_dir,
64 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
65 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
66 'authors-file|A=s' => \$_authors,
67 'repack:i' => \$Git::SVN::_repack,
68 'noMetadata' => \$Git::SVN::_no_metadata,
69 'useSvmProps' => \$Git::SVN::_use_svm_props,
70 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
71 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
72 'no-checkout' => \$_no_checkout,
73 'quiet|q' => \$_q,
74 'repack-flags|repack-args|repack-opts=s' =>
75 \$Git::SVN::_repack_flags,
76 %remote_opts );
78 my ($_trunk, $_tags, $_branches);
79 my %icv;
80 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
83 'no-metadata' => sub { $icv{noMetadata} = 1 },
84 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
85 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
86 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
87 %remote_opts );
88 my %cmt_opts = ( 'edit|e' => \$_edit,
89 'rmdir' => \$SVN::Git::Editor::_rmdir,
90 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
91 'l=i' => \$SVN::Git::Editor::_rename_limit,
92 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
95 my %cmd = (
96 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
97 { 'revision|r=s' => \$_revision,
98 'fetch-all|all' => \$_fetch_all,
99 %fc_opts } ],
100 clone => [ \&cmd_clone, "Initialize and fetch revisions",
101 { 'revision|r=s' => \$_revision,
102 %fc_opts, %init_opts } ],
103 init => [ \&cmd_init, "Initialize a repo for tracking" .
104 " (requires URL argument)",
105 \%init_opts ],
106 'multi-init' => [ \&cmd_multi_init,
107 "Deprecated alias for ".
108 "'$0 init -T<trunk> -b<branches> -t<tags>'",
109 \%init_opts ],
110 dcommit => [ \&cmd_dcommit,
111 'Commit several diffs to merge with upstream',
112 { 'merge|m|M' => \$_merge,
113 'strategy|s=s' => \$_strategy,
114 'verbose|v' => \$_verbose,
115 'dry-run|n' => \$_dry_run,
116 'fetch-all|all' => \$_fetch_all,
117 %cmt_opts, %fc_opts } ],
118 'set-tree' => [ \&cmd_set_tree,
119 "Set an SVN repository to a git tree-ish",
120 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
121 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
122 { 'revision|r=i' => \$_revision } ],
123 'multi-fetch' => [ \&cmd_multi_fetch,
124 "Deprecated alias for $0 fetch --all",
125 { 'revision|r=s' => \$_revision, %fc_opts } ],
126 'migrate' => [ sub { },
127 # no-op, we automatically run this anyways,
128 'Migrate configuration/metadata/layout from
129 previous versions of git-svn',
130 { 'minimize' => \$Git::SVN::Migration::_minimize,
131 %remote_opts } ],
132 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
133 { 'limit=i' => \$Git::SVN::Log::limit,
134 'revision|r=s' => \$_revision,
135 'verbose|v' => \$Git::SVN::Log::verbose,
136 'incremental' => \$Git::SVN::Log::incremental,
137 'oneline' => \$Git::SVN::Log::oneline,
138 'show-commit' => \$Git::SVN::Log::show_commit,
139 'non-recursive' => \$Git::SVN::Log::non_recursive,
140 'authors-file|A=s' => \$_authors,
141 'color' => \$Git::SVN::Log::color,
142 'pager=s' => \$Git::SVN::Log::pager,
143 } ],
144 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
145 { 'merge|m|M' => \$_merge,
146 'verbose|v' => \$_verbose,
147 'strategy|s=s' => \$_strategy,
148 'local|l' => \$_local,
149 'fetch-all|all' => \$_fetch_all,
150 %fc_opts } ],
151 'commit-diff' => [ \&cmd_commit_diff,
152 'Commit a diff between two trees',
153 { 'message|m=s' => \$_message,
154 'file|F=s' => \$_file,
155 'revision|r=s' => \$_revision,
156 %cmt_opts } ],
159 my $cmd;
160 for (my $i = 0; $i < @ARGV; $i++) {
161 if (defined $cmd{$ARGV[$i]}) {
162 $cmd = $ARGV[$i];
163 splice @ARGV, $i, 1;
164 last;
168 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
170 read_repo_config(\%opts);
171 Getopt::Long::Configure('pass_through') if $cmd eq 'log';
172 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
173 'minimize-connections' => \$Git::SVN::Migration::_minimize,
174 'id|i=s' => \$Git::SVN::default_ref_id,
175 'svn-remote|remote|R=s' => sub {
176 $Git::SVN::no_reuse_existing = 1;
177 $Git::SVN::default_repo_id = $_[1] });
178 exit 1 if (!$rv && $cmd ne 'log');
180 usage(0) if $_help;
181 version() if $_version;
182 usage(1) unless defined $cmd;
183 load_authors() if $_authors;
185 # make sure we're always running
186 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
187 unless (-d $ENV{GIT_DIR}) {
188 if ($git_dir_user_set) {
189 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
190 "but it is not a directory\n";
192 my $git_dir = delete $ENV{GIT_DIR};
193 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
194 unless (length $cdup) {
195 die "Already at toplevel, but $git_dir ",
196 "not found '$cdup'\n";
198 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
199 unless (-d $git_dir) {
200 die "$git_dir still not found after going to ",
201 "'$cdup'\n";
203 $ENV{GIT_DIR} = $git_dir;
206 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
207 Git::SVN::Migration::migration_check();
209 Git::SVN::init_vars();
210 eval {
211 Git::SVN::verify_remotes_sanity();
212 $cmd{$cmd}->[0]->(@ARGV);
214 fatal $@ if $@;
215 post_fetch_checkout();
216 exit 0;
218 ####################### primary functions ######################
219 sub usage {
220 my $exit = shift || 0;
221 my $fd = $exit ? \*STDERR : \*STDOUT;
222 print $fd <<"";
223 git-svn - bidirectional operations between a single Subversion tree and git
224 Usage: $0 <command> [options] [arguments]\n
226 print $fd "Available commands:\n" unless $cmd;
228 foreach (sort keys %cmd) {
229 next if $cmd && $cmd ne $_;
230 next if /^multi-/; # don't show deprecated commands
231 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
232 foreach (keys %{$cmd{$_}->[2]}) {
233 # mixed-case options are for .git/config only
234 next if /[A-Z]/ && /^[a-z]+$/i;
235 # prints out arguments as they should be passed:
236 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
237 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
238 "--$_" : "-$_" }
239 split /\|/,$_)," $x\n";
242 print $fd <<"";
243 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
244 arbitrary identifier if you're tracking multiple SVN branches/repositories in
245 one git repository and want to keep them separate. See git-svn(1) for more
246 information.
248 exit $exit;
251 sub version {
252 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
253 exit 0;
256 sub do_git_init_db {
257 unless (-d $ENV{GIT_DIR}) {
258 my @init_db = ('init');
259 push @init_db, "--template=$_template" if defined $_template;
260 if (defined $_shared) {
261 if ($_shared =~ /[a-z]/) {
262 push @init_db, "--shared=$_shared";
263 } else {
264 push @init_db, "--shared";
267 command_noisy(@init_db);
269 my $set;
270 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
271 foreach my $i (keys %icv) {
272 die "'$set' and '$i' cannot both be set\n" if $set;
273 next unless defined $icv{$i};
274 command_noisy('config', "$pfx.$i", $icv{$i});
275 $set = $i;
279 sub init_subdir {
280 my $repo_path = shift or return;
281 mkpath([$repo_path]) unless -d $repo_path;
282 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
283 $ENV{GIT_DIR} = '.git';
286 sub cmd_clone {
287 my ($url, $path) = @_;
288 if (!defined $path &&
289 (defined $_trunk || defined $_branches || defined $_tags) &&
290 $url !~ m#^[a-z\+]+://#) {
291 $path = $url;
293 $path = basename($url) if !defined $path || !length $path;
294 cmd_init($url, $path);
295 Git::SVN::fetch_all($Git::SVN::default_repo_id);
298 sub cmd_init {
299 if (defined $_trunk || defined $_branches || defined $_tags) {
300 return cmd_multi_init(@_);
302 my $url = shift or die "SVN repository location required ",
303 "as a command-line argument\n";
304 init_subdir(@_);
305 do_git_init_db();
307 Git::SVN->init($url);
310 sub cmd_fetch {
311 if (grep /^\d+=./, @_) {
312 die "'<rev>=<commit>' fetch arguments are ",
313 "no longer supported.\n";
315 my ($remote) = @_;
316 if (@_ > 1) {
317 die "Usage: $0 fetch [--all] [svn-remote]\n";
319 $remote ||= $Git::SVN::default_repo_id;
320 if ($_fetch_all) {
321 cmd_multi_fetch();
322 } else {
323 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
327 sub cmd_set_tree {
328 my (@commits) = @_;
329 if ($_stdin || !@commits) {
330 print "Reading from stdin...\n";
331 @commits = ();
332 while (<STDIN>) {
333 if (/\b($sha1_short)\b/o) {
334 unshift @commits, $1;
338 my @revs;
339 foreach my $c (@commits) {
340 my @tmp = command('rev-parse',$c);
341 if (scalar @tmp == 1) {
342 push @revs, $tmp[0];
343 } elsif (scalar @tmp > 1) {
344 push @revs, reverse(command('rev-list',@tmp));
345 } else {
346 fatal "Failed to rev-parse $c\n";
349 my $gs = Git::SVN->new;
350 my ($r_last, $cmt_last) = $gs->last_rev_commit;
351 $gs->fetch;
352 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
353 fatal "There are new revisions that were fetched ",
354 "and need to be merged (or acknowledged) ",
355 "before committing.\nlast rev: $r_last\n",
356 " current: $gs->{last_rev}\n";
358 $gs->set_tree($_) foreach @revs;
359 print "Done committing ",scalar @revs," revisions to SVN\n";
362 sub cmd_dcommit {
363 my $head = shift;
364 $head ||= 'HEAD';
365 my @refs;
366 my ($url, $rev, $uuid) = working_head_info($head, \@refs);
367 my $c = $refs[-1];
368 unless (defined $url && defined $rev && defined $uuid) {
369 die "Unable to determine upstream SVN information from ",
370 "$head history\n";
372 my $gs = Git::SVN->find_by_url($url);
373 my $last_rev;
374 foreach my $d (@refs) {
375 if (!verify_ref("$d~1")) {
376 fatal "Commit $d\n",
377 "has no parent commit, and therefore ",
378 "nothing to diff against.\n",
379 "You should be working from a repository ",
380 "originally created by git-svn\n";
382 unless (defined $last_rev) {
383 (undef, $last_rev, undef) = cmt_metadata("$d~1");
384 unless (defined $last_rev) {
385 fatal "Unable to extract revision information ",
386 "from commit $d~1\n";
389 if ($_dry_run) {
390 print "diff-tree $d~1 $d\n";
391 } else {
392 my %ed_opts = ( r => $last_rev,
393 log => get_commit_entry($d)->{log},
394 ra => Git::SVN::Ra->new($url),
395 tree_a => "$d~1",
396 tree_b => $d,
397 editor_cb => sub {
398 print "Committed r$_[0]\n";
399 $last_rev = $_[0]; },
400 svn_path => '');
401 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
402 print "No changes\n$d~1 == $d\n";
406 return if $_dry_run;
407 unless ($gs) {
408 warn "Could not determine fetch information for $url\n",
409 "Will not attempt to fetch and rebase commits.\n",
410 "This probably means you have useSvmProps and should\n",
411 "now resync your SVN::Mirror repository.\n";
412 return;
414 $_fetch_all ? $gs->fetch_all : $gs->fetch;
415 # we always want to rebase against the current HEAD, not any
416 # head that was passed to us
417 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
418 my @finish;
419 if (@diff) {
420 @finish = rebase_cmd();
421 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
422 "using @finish:\n", "@diff";
423 } else {
424 print "No changes between current HEAD and ",
425 $gs->refname, "\nResetting to the latest ",
426 $gs->refname, "\n";
427 @finish = qw/reset --mixed/;
429 command_noisy(@finish, $gs->refname);
432 sub cmd_rebase {
433 command_noisy(qw/update-index --refresh/);
434 my $url = (working_head_info('HEAD'))[0];
435 if (!defined $url) {
436 die "Unable to determine upstream SVN information from ",
437 "working tree history\n";
440 my $gs = Git::SVN->find_by_url($url);
441 unless ($gs) {
442 die "Unable to determine remote information from URL: $url\n";
444 if (command(qw/diff-index HEAD --/)) {
445 print STDERR "Cannot rebase with uncommited changes:\n";
446 command_noisy('status');
447 exit 1;
449 unless ($_local) {
450 $_fetch_all ? $gs->fetch_all : $gs->fetch;
452 command_noisy(rebase_cmd(), $gs->refname);
455 sub cmd_show_ignore {
456 my $url = (::working_head_info('HEAD'))[0];
457 my $gs = Git::SVN->find_by_url($url) || Git::SVN->new;
458 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
459 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
462 sub cmd_multi_init {
463 my $url = shift;
464 unless (defined $_trunk || defined $_branches || defined $_tags) {
465 usage(1);
467 $_prefix = '' unless defined $_prefix;
468 if (defined $url) {
469 $url =~ s#/+$##;
470 init_subdir(@_);
472 do_git_init_db();
473 if (defined $_trunk) {
474 my $trunk_ref = $_prefix . 'trunk';
475 # try both old-style and new-style lookups:
476 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
477 unless ($gs_trunk) {
478 my ($trunk_url, $trunk_path) =
479 complete_svn_url($url, $_trunk);
480 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
481 undef, $trunk_ref);
484 return unless defined $_branches || defined $_tags;
485 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
486 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
487 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
490 sub cmd_multi_fetch {
491 my $remotes = Git::SVN::read_all_remotes();
492 foreach my $repo_id (sort keys %$remotes) {
493 if ($remotes->{$repo_id}->{url}) {
494 Git::SVN::fetch_all($repo_id, $remotes);
499 # this command is special because it requires no metadata
500 sub cmd_commit_diff {
501 my ($ta, $tb, $url) = @_;
502 my $usage = "Usage: $0 commit-diff -r<revision> ".
503 "<tree-ish> <tree-ish> [<URL>]\n";
504 fatal($usage) if (!defined $ta || !defined $tb);
505 my $svn_path;
506 if (!defined $url) {
507 my $gs = eval { Git::SVN->new };
508 if (!$gs) {
509 fatal("Needed URL or usable git-svn --id in ",
510 "the command-line\n", $usage);
512 $url = $gs->{url};
513 $svn_path = $gs->{path};
515 unless (defined $_revision) {
516 fatal("-r|--revision is a required argument\n", $usage);
518 if (defined $_message && defined $_file) {
519 fatal("Both --message/-m and --file/-F specified ",
520 "for the commit message.\n",
521 "I have no idea what you mean\n");
523 if (defined $_file) {
524 $_message = file_to_s($_file);
525 } else {
526 $_message ||= get_commit_entry($tb)->{log};
528 my $ra ||= Git::SVN::Ra->new($url);
529 $svn_path ||= $ra->{svn_path};
530 my $r = $_revision;
531 if ($r eq 'HEAD') {
532 $r = $ra->get_latest_revnum;
533 } elsif ($r !~ /^\d+$/) {
534 die "revision argument: $r not understood by git-svn\n";
536 my %ed_opts = ( r => $r,
537 log => $_message,
538 ra => $ra,
539 tree_a => $ta,
540 tree_b => $tb,
541 editor_cb => sub { print "Committed r$_[0]\n" },
542 svn_path => $svn_path );
543 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
544 print "No changes\n$ta == $tb\n";
548 ########################### utility functions #########################
550 sub rebase_cmd {
551 my @cmd = qw/rebase/;
552 push @cmd, '-v' if $_verbose;
553 push @cmd, qw/--merge/ if $_merge;
554 push @cmd, "--strategy=$_strategy" if $_strategy;
555 @cmd;
558 sub post_fetch_checkout {
559 return if $_no_checkout;
560 my $gs = $Git::SVN::_head or return;
561 return if verify_ref('refs/heads/master^0');
563 my $valid_head = verify_ref('HEAD^0');
564 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
565 return if ($valid_head || !verify_ref('HEAD^0'));
567 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
568 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
569 return if -f $index;
571 chomp(my $bare = `git config --bool --get core.bare`);
572 return if $bare eq 'true';
573 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
574 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
575 print STDERR "Checked out HEAD:\n ",
576 $gs->full_url, " r", $gs->last_rev, "\n";
579 sub complete_svn_url {
580 my ($url, $path) = @_;
581 $path =~ s#/+$##;
582 if ($path !~ m#^[a-z\+]+://#) {
583 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
584 fatal("E: '$path' is not a complete URL ",
585 "and a separate URL is not specified\n");
587 return ($url, $path);
589 return ($path, '');
592 sub complete_url_ls_init {
593 my ($ra, $repo_path, $switch, $pfx) = @_;
594 unless ($repo_path) {
595 print STDERR "W: $switch not specified\n";
596 return;
598 $repo_path =~ s#/+$##;
599 if ($repo_path =~ m#^[a-z\+]+://#) {
600 $ra = Git::SVN::Ra->new($repo_path);
601 $repo_path = '';
602 } else {
603 $repo_path =~ s#^/+##;
604 unless ($ra) {
605 fatal("E: '$repo_path' is not a complete URL ",
606 "and a separate URL is not specified\n");
609 my $url = $ra->{url};
610 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
611 my $k = "svn-remote.$gs->{repo_id}.url";
612 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
613 if ($orig_url && ($orig_url ne $gs->{url})) {
614 die "$k already set: $orig_url\n",
615 "wanted to set to: $gs->{url}\n";
617 command_oneline('config', $k, $gs->{url}) unless $orig_url;
618 my $remote_path = "$ra->{svn_path}/$repo_path/*";
619 $remote_path =~ s#/+#/#g;
620 $remote_path =~ s#^/##g;
621 my ($n) = ($switch =~ /^--(\w+)/);
622 if (length $pfx && $pfx !~ m#/$#) {
623 die "--prefix='$pfx' must have a trailing slash '/'\n";
625 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
626 "$remote_path:refs/remotes/$pfx*");
629 sub verify_ref {
630 my ($ref) = @_;
631 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
632 { STDERR => 0 }); };
635 sub get_tree_from_treeish {
636 my ($treeish) = @_;
637 # $treeish can be a symbolic ref, too:
638 my $type = command_oneline(qw/cat-file -t/, $treeish);
639 my $expected;
640 while ($type eq 'tag') {
641 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
643 if ($type eq 'commit') {
644 $expected = (grep /^tree /, command(qw/cat-file commit/,
645 $treeish))[0];
646 ($expected) = ($expected =~ /^tree ($sha1)$/o);
647 die "Unable to get tree from $treeish\n" unless $expected;
648 } elsif ($type eq 'tree') {
649 $expected = $treeish;
650 } else {
651 die "$treeish is a $type, expected tree, tag or commit\n";
653 return $expected;
656 sub get_commit_entry {
657 my ($treeish) = shift;
658 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
659 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
660 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
661 open my $log_fh, '>', $commit_editmsg or croak $!;
663 my $type = command_oneline(qw/cat-file -t/, $treeish);
664 if ($type eq 'commit' || $type eq 'tag') {
665 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
666 $type, $treeish);
667 my $in_msg = 0;
668 while (<$msg_fh>) {
669 if (!$in_msg) {
670 $in_msg = 1 if (/^\s*$/);
671 } elsif (/^git-svn-id: /) {
672 # skip this for now, we regenerate the
673 # correct one on re-fetch anyways
674 # TODO: set *:merge properties or like...
675 } else {
676 print $log_fh $_ or croak $!;
679 command_close_pipe($msg_fh, $ctx);
681 close $log_fh or croak $!;
683 if ($_edit || ($type eq 'tree')) {
684 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
685 # TODO: strip out spaces, comments, like git-commit.sh
686 system($editor, $commit_editmsg);
688 rename $commit_editmsg, $commit_msg or croak $!;
689 open $log_fh, '<', $commit_msg or croak $!;
690 { local $/; chomp($log_entry{log} = <$log_fh>); }
691 close $log_fh or croak $!;
692 unlink $commit_msg;
693 \%log_entry;
696 sub s_to_file {
697 my ($str, $file, $mode) = @_;
698 open my $fd,'>',$file or croak $!;
699 print $fd $str,"\n" or croak $!;
700 close $fd or croak $!;
701 chmod ($mode &~ umask, $file) if (defined $mode);
704 sub file_to_s {
705 my $file = shift;
706 open my $fd,'<',$file or croak "$!: file: $file\n";
707 local $/;
708 my $ret = <$fd>;
709 close $fd or croak $!;
710 $ret =~ s/\s*$//s;
711 return $ret;
714 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
715 sub load_authors {
716 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
717 my $log = $cmd eq 'log';
718 while (<$authors>) {
719 chomp;
720 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
721 my ($user, $name, $email) = ($1, $2, $3);
722 if ($log) {
723 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
724 } else {
725 $users{$user} = [$name, $email];
728 close $authors or croak $!;
731 # convert GetOpt::Long specs for use by git-config
732 sub read_repo_config {
733 return unless -d $ENV{GIT_DIR};
734 my $opts = shift;
735 my @config_only;
736 foreach my $o (keys %$opts) {
737 # if we have mixedCase and a long option-only, then
738 # it's a config-only variable that we don't need for
739 # the command-line.
740 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
741 my $v = $opts->{$o};
742 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
743 $key =~ s/-//g;
744 my $arg = 'git-config';
745 $arg .= ' --int' if ($o =~ /[:=]i$/);
746 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
747 if (ref $v eq 'ARRAY') {
748 chomp(my @tmp = `$arg --get-all svn.$key`);
749 @$v = @tmp if @tmp;
750 } else {
751 chomp(my $tmp = `$arg --get svn.$key`);
752 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
753 $$v = $tmp;
757 delete @$opts{@config_only} if @config_only;
760 sub extract_metadata {
761 my $id = shift or return (undef, undef, undef);
762 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
763 \s([a-f\d\-]+)$/x);
764 if (!defined $rev || !$uuid || !$url) {
765 # some of the original repositories I made had
766 # identifiers like this:
767 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
769 return ($url, $rev, $uuid);
772 sub cmt_metadata {
773 return extract_metadata((grep(/^git-svn-id: /,
774 command(qw/cat-file commit/, shift)))[-1]);
777 sub working_head_info {
778 my ($head, $refs) = @_;
779 my ($url, $rev, $uuid);
780 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
781 while (<$fh>) {
782 chomp;
783 ($url, $rev, $uuid) = cmt_metadata($_);
784 last if (defined $url && defined $rev && defined $uuid);
785 unshift @$refs, $_ if $refs;
787 close $fh; # break the pipe
788 ($url, $rev, $uuid);
791 package Git::SVN;
792 use strict;
793 use warnings;
794 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
795 $_repack $_repack_flags $_use_svm_props $_head
796 $_use_svnsync_props $no_reuse_existing/;
797 use Carp qw/croak/;
798 use File::Path qw/mkpath/;
799 use File::Copy qw/copy/;
800 use IPC::Open3;
802 my $_repack_nr;
803 # properties that we do not log:
804 my %SKIP_PROP;
805 BEGIN {
806 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
807 svn:special svn:executable
808 svn:entry:committed-rev
809 svn:entry:last-author
810 svn:entry:uuid
811 svn:entry:committed-date/;
813 # some options are read globally, but can be overridden locally
814 # per [svn-remote "..."] section. Command-line options will *NOT*
815 # override options set in an [svn-remote "..."] section
816 my $e;
817 foreach (qw/follow_parent no_metadata use_svm_props
818 use_svnsync_props/) {
819 my $key = $_;
820 $key =~ tr/_//d;
821 $e .= "sub $_ {
822 my (\$self) = \@_;
823 return \$self->{-$_} if exists \$self->{-$_};
824 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
825 eval { command_oneline(qw/config --get/, \$k) };
826 if (\$@) {
827 \$self->{-$_} = \$Git::SVN::_$_;
828 } else {
829 my \$v = command_oneline(qw/config --bool/,\$k);
830 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
832 return \$self->{-$_} }\n";
834 $e .= "1;\n";
835 eval $e or die $@;
838 my %LOCKFILES;
839 END { unlink keys %LOCKFILES if %LOCKFILES }
841 sub resolve_local_globs {
842 my ($url, $fetch, $glob_spec) = @_;
843 return unless defined $glob_spec;
844 my $ref = $glob_spec->{ref};
845 my $path = $glob_spec->{path};
846 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
847 next unless m#^refs/remotes/$ref->{regex}$#;
848 my $p = $1;
849 my $pathname = $path->full_path($p);
850 my $refname = $ref->full_path($p);
851 if (my $existing = $fetch->{$pathname}) {
852 if ($existing ne $refname) {
853 die "Refspec conflict:\n",
854 "existing: refs/remotes/$existing\n",
855 " globbed: refs/remotes/$refname\n";
857 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
858 $u =~ s!^\Q$url\E(/|$)!! or die
859 "refs/remotes/$refname: '$url' not found in '$u'\n";
860 if ($pathname ne $u) {
861 warn "W: Refspec glob conflict ",
862 "(ref: refs/remotes/$refname):\n",
863 "expected path: $pathname\n",
864 " real path: $u\n",
865 "Continuing ahead with $u\n";
866 next;
868 } else {
869 $fetch->{$pathname} = $refname;
874 sub parse_revision_argument {
875 my ($base, $head) = @_;
876 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
877 return ($base, $head);
879 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
880 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
881 return ($head, $head) if ($::_revision eq 'HEAD');
882 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
883 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
884 die "revision argument: $::_revision not understood by git-svn\n";
887 sub fetch_all {
888 my ($repo_id, $remotes) = @_;
889 if (ref $repo_id) {
890 my $gs = $repo_id;
891 $repo_id = undef;
892 $repo_id = $gs->{repo_id};
894 $remotes ||= read_all_remotes();
895 my $remote = $remotes->{$repo_id} or
896 die "[svn-remote \"$repo_id\"] unknown\n";
897 my $fetch = $remote->{fetch};
898 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
899 my (@gs, @globs);
900 my $ra = Git::SVN::Ra->new($url);
901 my $uuid = $ra->get_uuid;
902 my $head = $ra->get_latest_revnum;
903 my $base = defined $fetch ? $head : 0;
905 # read the max revs for wildcard expansion (branches/*, tags/*)
906 foreach my $t (qw/branches tags/) {
907 defined $remote->{$t} or next;
908 push @globs, $remote->{$t};
909 my $max_rev = eval { tmp_config(qw/--int --get/,
910 "svn-remote.$repo_id.${t}-maxRev") };
911 if (defined $max_rev && ($max_rev < $base)) {
912 $base = $max_rev;
913 } elsif (!defined $max_rev) {
914 $base = 0;
918 if ($fetch) {
919 foreach my $p (sort keys %$fetch) {
920 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
921 my $lr = $gs->rev_db_max;
922 if (defined $lr) {
923 $base = $lr if ($lr < $base);
925 push @gs, $gs;
929 ($base, $head) = parse_revision_argument($base, $head);
930 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
933 sub read_all_remotes {
934 my $r = {};
935 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
936 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
937 $r->{$1}->{fetch}->{$2} = $3;
938 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
939 $r->{$1}->{url} = $2;
940 } elsif (m!^(.+)\.(branches|tags)=
941 (.*):refs/remotes/(.+)\s*$/!x) {
942 my ($p, $g) = ($3, $4);
943 my $rs = $r->{$1}->{$2} = {
944 t => $2,
945 remote => $1,
946 path => Git::SVN::GlobSpec->new($p),
947 ref => Git::SVN::GlobSpec->new($g) };
948 if (length($rs->{ref}->{right}) != 0) {
949 die "The '*' glob character must be the last ",
950 "character of '$g'\n";
957 sub init_vars {
958 if (defined $_repack) {
959 $_repack = 1000 if ($_repack <= 0);
960 $_repack_nr = $_repack;
961 $_repack_flags ||= '-d';
965 sub verify_remotes_sanity {
966 return unless -d $ENV{GIT_DIR};
967 my %seen;
968 foreach (command(qw/config -l/)) {
969 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
970 if ($seen{$1}) {
971 die "Remote ref refs/remote/$1 is tracked by",
972 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
973 "Please resolve this ambiguity in ",
974 "your git configuration file before ",
975 "continuing\n";
977 $seen{$1} = $_;
982 # we allow more chars than remotes2config.sh...
983 sub sanitize_remote_name {
984 my ($name) = @_;
985 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
986 $name;
989 sub find_existing_remote {
990 my ($url, $remotes) = @_;
991 return undef if $no_reuse_existing;
992 my $existing;
993 foreach my $repo_id (keys %$remotes) {
994 my $u = $remotes->{$repo_id}->{url} or next;
995 next if $u ne $url;
996 $existing = $repo_id;
997 last;
999 $existing;
1002 sub init_remote_config {
1003 my ($self, $url, $no_write) = @_;
1004 $url =~ s!/+$!!; # strip trailing slash
1005 my $r = read_all_remotes();
1006 my $existing = find_existing_remote($url, $r);
1007 if ($existing) {
1008 unless ($no_write) {
1009 print STDERR "Using existing ",
1010 "[svn-remote \"$existing\"]\n";
1012 $self->{repo_id} = $existing;
1013 } else {
1014 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1015 $existing = find_existing_remote($min_url, $r);
1016 if ($existing) {
1017 unless ($no_write) {
1018 print STDERR "Using existing ",
1019 "[svn-remote \"$existing\"]\n";
1021 $self->{repo_id} = $existing;
1023 if ($min_url ne $url) {
1024 unless ($no_write) {
1025 print STDERR "Using higher level of URL: ",
1026 "$url => $min_url\n";
1028 my $old_path = $self->{path};
1029 $self->{path} = $url;
1030 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1031 if (length $old_path) {
1032 $self->{path} .= "/$old_path";
1034 $url = $min_url;
1037 my $orig_url;
1038 if (!$existing) {
1039 # verify that we aren't overwriting anything:
1040 $orig_url = eval {
1041 command_oneline('config', '--get',
1042 "svn-remote.$self->{repo_id}.url")
1044 if ($orig_url && ($orig_url ne $url)) {
1045 die "svn-remote.$self->{repo_id}.url already set: ",
1046 "$orig_url\nwanted to set to: $url\n";
1049 my ($xrepo_id, $xpath) = find_ref($self->refname);
1050 if (defined $xpath) {
1051 die "svn-remote.$xrepo_id.fetch already set to track ",
1052 "$xpath:refs/remotes/", $self->refname, "\n";
1054 unless ($no_write) {
1055 command_noisy('config',
1056 "svn-remote.$self->{repo_id}.url", $url);
1057 command_noisy('config', '--add',
1058 "svn-remote.$self->{repo_id}.fetch",
1059 "$self->{path}:".$self->refname);
1061 $self->{url} = $url;
1064 sub find_by_url { # repos_root and, path are optional
1065 my ($class, $full_url, $repos_root, $path) = @_;
1066 return undef unless defined $full_url;
1067 my $remotes = read_all_remotes();
1068 if (defined $full_url && defined $repos_root && !defined $path) {
1069 $path = $full_url;
1070 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1072 foreach my $repo_id (keys %$remotes) {
1073 my $u = $remotes->{$repo_id}->{url} or next;
1074 next if defined $repos_root && $repos_root ne $u;
1076 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1077 foreach (qw/branches tags/) {
1078 resolve_local_globs($u, $fetch,
1079 $remotes->{$repo_id}->{$_});
1081 my $p = $path;
1082 unless (defined $p) {
1083 $p = $full_url;
1084 $p =~ s#^\Q$u\E(?:/|$)## or next;
1086 foreach my $f (keys %$fetch) {
1087 next if $f ne $p;
1088 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1091 undef;
1094 sub init {
1095 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1096 my $self = _new($class, $repo_id, $ref_id, $path);
1097 if (defined $url) {
1098 $self->init_remote_config($url, $no_write);
1100 $self;
1103 sub find_ref {
1104 my ($ref_id) = @_;
1105 foreach (command(qw/config -l/)) {
1106 next unless m!^svn-remote\.(.+)\.fetch=
1107 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1108 my ($repo_id, $path, $ref) = ($1, $2, $3);
1109 if ($ref eq $ref_id) {
1110 $path = '' if ($path =~ m#^\./?#);
1111 return ($repo_id, $path);
1114 (undef, undef, undef);
1117 sub new {
1118 my ($class, $ref_id, $repo_id, $path) = @_;
1119 if (defined $ref_id && !defined $repo_id && !defined $path) {
1120 ($repo_id, $path) = find_ref($ref_id);
1121 if (!defined $repo_id) {
1122 die "Could not find a \"svn-remote.*.fetch\" key ",
1123 "in the repository configuration matching: ",
1124 "refs/remotes/$ref_id\n";
1127 my $self = _new($class, $repo_id, $ref_id, $path);
1128 if (!defined $self->{path} || !length $self->{path}) {
1129 my $fetch = command_oneline('config', '--get',
1130 "svn-remote.$repo_id.fetch",
1131 ":refs/remotes/$ref_id\$") or
1132 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1133 "\":refs/remotes/$ref_id\$\" in config\n";
1134 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1136 $self->{url} = command_oneline('config', '--get',
1137 "svn-remote.$repo_id.url") or
1138 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1139 $self->rebuild;
1140 $self;
1143 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1145 sub svm_uuid {
1146 my ($self) = @_;
1147 return $self->{svm}->{uuid} if $self->svm;
1148 $self->ra;
1149 unless ($self->{svm}) {
1150 die "SVM UUID not cached, and reading remotely failed\n";
1152 $self->{svm}->{uuid};
1155 sub svm {
1156 my ($self) = @_;
1157 return $self->{svm} if $self->{svm};
1158 my $svm;
1159 # see if we have it in our config, first:
1160 eval {
1161 my $section = "svn-remote.$self->{repo_id}";
1162 $svm = {
1163 source => tmp_config('--get', "$section.svm-source"),
1164 uuid => tmp_config('--get', "$section.svm-uuid"),
1165 replace => tmp_config('--get', "$section.svm-replace"),
1168 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1169 $self->{svm} = $svm;
1171 $self->{svm};
1174 sub _set_svm_vars {
1175 my ($self, $ra) = @_;
1176 return $ra if $self->svm;
1178 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1179 "(svm:source, svm:uuid) ",
1180 "from the following URLs:\n" );
1181 sub read_svm_props {
1182 my ($self, $ra, $path, $r) = @_;
1183 my $props = ($ra->get_dir($path, $r))[2];
1184 my $src = $props->{'svm:source'};
1185 my $uuid = $props->{'svm:uuid'};
1186 return undef if (!$src || !$uuid);
1188 chomp($src, $uuid);
1190 $uuid =~ m{^[0-9a-f\-]{30,}$}
1191 or die "doesn't look right - svm:uuid is '$uuid'\n";
1193 # the '!' is used to mark the repos_root!/relative/path
1194 $src =~ s{/?!/?}{/};
1195 $src =~ s{/+$}{}; # no trailing slashes please
1196 # username is of no interest
1197 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1199 my $replace = $ra->{url};
1200 $replace .= "/$path" if length $path;
1202 my $section = "svn-remote.$self->{repo_id}";
1203 tmp_config("$section.svm-source", $src);
1204 tmp_config("$section.svm-replace", $replace);
1205 tmp_config("$section.svm-uuid", $uuid);
1206 $self->{svm} = {
1207 source => $src,
1208 uuid => $uuid,
1209 replace => $replace
1213 my $r = $ra->get_latest_revnum;
1214 my $path = $self->{path};
1215 my %tried;
1216 while (length $path) {
1217 unless ($tried{"$self->{url}/$path"}) {
1218 return $ra if $self->read_svm_props($ra, $path, $r);
1219 $tried{"$self->{url}/$path"} = 1;
1221 $path =~ s#/?[^/]+$##;
1223 die "Path: '$path' should be ''\n" if $path ne '';
1224 return $ra if $self->read_svm_props($ra, $path, $r);
1225 $tried{"$self->{url}/$path"} = 1;
1227 if ($ra->{repos_root} eq $self->{url}) {
1228 die @err, (map { " $_\n" } keys %tried), "\n";
1231 # nope, make sure we're connected to the repository root:
1232 my $ok;
1233 my @tried_b;
1234 $path = $ra->{svn_path};
1235 $ra = Git::SVN::Ra->new($ra->{repos_root});
1236 while (length $path) {
1237 unless ($tried{"$ra->{url}/$path"}) {
1238 $ok = $self->read_svm_props($ra, $path, $r);
1239 last if $ok;
1240 $tried{"$ra->{url}/$path"} = 1;
1242 $path =~ s#/?[^/]+$##;
1244 die "Path: '$path' should be ''\n" if $path ne '';
1245 $ok ||= $self->read_svm_props($ra, $path, $r);
1246 $tried{"$ra->{url}/$path"} = 1;
1247 if (!$ok) {
1248 die @err, (map { " $_\n" } keys %tried), "\n";
1250 Git::SVN::Ra->new($self->{url});
1253 sub svnsync {
1254 my ($self) = @_;
1255 return $self->{svnsync} if $self->{svnsync};
1257 if ($self->no_metadata) {
1258 die "Can't have both 'noMetadata' and ",
1259 "'useSvnsyncProps' options set!\n";
1261 if ($self->rewrite_root) {
1262 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1263 "options set!\n";
1266 my $svnsync;
1267 # see if we have it in our config, first:
1268 eval {
1269 my $section = "svn-remote.$self->{repo_id}";
1270 $svnsync = {
1271 url => tmp_config('--get', "$section.svnsync-url"),
1272 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1275 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1276 return $self->{svnsync} = $svnsync;
1279 my $err = "useSvnsyncProps set, but failed to read " .
1280 "svnsync property: svn:sync-from-";
1281 my $rp = $self->ra->rev_proplist(0);
1283 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1284 $url =~ m{^[a-z\+]+://} or
1285 die "doesn't look right - svn:sync-from-url is '$url'\n";
1287 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1288 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1289 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1291 my $section = "svn-remote.$self->{repo_id}";
1292 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1293 tmp_config('--add', "$section.svnsync-url", $url);
1294 return $self->{svnsync} = { url => $url, uuid => $uuid };
1297 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1298 # remote lookup (useful for 'git svn log').
1299 sub ra_uuid {
1300 my ($self) = @_;
1301 unless ($self->{ra_uuid}) {
1302 my $key = "svn-remote.$self->{repo_id}.uuid";
1303 my $uuid = eval { tmp_config('--get', $key) };
1304 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1305 $self->{ra_uuid} = $uuid;
1306 } else {
1307 die "ra_uuid called without URL\n" unless $self->{url};
1308 $self->{ra_uuid} = $self->ra->get_uuid;
1309 tmp_config('--add', $key, $self->{ra_uuid});
1312 $self->{ra_uuid};
1315 sub ra {
1316 my ($self) = shift;
1317 my $ra = Git::SVN::Ra->new($self->{url});
1318 if ($self->use_svm_props && !$self->{svm}) {
1319 if ($self->no_metadata) {
1320 die "Can't have both 'noMetadata' and ",
1321 "'useSvmProps' options set!\n";
1322 } elsif ($self->use_svnsync_props) {
1323 die "Can't have both 'useSvnsyncProps' and ",
1324 "'useSvmProps' options set!\n";
1326 $ra = $self->_set_svm_vars($ra);
1327 $self->{-want_revprops} = 1;
1329 $ra;
1332 sub rel_path {
1333 my ($self) = @_;
1334 my $repos_root = $self->ra->{repos_root};
1335 return $self->{path} if ($self->{url} eq $repos_root);
1336 my $url = $self->{url} .
1337 (length $self->{path} ? "/$self->{path}" : $self->{path});
1338 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1339 $url;
1342 sub traverse_ignore {
1343 my ($self, $fh, $path, $r) = @_;
1344 $path =~ s#^/+##g;
1345 my $ra = $self->ra;
1346 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1347 my $p = $path;
1348 $p =~ s#^\Q$self->{path}\E(/|$)##;
1349 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1350 if (my $s = $props->{'svn:ignore'}) {
1351 $s =~ s/[\r\n]+/\n/g;
1352 chomp $s;
1353 if (length $p == 0) {
1354 $s =~ s#\n#\n/$p#g;
1355 print $fh "/$s\n";
1356 } else {
1357 $s =~ s#\n#\n/$p/#g;
1358 print $fh "/$p/$s\n";
1361 foreach (sort keys %$dirent) {
1362 next if $dirent->{$_}->kind != $SVN::Node::dir;
1363 $self->traverse_ignore($fh, "$path/$_", $r);
1367 sub last_rev { ($_[0]->last_rev_commit)[0] }
1368 sub last_commit { ($_[0]->last_rev_commit)[1] }
1370 # returns the newest SVN revision number and newest commit SHA1
1371 sub last_rev_commit {
1372 my ($self) = @_;
1373 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1374 return ($self->{last_rev}, $self->{last_commit});
1376 my $c = ::verify_ref($self->refname.'^0');
1377 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1378 my $rev = (::cmt_metadata($c))[1];
1379 if (defined $rev) {
1380 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1381 return ($rev, $c);
1384 my $db_path = $self->db_path;
1385 unless (-e $db_path) {
1386 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1387 return (undef, undef);
1389 my $offset = -41; # from tail
1390 my $rl;
1391 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1392 sysseek($fh, $offset, 2); # don't care for errors
1393 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1394 chomp $rl;
1395 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1396 $offset -= 41;
1397 sysseek($fh, $offset, 2); # don't care for errors
1398 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1399 chomp $rl;
1401 if ($c && $c ne $rl) {
1402 die "$db_path and ", $self->refname,
1403 " inconsistent!:\n$c != $rl\n";
1405 my $rev = sysseek($fh, 0, 1) or croak $!;
1406 $rev = ($rev - 41) / 41;
1407 close $fh or croak $!;
1408 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1409 return ($rev, $c);
1412 sub get_fetch_range {
1413 my ($self, $min, $max) = @_;
1414 $max ||= $self->ra->get_latest_revnum;
1415 $min ||= $self->rev_db_max;
1416 (++$min, $max);
1419 sub tmp_config {
1420 my (@args) = @_;
1421 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1422 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1423 if (-e $old_def_config && ! -e $config) {
1424 rename $old_def_config, $config or
1425 die "Failed rename $old_def_config => $config: $!\n";
1427 my $old_config = $ENV{GIT_CONFIG};
1428 $ENV{GIT_CONFIG} = $config;
1429 $@ = undef;
1430 my @ret = eval {
1431 unless (-f $config) {
1432 mkfile($config);
1433 open my $fh, '>', $config or
1434 die "Can't open $config: $!\n";
1435 print $fh "; This file is used internally by ",
1436 "git-svn\n" or die
1437 "Couldn't write to $config: $!\n";
1438 print $fh "; You should not have to edit it\n" or
1439 die "Couldn't write to $config: $!\n";
1440 close $fh or die "Couldn't close $config: $!\n";
1442 command('config', @args);
1444 my $err = $@;
1445 if (defined $old_config) {
1446 $ENV{GIT_CONFIG} = $old_config;
1447 } else {
1448 delete $ENV{GIT_CONFIG};
1450 die $err if $err;
1451 wantarray ? @ret : $ret[0];
1454 sub tmp_index_do {
1455 my ($self, $sub) = @_;
1456 my $old_index = $ENV{GIT_INDEX_FILE};
1457 $ENV{GIT_INDEX_FILE} = $self->{index};
1458 $@ = undef;
1459 my @ret = eval {
1460 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1461 mkpath([$dir]) unless -d $dir;
1462 &$sub;
1464 my $err = $@;
1465 if (defined $old_index) {
1466 $ENV{GIT_INDEX_FILE} = $old_index;
1467 } else {
1468 delete $ENV{GIT_INDEX_FILE};
1470 die $err if $err;
1471 wantarray ? @ret : $ret[0];
1474 sub assert_index_clean {
1475 my ($self, $treeish) = @_;
1477 $self->tmp_index_do(sub {
1478 command_noisy('read-tree', $treeish) unless -e $self->{index};
1479 my $x = command_oneline('write-tree');
1480 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1481 /^tree ($::sha1)/mo);
1482 return if $y eq $x;
1484 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1485 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1486 command_noisy('read-tree', $treeish);
1487 $x = command_oneline('write-tree');
1488 if ($y ne $x) {
1489 ::fatal "trees ($treeish) $y != $x\n",
1490 "Something is seriously wrong...\n";
1495 sub get_commit_parents {
1496 my ($self, $log_entry) = @_;
1497 my (%seen, @ret, @tmp);
1498 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1499 if (my $ip = $self->{inject_parents}) {
1500 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1501 push @tmp, $commit;
1504 if (my $cur = ::verify_ref($self->refname.'^0')) {
1505 push @tmp, $cur;
1507 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1508 while (my $p = shift @tmp) {
1509 next if $seen{$p};
1510 $seen{$p} = 1;
1511 push @ret, $p;
1512 # MAXPARENT is defined to 16 in commit-tree.c:
1513 last if @ret >= 16;
1515 if (@tmp) {
1516 die "r$log_entry->{revision}: No room for parents:\n\t",
1517 join("\n\t", @tmp), "\n";
1519 @ret;
1522 sub rewrite_root {
1523 my ($self) = @_;
1524 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1525 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1526 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1527 if ($rwr) {
1528 $rwr =~ s#/+$##;
1529 if ($rwr !~ m#^[a-z\+]+://#) {
1530 die "$rwr is not a valid URL (key: $k)\n";
1533 $self->{-rewrite_root} = $rwr;
1536 sub metadata_url {
1537 my ($self) = @_;
1538 ($self->rewrite_root || $self->{url}) .
1539 (length $self->{path} ? '/' . $self->{path} : '');
1542 sub full_url {
1543 my ($self) = @_;
1544 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1547 sub do_git_commit {
1548 my ($self, $log_entry) = @_;
1549 my $lr = $self->last_rev;
1550 if (defined $lr && $lr >= $log_entry->{revision}) {
1551 die "Last fetched revision of ", $self->refname,
1552 " was r$lr, but we are about to fetch: ",
1553 "r$log_entry->{revision}!\n";
1555 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1556 croak "$log_entry->{revision} = $c already exists! ",
1557 "Why are we refetching it?\n";
1559 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1560 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1561 $log_entry->{email};
1562 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1564 my $tree = $log_entry->{tree};
1565 if (!defined $tree) {
1566 $tree = $self->tmp_index_do(sub {
1567 command_oneline('write-tree') });
1569 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1571 my @exec = ('git-commit-tree', $tree);
1572 foreach ($self->get_commit_parents($log_entry)) {
1573 push @exec, '-p', $_;
1575 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1576 or croak $!;
1577 print $msg_fh $log_entry->{log} or croak $!;
1578 unless ($self->no_metadata) {
1579 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1580 or croak $!;
1582 $msg_fh->flush == 0 or croak $!;
1583 close $msg_fh or croak $!;
1584 chomp(my $commit = do { local $/; <$out_fh> });
1585 close $out_fh or croak $!;
1586 waitpid $pid, 0;
1587 croak $? if $?;
1588 if ($commit !~ /^$::sha1$/o) {
1589 die "Failed to commit, invalid sha1: $commit\n";
1592 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1594 $self->{last_rev} = $log_entry->{revision};
1595 $self->{last_commit} = $commit;
1596 print "r$log_entry->{revision}";
1597 if (defined $log_entry->{svm_revision}) {
1598 print " (\@$log_entry->{svm_revision})";
1599 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1600 0, $self->svm_uuid);
1602 print " = $commit ($self->{ref_id})\n";
1603 if (defined $_repack && (--$_repack_nr == 0)) {
1604 $_repack_nr = $_repack;
1605 # repack doesn't use any arguments with spaces in them, does it?
1606 print "Running git repack $_repack_flags ...\n";
1607 command_noisy('repack', split(/\s+/, $_repack_flags));
1608 print "Done repacking\n";
1610 return $commit;
1613 sub match_paths {
1614 my ($self, $paths, $r) = @_;
1615 return 1 if $self->{path} eq '';
1616 if (my $path = $paths->{"/$self->{path}"}) {
1617 return ($path->{action} eq 'D') ? 0 : 1;
1619 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1620 if (grep /$self->{path_regex}/, keys %$paths) {
1621 return 1;
1623 my $c = '';
1624 foreach (split m#/#, $self->{path}) {
1625 $c .= "/$_";
1626 next unless ($paths->{$c} &&
1627 ($paths->{$c}->{action} =~ /^[AR]$/));
1628 if ($self->ra->check_path($self->{path}, $r) ==
1629 $SVN::Node::dir) {
1630 return 1;
1633 return 0;
1636 sub find_parent_branch {
1637 my ($self, $paths, $rev) = @_;
1638 return undef unless $self->follow_parent;
1639 unless (defined $paths) {
1640 my $err_handler = $SVN::Error::handler;
1641 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1642 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1643 $paths =
1644 Git::SVN::Ra::dup_changed_paths($_[0]) });
1645 $SVN::Error::handler = $err_handler;
1647 return undef unless defined $paths;
1649 # look for a parent from another branch:
1650 my @b_path_components = split m#/#, $self->rel_path;
1651 my @a_path_components;
1652 my $i;
1653 while (@b_path_components) {
1654 $i = $paths->{'/'.join('/', @b_path_components)};
1655 last if $i && defined $i->{copyfrom_path};
1656 unshift(@a_path_components, pop(@b_path_components));
1658 return undef unless defined $i && defined $i->{copyfrom_path};
1659 my $branch_from = $i->{copyfrom_path};
1660 if (@a_path_components) {
1661 print STDERR "branch_from: $branch_from => ";
1662 $branch_from .= '/'.join('/', @a_path_components);
1663 print STDERR $branch_from, "\n";
1665 my $r = $i->{copyfrom_rev};
1666 my $repos_root = $self->ra->{repos_root};
1667 my $url = $self->ra->{url};
1668 my $new_url = $repos_root . $branch_from;
1669 print STDERR "Found possible branch point: ",
1670 "$new_url => ", $self->full_url, ", $r\n";
1671 $branch_from =~ s#^/##;
1672 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1673 unless ($gs) {
1674 my $ref_id = $self->{ref_id};
1675 $ref_id =~ s/\@\d+$//;
1676 $ref_id .= "\@$r";
1677 # just grow a tail if we're not unique enough :x
1678 $ref_id .= '-' while find_ref($ref_id);
1679 print STDERR "Initializing parent: $ref_id\n";
1680 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1682 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1683 if (!defined $r0 || !defined $parent) {
1684 $gs->fetch(0, $r);
1685 ($r0, $parent) = $gs->last_rev_commit;
1687 if (defined $r0 && defined $parent) {
1688 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1689 my $ed;
1690 if ($self->ra->can_do_switch) {
1691 $self->assert_index_clean($parent);
1692 print STDERR "Following parent with do_switch\n";
1693 # do_switch works with svn/trunk >= r22312, but that
1694 # is not included with SVN 1.4.3 (the latest version
1695 # at the moment), so we can't rely on it
1696 $self->{last_commit} = $parent;
1697 $ed = SVN::Git::Fetcher->new($self);
1698 $gs->ra->gs_do_switch($r0, $rev, $gs,
1699 $self->full_url, $ed)
1700 or die "SVN connection failed somewhere...\n";
1701 } else {
1702 print STDERR "Following parent with do_update\n";
1703 $ed = SVN::Git::Fetcher->new($self);
1704 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1705 or die "SVN connection failed somewhere...\n";
1707 print STDERR "Successfully followed parent\n";
1708 return $self->make_log_entry($rev, [$parent], $ed);
1710 return undef;
1713 sub do_fetch {
1714 my ($self, $paths, $rev) = @_;
1715 my $ed;
1716 my ($last_rev, @parents);
1717 if (my $lc = $self->last_commit) {
1718 # we can have a branch that was deleted, then re-added
1719 # under the same name but copied from another path, in
1720 # which case we'll have multiple parents (we don't
1721 # want to break the original ref, nor lose copypath info):
1722 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1723 push @{$log_entry->{parents}}, $lc;
1724 return $log_entry;
1726 $ed = SVN::Git::Fetcher->new($self);
1727 $last_rev = $self->{last_rev};
1728 $ed->{c} = $lc;
1729 @parents = ($lc);
1730 } else {
1731 $last_rev = $rev;
1732 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1733 return $log_entry;
1735 $ed = SVN::Git::Fetcher->new($self);
1737 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1738 die "SVN connection failed somewhere...\n";
1740 $self->make_log_entry($rev, \@parents, $ed);
1743 sub get_untracked {
1744 my ($self, $ed) = @_;
1745 my @out;
1746 my $h = $ed->{empty};
1747 foreach (sort keys %$h) {
1748 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1749 push @out, " $act: " . uri_encode($_);
1750 warn "W: $act: $_\n";
1752 foreach my $t (qw/dir_prop file_prop/) {
1753 $h = $ed->{$t} or next;
1754 foreach my $path (sort keys %$h) {
1755 my $ppath = $path eq '' ? '.' : $path;
1756 foreach my $prop (sort keys %{$h->{$path}}) {
1757 next if $SKIP_PROP{$prop};
1758 my $v = $h->{$path}->{$prop};
1759 my $t_ppath_prop = "$t: " .
1760 uri_encode($ppath) . ' ' .
1761 uri_encode($prop);
1762 if (defined $v) {
1763 push @out, " +$t_ppath_prop " .
1764 uri_encode($v);
1765 } else {
1766 push @out, " -$t_ppath_prop";
1771 foreach my $t (qw/absent_file absent_directory/) {
1772 $h = $ed->{$t} or next;
1773 foreach my $parent (sort keys %$h) {
1774 foreach my $path (sort @{$h->{$parent}}) {
1775 push @out, " $t: " .
1776 uri_encode("$parent/$path");
1777 warn "W: $t: $parent/$path ",
1778 "Insufficient permissions?\n";
1782 \@out;
1785 sub parse_svn_date {
1786 my $date = shift || return '+0000 1970-01-01 00:00:00';
1787 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1788 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1789 croak "Unable to parse date: $date\n";
1790 "+0000 $Y-$m-$d $H:$M:$S";
1793 sub check_author {
1794 my ($author) = @_;
1795 if (!defined $author || length $author == 0) {
1796 $author = '(no author)';
1798 if (defined $::_authors && ! defined $::users{$author}) {
1799 die "Author: $author not defined in $::_authors file\n";
1801 $author;
1804 sub make_log_entry {
1805 my ($self, $rev, $parents, $ed) = @_;
1806 my $untracked = $self->get_untracked($ed);
1808 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1809 print $un "r$rev\n" or croak $!;
1810 print $un $_, "\n" foreach @$untracked;
1811 my %log_entry = ( parents => $parents || [], revision => $rev,
1812 log => '');
1814 my $headrev;
1815 my $logged = delete $self->{logged_rev_props};
1816 if (!$logged || $self->{-want_revprops}) {
1817 my $rp = $self->ra->rev_proplist($rev);
1818 foreach (sort keys %$rp) {
1819 my $v = $rp->{$_};
1820 if (/^svn:(author|date|log)$/) {
1821 $log_entry{$1} = $v;
1822 } elsif ($_ eq 'svm:headrev') {
1823 $headrev = $v;
1824 } else {
1825 print $un " rev_prop: ", uri_encode($_), ' ',
1826 uri_encode($v), "\n";
1829 } else {
1830 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1832 close $un or croak $!;
1834 $log_entry{date} = parse_svn_date($log_entry{date});
1835 $log_entry{log} .= "\n";
1836 my $author = $log_entry{author} = check_author($log_entry{author});
1837 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1838 : ($author, undef);
1839 if (defined $headrev && $self->use_svm_props) {
1840 if ($self->rewrite_root) {
1841 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1842 "options set!\n";
1844 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1845 # we don't want "SVM: initializing mirror for junk" ...
1846 return undef if $r == 0;
1847 my $svm = $self->svm;
1848 if ($uuid ne $svm->{uuid}) {
1849 die "UUID mismatch on SVM path:\n",
1850 "expected: $svm->{uuid}\n",
1851 " got: $uuid\n";
1853 my $full_url = $self->full_url;
1854 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1855 die "Failed to replace '$svm->{replace}' with ",
1856 "'$svm->{source}' in $full_url\n";
1857 # throw away username for storing in records
1858 remove_username($full_url);
1859 $log_entry{metadata} = "$full_url\@$r $uuid";
1860 $log_entry{svm_revision} = $r;
1861 $email ||= "$author\@$uuid"
1862 } elsif ($self->use_svnsync_props) {
1863 my $full_url = $self->svnsync->{url};
1864 $full_url .= "/$self->{path}" if length $self->{path};
1865 my $uuid = $self->svnsync->{uuid};
1866 $log_entry{metadata} = "$full_url\@$rev $uuid";
1867 $email ||= "$author\@$uuid"
1868 } else {
1869 $log_entry{metadata} = $self->metadata_url. "\@$rev " .
1870 $self->ra->get_uuid;
1871 $email ||= "$author\@" . $self->ra->get_uuid;
1873 $log_entry{name} = $name;
1874 $log_entry{email} = $email;
1875 \%log_entry;
1878 sub fetch {
1879 my ($self, $min_rev, $max_rev, @parents) = @_;
1880 my ($last_rev, $last_commit) = $self->last_rev_commit;
1881 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1882 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1885 sub set_tree_cb {
1886 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1887 $self->{inject_parents} = { $rev => $tree };
1888 $self->fetch(undef, undef);
1891 sub set_tree {
1892 my ($self, $tree) = (shift, shift);
1893 my $log_entry = ::get_commit_entry($tree);
1894 unless ($self->{last_rev}) {
1895 fatal("Must have an existing revision to commit\n");
1897 my %ed_opts = ( r => $self->{last_rev},
1898 log => $log_entry->{log},
1899 ra => $self->ra,
1900 tree_a => $self->{last_commit},
1901 tree_b => $tree,
1902 editor_cb => sub {
1903 $self->set_tree_cb($log_entry, $tree, @_) },
1904 svn_path => $self->{path} );
1905 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1906 print "No changes\nr$self->{last_rev} = $tree\n";
1910 sub rebuild {
1911 my ($self) = @_;
1912 my $db_path = $self->db_path;
1913 return if (-e $db_path && ! -z $db_path);
1914 return unless ::verify_ref($self->refname.'^0');
1915 if (-f $self->{db_root}) {
1916 rename $self->{db_root}, $db_path or die
1917 "rename $self->{db_root} => $db_path failed: $!\n";
1918 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1919 symlink $base, $self->{db_root} or die
1920 "symlink $base => $self->{db_root} failed: $!\n";
1921 return;
1923 print "Rebuilding $db_path ...\n";
1924 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1925 my $latest;
1926 my $full_url = $self->full_url;
1927 remove_username($full_url);
1928 my $svn_uuid;
1929 while (<$rev_list>) {
1930 chomp;
1931 my $c = $_;
1932 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1933 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1934 remove_username($url);
1936 # ignore merges (from set-tree)
1937 next if (!defined $rev || !$uuid);
1939 # if we merged or otherwise started elsewhere, this is
1940 # how we break out of it
1941 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1942 ($full_url && $url && ($url ne $full_url))) {
1943 next;
1945 $latest ||= $rev;
1946 $svn_uuid ||= $uuid;
1948 $self->rev_db_set($rev, $c);
1949 print "r$rev = $c\n";
1951 command_close_pipe($rev_list, $ctx);
1952 print "Done rebuilding $db_path\n";
1955 # rev_db:
1956 # Tie::File seems to be prone to offset errors if revisions get sparse,
1957 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1958 # one of my favorite modules is out :< Next up would be one of the DBM
1959 # modules, but I'm not sure which is most portable... So I'll just
1960 # go with something that's plain-text, but still capable of
1961 # being randomly accessed. So here's my ultra-simple fixed-width
1962 # database. All records are 40 characters + "\n", so it's easy to seek
1963 # to a revision: (41 * rev) is the byte offset.
1964 # A record of 40 0s denotes an empty revision.
1965 # And yes, it's still pretty fast (faster than Tie::File).
1966 # These files are disposable unless noMetadata or useSvmProps is set
1968 sub _rev_db_set {
1969 my ($fh, $rev, $commit) = @_;
1970 my $offset = $rev * 41;
1971 # assume that append is the common case:
1972 seek $fh, 0, 2 or croak $!;
1973 my $pos = tell $fh;
1974 if ($pos < $offset) {
1975 for (1 .. (($offset - $pos) / 41)) {
1976 print $fh (('0' x 40),"\n") or croak $!;
1979 seek $fh, $offset, 0 or croak $!;
1980 print $fh $commit,"\n" or croak $!;
1983 sub mkfile {
1984 my ($path) = @_;
1985 unless (-e $path) {
1986 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1987 mkpath([$dir]) unless -d $dir;
1988 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1989 close $fh or die "Couldn't close (create) $path: $!\n";
1993 sub rev_db_set {
1994 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1995 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1996 my $db = $self->db_path($uuid);
1997 my $db_lock = "$db.lock";
1998 my $sig;
1999 if ($update_ref) {
2000 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2001 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2003 mkfile($db);
2005 $LOCKFILES{$db_lock} = 1;
2006 my $sync;
2007 # both of these options make our .rev_db file very, very important
2008 # and we can't afford to lose it because rebuild() won't work
2009 if ($self->use_svm_props || $self->no_metadata) {
2010 $sync = 1;
2011 copy($db, $db_lock) or die "rev_db_set(@_): ",
2012 "Failed to copy: ",
2013 "$db => $db_lock ($!)\n";
2014 } else {
2015 rename $db, $db_lock or die "rev_db_set(@_): ",
2016 "Failed to rename: ",
2017 "$db => $db_lock ($!)\n";
2019 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2020 _rev_db_set($fh, $rev, $commit);
2021 if ($sync) {
2022 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2023 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2025 close $fh or croak $!;
2026 if ($update_ref) {
2027 $_head = $self;
2028 command_noisy('update-ref', '-m', "r$rev",
2029 $self->refname, $commit);
2031 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2032 "$db_lock => $db ($!)\n";
2033 delete $LOCKFILES{$db_lock};
2034 if ($update_ref) {
2035 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2036 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2037 kill $sig, $$ if defined $sig;
2041 sub rev_db_max {
2042 my ($self) = @_;
2043 $self->rebuild;
2044 my $db_path = $self->db_path;
2045 my @stat = stat $db_path or return 0;
2046 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2047 my $max = $stat[7] / 41;
2048 (($max > 0) ? $max - 1 : 0);
2051 sub rev_db_get {
2052 my ($self, $rev, $uuid) = @_;
2053 my $ret;
2054 my $offset = $rev * 41;
2055 my $db_path = $self->db_path($uuid);
2056 return undef unless -e $db_path;
2057 open my $fh, '<', $db_path or croak $!;
2058 if (sysseek($fh, $offset, 0) == $offset) {
2059 my $read = sysread($fh, $ret, 40);
2060 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2062 close $fh or croak $!;
2063 $ret;
2066 sub find_rev_before {
2067 my ($self, $rev, $eq_ok) = @_;
2068 --$rev unless $eq_ok;
2069 while ($rev > 0) {
2070 if (my $c = $self->rev_db_get($rev)) {
2071 return ($rev, $c);
2073 --$rev;
2075 return (undef, undef);
2078 sub _new {
2079 my ($class, $repo_id, $ref_id, $path) = @_;
2080 unless (defined $repo_id && length $repo_id) {
2081 $repo_id = $Git::SVN::default_repo_id;
2083 unless (defined $ref_id && length $ref_id) {
2084 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2086 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2087 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2088 $_[3] = $path = '' unless (defined $path);
2089 mkpath(["$ENV{GIT_DIR}/svn"]);
2090 bless {
2091 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2092 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2093 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2096 sub db_path {
2097 my ($self, $uuid) = @_;
2098 $uuid ||= $self->ra_uuid;
2099 "$self->{db_root}.$uuid";
2102 sub uri_encode {
2103 my ($f) = @_;
2104 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2108 sub remove_username {
2109 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2112 package Git::SVN::Prompt;
2113 use strict;
2114 use warnings;
2115 require SVN::Core;
2116 use vars qw/$_no_auth_cache $_username/;
2118 sub simple {
2119 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2120 $may_save = undef if $_no_auth_cache;
2121 $default_username = $_username if defined $_username;
2122 if (defined $default_username && length $default_username) {
2123 if (defined $realm && length $realm) {
2124 print STDERR "Authentication realm: $realm\n";
2125 STDERR->flush;
2127 $cred->username($default_username);
2128 } else {
2129 username($cred, $realm, $may_save, $pool);
2131 $cred->password(_read_password("Password for '" .
2132 $cred->username . "': ", $realm));
2133 $cred->may_save($may_save);
2134 $SVN::_Core::SVN_NO_ERROR;
2137 sub ssl_server_trust {
2138 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2139 $may_save = undef if $_no_auth_cache;
2140 print STDERR "Error validating server certificate for '$realm':\n";
2141 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2142 print STDERR " - The certificate is not issued by a trusted ",
2143 "authority. Use the\n",
2144 " fingerprint to validate the certificate manually!\n";
2146 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2147 print STDERR " - The certificate hostname does not match.\n";
2149 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2150 print STDERR " - The certificate is not yet valid.\n";
2152 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2153 print STDERR " - The certificate has expired.\n";
2155 if ($failures & $SVN::Auth::SSL::OTHER) {
2156 print STDERR " - The certificate has an unknown error.\n";
2158 printf STDERR
2159 "Certificate information:\n".
2160 " - Hostname: %s\n".
2161 " - Valid: from %s until %s\n".
2162 " - Issuer: %s\n".
2163 " - Fingerprint: %s\n",
2164 map $cert_info->$_, qw(hostname valid_from valid_until
2165 issuer_dname fingerprint);
2166 my $choice;
2167 prompt:
2168 print STDERR $may_save ?
2169 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2170 "(R)eject or accept (t)emporarily? ";
2171 STDERR->flush;
2172 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2173 if ($choice =~ /^t$/i) {
2174 $cred->may_save(undef);
2175 } elsif ($choice =~ /^r$/i) {
2176 return -1;
2177 } elsif ($may_save && $choice =~ /^p$/i) {
2178 $cred->may_save($may_save);
2179 } else {
2180 goto prompt;
2182 $cred->accepted_failures($failures);
2183 $SVN::_Core::SVN_NO_ERROR;
2186 sub ssl_client_cert {
2187 my ($cred, $realm, $may_save, $pool) = @_;
2188 $may_save = undef if $_no_auth_cache;
2189 print STDERR "Client certificate filename: ";
2190 STDERR->flush;
2191 chomp(my $filename = <STDIN>);
2192 $cred->cert_file($filename);
2193 $cred->may_save($may_save);
2194 $SVN::_Core::SVN_NO_ERROR;
2197 sub ssl_client_cert_pw {
2198 my ($cred, $realm, $may_save, $pool) = @_;
2199 $may_save = undef if $_no_auth_cache;
2200 $cred->password(_read_password("Password: ", $realm));
2201 $cred->may_save($may_save);
2202 $SVN::_Core::SVN_NO_ERROR;
2205 sub username {
2206 my ($cred, $realm, $may_save, $pool) = @_;
2207 $may_save = undef if $_no_auth_cache;
2208 if (defined $realm && length $realm) {
2209 print STDERR "Authentication realm: $realm\n";
2211 my $username;
2212 if (defined $_username) {
2213 $username = $_username;
2214 } else {
2215 print STDERR "Username: ";
2216 STDERR->flush;
2217 chomp($username = <STDIN>);
2219 $cred->username($username);
2220 $cred->may_save($may_save);
2221 $SVN::_Core::SVN_NO_ERROR;
2224 sub _read_password {
2225 my ($prompt, $realm) = @_;
2226 print STDERR $prompt;
2227 STDERR->flush;
2228 require Term::ReadKey;
2229 Term::ReadKey::ReadMode('noecho');
2230 my $password = '';
2231 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2232 last if $key =~ /[\012\015]/; # \n\r
2233 $password .= $key;
2235 Term::ReadKey::ReadMode('restore');
2236 print STDERR "\n";
2237 STDERR->flush;
2238 $password;
2241 package main;
2244 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2245 $SVN::Node::dir.$SVN::Node::unknown.
2246 $SVN::Node::none.$SVN::Node::file.
2247 $SVN::Node::dir.$SVN::Node::unknown.
2248 $SVN::Auth::SSL::CNMISMATCH.
2249 $SVN::Auth::SSL::NOTYETVALID.
2250 $SVN::Auth::SSL::EXPIRED.
2251 $SVN::Auth::SSL::UNKNOWNCA.
2252 $SVN::Auth::SSL::OTHER;
2255 package SVN::Git::Fetcher;
2256 use vars qw/@ISA/;
2257 use strict;
2258 use warnings;
2259 use Carp qw/croak/;
2260 use IO::File qw//;
2261 use Digest::MD5;
2263 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2264 sub new {
2265 my ($class, $git_svn) = @_;
2266 my $self = SVN::Delta::Editor->new;
2267 bless $self, $class;
2268 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2269 $self->{empty} = {};
2270 $self->{dir_prop} = {};
2271 $self->{file_prop} = {};
2272 $self->{absent_dir} = {};
2273 $self->{absent_file} = {};
2274 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2275 $self;
2278 sub set_path_strip {
2279 my ($self, $path) = @_;
2280 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2283 sub open_root {
2284 { path => '' };
2287 sub open_directory {
2288 my ($self, $path, $pb, $rev) = @_;
2289 { path => $path };
2292 sub git_path {
2293 my ($self, $path) = @_;
2294 if ($self->{path_strip}) {
2295 $path =~ s!$self->{path_strip}!! or
2296 die "Failed to strip path '$path' ($self->{path_strip})\n";
2298 $path;
2301 sub delete_entry {
2302 my ($self, $path, $rev, $pb) = @_;
2304 my $gpath = $self->git_path($path);
2305 return undef if ($gpath eq '');
2307 # remove entire directories.
2308 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2309 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2310 -r --name-only -z/,
2311 $self->{c}, '--', $gpath);
2312 local $/ = "\0";
2313 while (<$ls>) {
2314 chomp;
2315 $self->{gii}->remove($_);
2316 print "\tD\t$_\n" unless $::_q;
2318 print "\tD\t$gpath/\n" unless $::_q;
2319 command_close_pipe($ls, $ctx);
2320 $self->{empty}->{$path} = 0
2321 } else {
2322 $self->{gii}->remove($gpath);
2323 print "\tD\t$gpath\n" unless $::_q;
2325 undef;
2328 sub open_file {
2329 my ($self, $path, $pb, $rev) = @_;
2330 my $gpath = $self->git_path($path);
2331 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2332 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2333 unless (defined $mode && defined $blob) {
2334 die "$path was not found in commit $self->{c} (r$rev)\n";
2336 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2337 pool => SVN::Pool->new, action => 'M' };
2340 sub add_file {
2341 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2342 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2343 delete $self->{empty}->{$dir};
2344 { path => $path, mode_a => 100644, mode_b => 100644,
2345 pool => SVN::Pool->new, action => 'A' };
2348 sub add_directory {
2349 my ($self, $path, $cp_path, $cp_rev) = @_;
2350 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2351 delete $self->{empty}->{$dir};
2352 $self->{empty}->{$path} = 1;
2353 { path => $path };
2356 sub change_dir_prop {
2357 my ($self, $db, $prop, $value) = @_;
2358 $self->{dir_prop}->{$db->{path}} ||= {};
2359 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2360 undef;
2363 sub absent_directory {
2364 my ($self, $path, $pb) = @_;
2365 $self->{absent_dir}->{$pb->{path}} ||= [];
2366 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2367 undef;
2370 sub absent_file {
2371 my ($self, $path, $pb) = @_;
2372 $self->{absent_file}->{$pb->{path}} ||= [];
2373 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2374 undef;
2377 sub change_file_prop {
2378 my ($self, $fb, $prop, $value) = @_;
2379 if ($prop eq 'svn:executable') {
2380 if ($fb->{mode_b} != 120000) {
2381 $fb->{mode_b} = defined $value ? 100755 : 100644;
2383 } elsif ($prop eq 'svn:special') {
2384 $fb->{mode_b} = defined $value ? 120000 : 100644;
2385 } else {
2386 $self->{file_prop}->{$fb->{path}} ||= {};
2387 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2389 undef;
2392 sub apply_textdelta {
2393 my ($self, $fb, $exp) = @_;
2394 my $fh = IO::File->new_tmpfile;
2395 $fh->autoflush(1);
2396 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2397 # (but $base does not,) so dup() it for reading in close_file
2398 open my $dup, '<&', $fh or croak $!;
2399 my $base = IO::File->new_tmpfile;
2400 $base->autoflush(1);
2401 if ($fb->{blob}) {
2402 defined (my $pid = fork) or croak $!;
2403 if (!$pid) {
2404 open STDOUT, '>&', $base or croak $!;
2405 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2406 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2408 waitpid $pid, 0;
2409 croak $? if $?;
2411 if (defined $exp) {
2412 seek $base, 0, 0 or croak $!;
2413 my $md5 = Digest::MD5->new;
2414 $md5->addfile($base);
2415 my $got = $md5->hexdigest;
2416 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2417 "expected: $exp\n",
2418 " got: $got\n" if ($got ne $exp);
2421 seek $base, 0, 0 or croak $!;
2422 $fb->{fh} = $dup;
2423 $fb->{base} = $base;
2424 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2427 sub close_file {
2428 my ($self, $fb, $exp) = @_;
2429 my $hash;
2430 my $path = $self->git_path($fb->{path});
2431 if (my $fh = $fb->{fh}) {
2432 seek($fh, 0, 0) or croak $!;
2433 my $md5 = Digest::MD5->new;
2434 $md5->addfile($fh);
2435 my $got = $md5->hexdigest;
2436 die "Checksum mismatch: $path\n",
2437 "expected: $exp\n got: $got\n" if ($got ne $exp);
2438 seek($fh, 0, 0) or croak $!;
2439 if ($fb->{mode_b} == 120000) {
2440 read($fh, my $buf, 5) == 5 or croak $!;
2441 $buf eq 'link ' or die "$path has mode 120000",
2442 "but is not a link\n";
2444 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2445 if (!$pid) {
2446 open STDIN, '<&', $fh or croak $!;
2447 exec qw/git-hash-object -w --stdin/ or croak $!;
2449 chomp($hash = do { local $/; <$out> });
2450 close $out or croak $!;
2451 close $fh or croak $!;
2452 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2453 close $fb->{base} or croak $!;
2454 } else {
2455 $hash = $fb->{blob} or die "no blob information\n";
2457 $fb->{pool}->clear;
2458 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2459 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2460 undef;
2463 sub abort_edit {
2464 my $self = shift;
2465 $self->{nr} = $self->{gii}->{nr};
2466 delete $self->{gii};
2467 $self->SUPER::abort_edit(@_);
2470 sub close_edit {
2471 my $self = shift;
2472 $self->{git_commit_ok} = 1;
2473 $self->{nr} = $self->{gii}->{nr};
2474 delete $self->{gii};
2475 $self->SUPER::close_edit(@_);
2478 package SVN::Git::Editor;
2479 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2480 use strict;
2481 use warnings;
2482 use Carp qw/croak/;
2483 use IO::File;
2484 use Digest::MD5;
2486 sub new {
2487 my ($class, $opts) = @_;
2488 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2489 die "$_ required!\n" unless (defined $opts->{$_});
2492 my $pool = SVN::Pool->new;
2493 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2494 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2495 $opts->{r}, $mods);
2497 # $opts->{ra} functions should not be used after this:
2498 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2499 $opts->{editor_cb}, $pool);
2500 my $self = SVN::Delta::Editor->new(@ce, $pool);
2501 bless $self, $class;
2502 foreach (qw/svn_path r tree_a tree_b/) {
2503 $self->{$_} = $opts->{$_};
2505 $self->{url} = $opts->{ra}->{url};
2506 $self->{mods} = $mods;
2507 $self->{types} = $types;
2508 $self->{pool} = $pool;
2509 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2510 $self->{rm} = { };
2511 $self->{path_prefix} = length $self->{svn_path} ?
2512 "$self->{svn_path}/" : '';
2513 return $self;
2516 sub generate_diff {
2517 my ($tree_a, $tree_b) = @_;
2518 my @diff_tree = qw(diff-tree -z -r);
2519 if ($_cp_similarity) {
2520 push @diff_tree, "-C$_cp_similarity";
2521 } else {
2522 push @diff_tree, '-C';
2524 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2525 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2526 push @diff_tree, $tree_a, $tree_b;
2527 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2528 local $/ = "\0";
2529 my $state = 'meta';
2530 my @mods;
2531 while (<$diff_fh>) {
2532 chomp $_; # this gets rid of the trailing "\0"
2533 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2534 $::sha1\s($::sha1)\s
2535 ([MTCRAD])\d*$/xo) {
2536 push @mods, { mode_a => $1, mode_b => $2,
2537 sha1_b => $3, chg => $4 };
2538 if ($4 =~ /^(?:C|R)$/) {
2539 $state = 'file_a';
2540 } else {
2541 $state = 'file_b';
2543 } elsif ($state eq 'file_a') {
2544 my $x = $mods[$#mods] or croak "Empty array\n";
2545 if ($x->{chg} !~ /^(?:C|R)$/) {
2546 croak "Error parsing $_, $x->{chg}\n";
2548 $x->{file_a} = $_;
2549 $state = 'file_b';
2550 } elsif ($state eq 'file_b') {
2551 my $x = $mods[$#mods] or croak "Empty array\n";
2552 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2553 croak "Error parsing $_, $x->{chg}\n";
2555 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2556 croak "Error parsing $_, $x->{chg}\n";
2558 $x->{file_b} = $_;
2559 $state = 'meta';
2560 } else {
2561 croak "Error parsing $_\n";
2564 command_close_pipe($diff_fh, $ctx);
2565 \@mods;
2568 sub check_diff_paths {
2569 my ($ra, $pfx, $rev, $mods) = @_;
2570 my %types;
2571 $pfx .= '/' if length $pfx;
2573 sub type_diff_paths {
2574 my ($ra, $types, $path, $rev) = @_;
2575 my @p = split m#/+#, $path;
2576 my $c = shift @p;
2577 unless (defined $types->{$c}) {
2578 $types->{$c} = $ra->check_path($c, $rev);
2580 while (@p) {
2581 $c .= '/' . shift @p;
2582 next if defined $types->{$c};
2583 $types->{$c} = $ra->check_path($c, $rev);
2587 foreach my $m (@$mods) {
2588 foreach my $f (qw/file_a file_b/) {
2589 next unless defined $m->{$f};
2590 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2591 if (length $pfx.$dir && ! defined $types{$dir}) {
2592 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2596 \%types;
2599 sub split_path {
2600 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2603 sub repo_path {
2604 my ($self, $path) = @_;
2605 $self->{path_prefix}.(defined $path ? $path : '');
2608 sub url_path {
2609 my ($self, $path) = @_;
2610 $self->{url} . '/' . $self->repo_path($path);
2613 sub rmdirs {
2614 my ($self) = @_;
2615 my $rm = $self->{rm};
2616 delete $rm->{''}; # we never delete the url we're tracking
2617 return unless %$rm;
2619 foreach (keys %$rm) {
2620 my @d = split m#/#, $_;
2621 my $c = shift @d;
2622 $rm->{$c} = 1;
2623 while (@d) {
2624 $c .= '/' . shift @d;
2625 $rm->{$c} = 1;
2628 delete $rm->{$self->{svn_path}};
2629 delete $rm->{''}; # we never delete the url we're tracking
2630 return unless %$rm;
2632 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2633 $self->{tree_b});
2634 local $/ = "\0";
2635 while (<$fh>) {
2636 chomp;
2637 my @dn = split m#/#, $_;
2638 while (pop @dn) {
2639 delete $rm->{join '/', @dn};
2641 unless (%$rm) {
2642 close $fh;
2643 return;
2646 command_close_pipe($fh, $ctx);
2648 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2649 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2650 $self->close_directory($bat->{$d}, $p);
2651 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2652 print "\tD+\t$d/\n" unless $::_q;
2653 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2654 delete $bat->{$d};
2658 sub open_or_add_dir {
2659 my ($self, $full_path, $baton) = @_;
2660 my $t = $self->{types}->{$full_path};
2661 if (!defined $t) {
2662 die "$full_path not known in r$self->{r} or we have a bug!\n";
2664 if ($t == $SVN::Node::none) {
2665 return $self->add_directory($full_path, $baton,
2666 undef, -1, $self->{pool});
2667 } elsif ($t == $SVN::Node::dir) {
2668 return $self->open_directory($full_path, $baton,
2669 $self->{r}, $self->{pool});
2671 print STDERR "$full_path already exists in repository at ",
2672 "r$self->{r} and it is not a directory (",
2673 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2674 exit 1;
2677 sub ensure_path {
2678 my ($self, $path) = @_;
2679 my $bat = $self->{bat};
2680 my $repo_path = $self->repo_path($path);
2681 return $bat->{''} unless (length $repo_path);
2682 my @p = split m#/+#, $repo_path;
2683 my $c = shift @p;
2684 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2685 while (@p) {
2686 my $c0 = $c;
2687 $c .= '/' . shift @p;
2688 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2690 return $bat->{$c};
2693 sub A {
2694 my ($self, $m) = @_;
2695 my ($dir, $file) = split_path($m->{file_b});
2696 my $pbat = $self->ensure_path($dir);
2697 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2698 undef, -1);
2699 print "\tA\t$m->{file_b}\n" unless $::_q;
2700 $self->chg_file($fbat, $m);
2701 $self->close_file($fbat,undef,$self->{pool});
2704 sub C {
2705 my ($self, $m) = @_;
2706 my ($dir, $file) = split_path($m->{file_b});
2707 my $pbat = $self->ensure_path($dir);
2708 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2709 $self->url_path($m->{file_a}), $self->{r});
2710 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2711 $self->chg_file($fbat, $m);
2712 $self->close_file($fbat,undef,$self->{pool});
2715 sub delete_entry {
2716 my ($self, $path, $pbat) = @_;
2717 my $rpath = $self->repo_path($path);
2718 my ($dir, $file) = split_path($rpath);
2719 $self->{rm}->{$dir} = 1;
2720 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2723 sub R {
2724 my ($self, $m) = @_;
2725 my ($dir, $file) = split_path($m->{file_b});
2726 my $pbat = $self->ensure_path($dir);
2727 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2728 $self->url_path($m->{file_a}), $self->{r});
2729 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2730 $self->chg_file($fbat, $m);
2731 $self->close_file($fbat,undef,$self->{pool});
2733 ($dir, $file) = split_path($m->{file_a});
2734 $pbat = $self->ensure_path($dir);
2735 $self->delete_entry($m->{file_a}, $pbat);
2738 sub M {
2739 my ($self, $m) = @_;
2740 my ($dir, $file) = split_path($m->{file_b});
2741 my $pbat = $self->ensure_path($dir);
2742 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2743 $pbat,$self->{r},$self->{pool});
2744 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2745 $self->chg_file($fbat, $m);
2746 $self->close_file($fbat,undef,$self->{pool});
2749 sub T { shift->M(@_) }
2751 sub change_file_prop {
2752 my ($self, $fbat, $pname, $pval) = @_;
2753 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2756 sub chg_file {
2757 my ($self, $fbat, $m) = @_;
2758 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2759 $self->change_file_prop($fbat,'svn:executable','*');
2760 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2761 $self->change_file_prop($fbat,'svn:executable',undef);
2763 my $fh = IO::File->new_tmpfile or croak $!;
2764 if ($m->{mode_b} =~ /^120/) {
2765 print $fh 'link ' or croak $!;
2766 $self->change_file_prop($fbat,'svn:special','*');
2767 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2768 $self->change_file_prop($fbat,'svn:special',undef);
2770 defined(my $pid = fork) or croak $!;
2771 if (!$pid) {
2772 open STDOUT, '>&', $fh or croak $!;
2773 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2775 waitpid $pid, 0;
2776 croak $? if $?;
2777 $fh->flush == 0 or croak $!;
2778 seek $fh, 0, 0 or croak $!;
2780 my $md5 = Digest::MD5->new;
2781 $md5->addfile($fh) or croak $!;
2782 seek $fh, 0, 0 or croak $!;
2784 my $exp = $md5->hexdigest;
2785 my $pool = SVN::Pool->new;
2786 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2787 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2788 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2789 $pool->clear;
2791 close $fh or croak $!;
2794 sub D {
2795 my ($self, $m) = @_;
2796 my ($dir, $file) = split_path($m->{file_b});
2797 my $pbat = $self->ensure_path($dir);
2798 print "\tD\t$m->{file_b}\n" unless $::_q;
2799 $self->delete_entry($m->{file_b}, $pbat);
2802 sub close_edit {
2803 my ($self) = @_;
2804 my ($p,$bat) = ($self->{pool}, $self->{bat});
2805 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2806 $self->close_directory($bat->{$_}, $p);
2808 $self->SUPER::close_edit($p);
2809 $p->clear;
2812 sub abort_edit {
2813 my ($self) = @_;
2814 $self->SUPER::abort_edit($self->{pool});
2817 sub DESTROY {
2818 my $self = shift;
2819 $self->SUPER::DESTROY(@_);
2820 $self->{pool}->clear;
2823 # this drives the editor
2824 sub apply_diff {
2825 my ($self) = @_;
2826 my $mods = $self->{mods};
2827 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2828 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2829 my $f = $m->{chg};
2830 if (defined $o{$f}) {
2831 $self->$f($m);
2832 } else {
2833 fatal("Invalid change type: $f\n");
2836 $self->rmdirs if $_rmdir;
2837 if (@$mods == 0) {
2838 $self->abort_edit;
2839 } else {
2840 $self->close_edit;
2842 return scalar @$mods;
2845 package Git::SVN::Ra;
2846 use vars qw/@ISA $config_dir $_log_window_size/;
2847 use strict;
2848 use warnings;
2849 my ($can_do_switch, %ignored_err, $RA);
2851 BEGIN {
2852 # enforce temporary pool usage for some simple functions
2853 my $e;
2854 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2855 $e .= "sub $_ {
2856 my \$self = shift;
2857 my \$pool = SVN::Pool->new;
2858 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2859 \$pool->clear;
2860 wantarray ? \@ret : \$ret[0]; }\n";
2863 # get_dir needs $pool held in cache for dirents to work,
2864 # check_path is cacheable and rev_proplist is close enough
2865 # for our purposes.
2866 foreach (qw/check_path get_dir rev_proplist/) {
2867 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2868 my \$self = shift;
2869 my \$r = pop;
2870 my \$k = join(\"\\0\", \@_);
2871 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2872 return wantarray ? \@\$x : \$x->[0];
2874 my \$pool = SVN::Pool->new;
2875 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2876 if (\$r != \$${_}_rev) {
2877 \%${_}_cache = ( pool => [] );
2878 \$${_}_rev = \$r;
2880 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2881 push \@{\$${_}_cache{pool}}, \$pool;
2882 wantarray ? \@ret : \$ret[0]; }\n";
2884 $e .= "\n1;";
2885 eval $e or die $@;
2888 sub new {
2889 my ($class, $url) = @_;
2890 $url =~ s!/+$!!;
2891 return $RA if ($RA && $RA->{url} eq $url);
2892 $RA->{pool}->clear if $RA;
2894 SVN::_Core::svn_config_ensure($config_dir, undef);
2895 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2896 SVN::Client::get_simple_provider(),
2897 SVN::Client::get_ssl_server_trust_file_provider(),
2898 SVN::Client::get_simple_prompt_provider(
2899 \&Git::SVN::Prompt::simple, 2),
2900 SVN::Client::get_ssl_client_cert_prompt_provider(
2901 \&Git::SVN::Prompt::ssl_client_cert, 2),
2902 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2903 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2904 SVN::Client::get_username_provider(),
2905 SVN::Client::get_ssl_server_trust_prompt_provider(
2906 \&Git::SVN::Prompt::ssl_server_trust),
2907 SVN::Client::get_username_prompt_provider(
2908 \&Git::SVN::Prompt::username, 2),
2910 my $config = SVN::Core::config_get_config($config_dir);
2911 my $self = SVN::Ra->new(url => $url, auth => $baton,
2912 config => $config,
2913 pool => SVN::Pool->new,
2914 auth_provider_callbacks => $callbacks);
2915 $self->{svn_path} = $url;
2916 $self->{repos_root} = $self->get_repos_root;
2917 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2918 $RA = bless $self, $class;
2921 sub DESTROY {
2922 # do not call the real DESTROY since we store ourselves in $RA
2925 sub get_log {
2926 my ($self, @args) = @_;
2927 my $pool = SVN::Pool->new;
2928 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2929 my $ret = $self->SUPER::get_log(@args, $pool);
2930 $pool->clear;
2931 $ret;
2934 sub get_commit_editor {
2935 my ($self, $log, $cb, $pool) = @_;
2936 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2937 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2940 sub gs_do_update {
2941 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2942 my $new = ($rev_a == $rev_b);
2943 my $path = $gs->{path};
2945 if ($new && -e $gs->{index}) {
2946 unlink $gs->{index} or die
2947 "Couldn't unlink index: $gs->{index}: $!\n";
2949 my $pool = SVN::Pool->new;
2950 $editor->set_path_strip($path);
2951 my (@pc) = split m#/#, $path;
2952 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2953 1, $editor, $pool);
2954 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2956 # Since we can't rely on svn_ra_reparent being available, we'll
2957 # just have to do some magic with set_path to make it so
2958 # we only want a partial path.
2959 my $sp = '';
2960 my $final = join('/', @pc);
2961 while (@pc) {
2962 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2963 $sp .= '/' if length $sp;
2964 $sp .= shift @pc;
2966 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2968 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2970 $reporter->finish_report($pool);
2971 $pool->clear;
2972 $editor->{git_commit_ok};
2975 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2976 # svn_ra_reparent didn't work before 1.4)
2977 sub gs_do_switch {
2978 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2979 my $path = $gs->{path};
2980 my $pool = SVN::Pool->new;
2982 my $full_url = $self->{url};
2983 my $old_url = $full_url;
2984 $full_url .= "/$path" if length $path;
2985 my ($ra, $reparented);
2986 if ($old_url ne $full_url) {
2987 if ($old_url !~ m#^svn(\+ssh)?://#) {
2988 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2989 $pool);
2990 $self->{url} = $full_url;
2991 $reparented = 1;
2992 } else {
2993 $ra = Git::SVN::Ra->new($full_url);
2996 $ra ||= $self;
2997 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2998 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2999 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3000 $reporter->finish_report($pool);
3002 if ($reparented) {
3003 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3004 $self->{url} = $old_url;
3007 $pool->clear;
3008 $editor->{git_commit_ok};
3011 sub gs_fetch_loop_common {
3012 my ($self, $base, $head, $gsv, $globs) = @_;
3013 return if ($base > $head);
3014 my $inc = $_log_window_size;
3015 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3016 my %common;
3017 my $common_max = scalar @$gsv;
3019 foreach my $gs (@$gsv) {
3020 my @tmp = split m#/#, $gs->{path};
3021 my $p = '';
3022 foreach (@tmp) {
3023 $p .= length($p) ? "/$_" : $_;
3024 $common{$p} ||= 0;
3025 $common{$p}++;
3028 $globs ||= [];
3029 $common_max += scalar @$globs;
3030 foreach my $glob (@$globs) {
3031 my @tmp = split m#/#, $glob->{path}->{left};
3032 my $p = '';
3033 foreach (@tmp) {
3034 $p .= length($p) ? "/$_" : $_;
3035 $common{$p} ||= 0;
3036 $common{$p}++;
3040 my $longest_path = '';
3041 foreach (sort {length $b <=> length $a} keys %common) {
3042 if ($common{$_} == $common_max) {
3043 $longest_path = $_;
3044 last;
3047 while (1) {
3048 my %revs;
3049 my $err;
3050 my $err_handler = $SVN::Error::handler;
3051 $SVN::Error::handler = sub {
3052 ($err) = @_;
3053 skip_unknown_revs($err);
3055 sub _cb {
3056 my ($paths, $r, $author, $date, $log) = @_;
3057 [ dup_changed_paths($paths),
3058 { author => $author, date => $date, log => $log } ];
3060 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3061 sub { $revs{$_[1]} = _cb(@_) });
3062 if ($err && $max >= $head) {
3063 print STDERR "Path '$longest_path' ",
3064 "was probably deleted:\n",
3065 $err->expanded_message,
3066 "\nWill attempt to follow ",
3067 "revisions r$min .. r$max ",
3068 "committed before the deletion\n";
3069 my $hi = $max;
3070 while (--$hi >= $min) {
3071 my $ok;
3072 $self->get_log([$longest_path], $min, $hi,
3073 0, 1, 1, sub {
3074 $ok ||= $_[1];
3075 $revs{$_[1]} = _cb(@_) });
3076 if ($ok) {
3077 print STDERR "r$min .. r$ok OK\n";
3078 last;
3082 $SVN::Error::handler = $err_handler;
3084 my %exists = map { $_->{path} => $_ } @$gsv;
3085 foreach my $r (sort {$a <=> $b} keys %revs) {
3086 my ($paths, $logged) = @{$revs{$r}};
3088 foreach my $gs ($self->match_globs(\%exists, $paths,
3089 $globs, $r)) {
3090 if ($gs->rev_db_max >= $r) {
3091 next;
3093 next unless $gs->match_paths($paths, $r);
3094 $gs->{logged_rev_props} = $logged;
3095 if (my $last_commit = $gs->last_commit) {
3096 $gs->assert_index_clean($last_commit);
3098 my $log_entry = $gs->do_fetch($paths, $r);
3099 if ($log_entry) {
3100 $gs->do_git_commit($log_entry);
3103 foreach my $g (@$globs) {
3104 my $k = "svn-remote.$g->{remote}." .
3105 "$g->{t}-maxRev";
3106 Git::SVN::tmp_config($k, $r);
3109 # pre-fill the .rev_db since it'll eventually get filled in
3110 # with '0' x40 if something new gets committed
3111 foreach my $gs (@$gsv) {
3112 next if defined $gs->rev_db_get($max);
3113 $gs->rev_db_set($max, 0 x40);
3115 foreach my $g (@$globs) {
3116 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3117 Git::SVN::tmp_config($k, $max);
3119 last if $max >= $head;
3120 $min = $max + 1;
3121 $max += $inc;
3122 $max = $head if ($max > $head);
3126 sub match_globs {
3127 my ($self, $exists, $paths, $globs, $r) = @_;
3129 sub get_dir_check {
3130 my ($self, $exists, $g, $r) = @_;
3131 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3132 return unless scalar @x == 3;
3133 my $dirents = $x[0];
3134 foreach my $de (keys %$dirents) {
3135 next if $dirents->{$de}->kind != $SVN::Node::dir;
3136 my $p = $g->{path}->full_path($de);
3137 next if $exists->{$p};
3138 next if (length $g->{path}->{right} &&
3139 ($self->check_path($p, $r) !=
3140 $SVN::Node::dir));
3141 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3142 $g->{ref}->full_path($de), 1);
3145 foreach my $g (@$globs) {
3146 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3147 if ($path->{action} =~ /^[AR]$/) {
3148 get_dir_check($self, $exists, $g, $r);
3151 foreach (keys %$paths) {
3152 if (/$g->{path}->{left_regex}/ &&
3153 !/$g->{path}->{regex}/) {
3154 next if $paths->{$_}->{action} !~ /^[AR]$/;
3155 get_dir_check($self, $exists, $g, $r);
3157 next unless /$g->{path}->{regex}/;
3158 my $p = $1;
3159 my $pathname = $g->{path}->full_path($p);
3160 next if $exists->{$pathname};
3161 $exists->{$pathname} = Git::SVN->init(
3162 $self->{url}, $pathname, undef,
3163 $g->{ref}->full_path($p), 1);
3165 my $c = '';
3166 foreach (split m#/#, $g->{path}->{left}) {
3167 $c .= "/$_";
3168 next unless ($paths->{$c} &&
3169 ($paths->{$c}->{action} =~ /^[AR]$/));
3170 get_dir_check($self, $exists, $g, $r);
3173 values %$exists;
3176 sub minimize_url {
3177 my ($self) = @_;
3178 return $self->{url} if ($self->{url} eq $self->{repos_root});
3179 my $url = $self->{repos_root};
3180 my @components = split(m!/!, $self->{svn_path});
3181 my $c = '';
3182 do {
3183 $url .= "/$c" if length $c;
3184 eval { (ref $self)->new($url)->get_latest_revnum };
3185 } while ($@ && ($c = shift @components));
3186 $url;
3189 sub can_do_switch {
3190 my $self = shift;
3191 unless (defined $can_do_switch) {
3192 my $pool = SVN::Pool->new;
3193 my $rep = eval {
3194 $self->do_switch(1, '', 0, $self->{url},
3195 SVN::Delta::Editor->new, $pool);
3197 if ($@) {
3198 $can_do_switch = 0;
3199 } else {
3200 $rep->abort_report($pool);
3201 $can_do_switch = 1;
3203 $pool->clear;
3205 $can_do_switch;
3208 sub skip_unknown_revs {
3209 my ($err) = @_;
3210 my $errno = $err->apr_err();
3211 # Maybe the branch we're tracking didn't
3212 # exist when the repo started, so it's
3213 # not an error if it doesn't, just continue
3215 # Wonderfully consistent library, eh?
3216 # 160013 - svn:// and file://
3217 # 175002 - http(s)://
3218 # 175007 - http(s):// (this repo required authorization, too...)
3219 # More codes may be discovered later...
3220 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3221 my $err_key = $err->expanded_message;
3222 # revision numbers change every time, filter them out
3223 $err_key =~ s/\d+/\0/g;
3224 $err_key = "$errno\0$err_key";
3225 unless ($ignored_err{$err_key}) {
3226 warn "W: Ignoring error from SVN, path probably ",
3227 "does not exist: ($errno): ",
3228 $err->expanded_message,"\n";
3229 $ignored_err{$err_key} = 1;
3231 return;
3233 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3236 # svn_log_changed_path_t objects passed to get_log are likely to be
3237 # overwritten even if only the refs are copied to an external variable,
3238 # so we should dup the structures in their entirety. Using an externally
3239 # passed pool (instead of our temporary and quickly cleared pool in
3240 # Git::SVN::Ra) does not help matters at all...
3241 sub dup_changed_paths {
3242 my ($paths) = @_;
3243 return undef unless $paths;
3244 my %ret;
3245 foreach my $p (keys %$paths) {
3246 my $i = $paths->{$p};
3247 my %s = map { $_ => $i->$_ }
3248 qw/copyfrom_path copyfrom_rev action/;
3249 $ret{$p} = \%s;
3251 \%ret;
3254 package Git::SVN::Log;
3255 use strict;
3256 use warnings;
3257 use POSIX qw/strftime/;
3258 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3259 %rusers $show_commit $incremental/;
3260 my $l_fmt;
3262 sub cmt_showable {
3263 my ($c) = @_;
3264 return 1 if defined $c->{r};
3265 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3266 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3267 my @log = command(qw/cat-file commit/, $c->{c});
3268 shift @log while ($log[0] ne "\n");
3269 shift @log;
3270 @{$c->{l}} = grep !/^git-svn-id: /, @log;
3272 (undef, $c->{r}, undef) = ::extract_metadata(
3273 (grep(/^git-svn-id: /, @log))[-1]);
3275 return defined $c->{r};
3278 sub log_use_color {
3279 return 1 if $color;
3280 my ($dc, $dcvar);
3281 $dcvar = 'color.diff';
3282 $dc = `git-config --get $dcvar`;
3283 if ($dc eq '') {
3284 # nothing at all; fallback to "diff.color"
3285 $dcvar = 'diff.color';
3286 $dc = `git-config --get $dcvar`;
3288 chomp($dc);
3289 if ($dc eq 'auto') {
3290 my $pc;
3291 $pc = `git-config --get color.pager`;
3292 if ($pc eq '') {
3293 # does not have it -- fallback to pager.color
3294 $pc = `git-config --bool --get pager.color`;
3296 else {
3297 $pc = `git-config --bool --get color.pager`;
3298 if ($?) {
3299 $pc = 'false';
3302 chomp($pc);
3303 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3304 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3306 return 0;
3308 return 0 if $dc eq 'never';
3309 return 1 if $dc eq 'always';
3310 chomp($dc = `git-config --bool --get $dcvar`);
3311 return ($dc eq 'true');
3314 sub git_svn_log_cmd {
3315 my ($r_min, $r_max, @args) = @_;
3316 my $head = 'HEAD';
3317 foreach my $x (@args) {
3318 last if $x eq '--';
3319 next unless ::verify_ref("$x^0");
3320 $head = $x;
3321 last;
3324 my $url = (::working_head_info($head))[0];
3325 my $gs = Git::SVN->find_by_url($url) || Git::SVN->_new;
3326 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3327 $gs->refname);
3328 push @cmd, '-r' unless $non_recursive;
3329 push @cmd, qw/--raw --name-status/ if $verbose;
3330 push @cmd, '--color' if log_use_color();
3331 return @cmd unless defined $r_max;
3332 if ($r_max == $r_min) {
3333 push @cmd, '--max-count=1';
3334 if (my $c = $gs->rev_db_get($r_max)) {
3335 push @cmd, $c;
3337 } else {
3338 my ($c_min, $c_max);
3339 $c_max = $gs->rev_db_get($r_max);
3340 $c_min = $gs->rev_db_get($r_min);
3341 if (defined $c_min && defined $c_max) {
3342 if ($r_max > $r_max) {
3343 push @cmd, "$c_min..$c_max";
3344 } else {
3345 push @cmd, "$c_max..$c_min";
3347 } elsif ($r_max > $r_min) {
3348 push @cmd, $c_max;
3349 } else {
3350 push @cmd, $c_min;
3353 return @cmd;
3356 # adapted from pager.c
3357 sub config_pager {
3358 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3359 if (!defined $pager) {
3360 $pager = 'less';
3361 } elsif (length $pager == 0 || $pager eq 'cat') {
3362 $pager = undef;
3366 sub run_pager {
3367 return unless -t *STDOUT;
3368 pipe my $rfd, my $wfd or return;
3369 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3370 if (!$pid) {
3371 open STDOUT, '>&', $wfd or
3372 ::fatal "Can't redirect to stdout: $!\n";
3373 return;
3375 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3376 $ENV{LESS} ||= 'FRSX';
3377 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3380 sub tz_to_s_offset {
3381 my ($tz) = @_;
3382 $tz =~ s/(\d\d)$//;
3383 return ($1 * 60) + ($tz * 3600);
3386 sub get_author_info {
3387 my ($dest, $author, $t, $tz) = @_;
3388 $author =~ s/(?:^\s*|\s*$)//g;
3389 $dest->{a_raw} = $author;
3390 my $au;
3391 if ($::_authors) {
3392 $au = $rusers{$author} || undef;
3394 if (!$au) {
3395 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3397 $dest->{t} = $t;
3398 $dest->{tz} = $tz;
3399 $dest->{a} = $au;
3400 # Date::Parse isn't in the standard Perl distro :(
3401 if ($tz =~ s/^\+//) {
3402 $t += tz_to_s_offset($tz);
3403 } elsif ($tz =~ s/^\-//) {
3404 $t -= tz_to_s_offset($tz);
3406 $dest->{t_utc} = $t;
3409 sub process_commit {
3410 my ($c, $r_min, $r_max, $defer) = @_;
3411 if (defined $r_min && defined $r_max) {
3412 if ($r_min == $c->{r} && $r_min == $r_max) {
3413 show_commit($c);
3414 return 0;
3416 return 1 if $r_min == $r_max;
3417 if ($r_min < $r_max) {
3418 # we need to reverse the print order
3419 return 0 if (defined $limit && --$limit < 0);
3420 push @$defer, $c;
3421 return 1;
3423 if ($r_min != $r_max) {
3424 return 1 if ($r_min < $c->{r});
3425 return 1 if ($r_max > $c->{r});
3428 return 0 if (defined $limit && --$limit < 0);
3429 show_commit($c);
3430 return 1;
3433 sub show_commit {
3434 my $c = shift;
3435 if ($oneline) {
3436 my $x = "\n";
3437 if (my $l = $c->{l}) {
3438 while ($l->[0] =~ /^\s*$/) { shift @$l }
3439 $x = $l->[0];
3441 $l_fmt ||= 'A' . length($c->{r});
3442 print 'r',pack($l_fmt, $c->{r}),' | ';
3443 print "$c->{c} | " if $show_commit;
3444 print $x;
3445 } else {
3446 show_commit_normal($c);
3450 sub show_commit_changed_paths {
3451 my ($c) = @_;
3452 return unless $c->{changed};
3453 print "Changed paths:\n", @{$c->{changed}};
3456 sub show_commit_normal {
3457 my ($c) = @_;
3458 print '-' x72, "\nr$c->{r} | ";
3459 print "$c->{c} | " if $show_commit;
3460 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3461 localtime($c->{t_utc})), ' | ';
3462 my $nr_line = 0;
3464 if (my $l = $c->{l}) {
3465 while ($l->[$#$l] eq "\n" && $#$l > 0
3466 && $l->[($#$l - 1)] eq "\n") {
3467 pop @$l;
3469 $nr_line = scalar @$l;
3470 if (!$nr_line) {
3471 print "1 line\n\n\n";
3472 } else {
3473 if ($nr_line == 1) {
3474 $nr_line = '1 line';
3475 } else {
3476 $nr_line .= ' lines';
3478 print $nr_line, "\n";
3479 show_commit_changed_paths($c);
3480 print "\n";
3481 print $_ foreach @$l;
3483 } else {
3484 print "1 line\n";
3485 show_commit_changed_paths($c);
3486 print "\n";
3489 foreach my $x (qw/raw stat diff/) {
3490 if ($c->{$x}) {
3491 print "\n";
3492 print $_ foreach @{$c->{$x}}
3497 sub cmd_show_log {
3498 my (@args) = @_;
3499 my ($r_min, $r_max);
3500 my $r_last = -1; # prevent dupes
3501 if (defined $TZ) {
3502 $ENV{TZ} = $TZ;
3503 } else {
3504 delete $ENV{TZ};
3506 if (defined $::_revision) {
3507 if ($::_revision =~ /^(\d+):(\d+)$/) {
3508 ($r_min, $r_max) = ($1, $2);
3509 } elsif ($::_revision =~ /^\d+$/) {
3510 $r_min = $r_max = $::_revision;
3511 } else {
3512 ::fatal "-r$::_revision is not supported, use ",
3513 "standard \'git log\' arguments instead\n";
3517 config_pager();
3518 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3519 my $log = command_output_pipe(@args);
3520 run_pager();
3521 my (@k, $c, $d, $stat);
3522 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3523 while (<$log>) {
3524 if (/^${esc_color}commit ($::sha1_short)/o) {
3525 my $cmt = $1;
3526 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3527 $r_last = $c->{r};
3528 process_commit($c, $r_min, $r_max, \@k) or
3529 goto out;
3531 $d = undef;
3532 $c = { c => $cmt };
3533 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3534 get_author_info($c, $1, $2, $3);
3535 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3536 # ignore
3537 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3538 push @{$c->{raw}}, $_;
3539 } elsif (/^${esc_color}[ACRMDT]\t/) {
3540 # we could add $SVN->{svn_path} here, but that requires
3541 # remote access at the moment (repo_path_split)...
3542 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3543 push @{$c->{changed}}, $_;
3544 } elsif (/^${esc_color}diff /o) {
3545 $d = 1;
3546 push @{$c->{diff}}, $_;
3547 } elsif ($d) {
3548 push @{$c->{diff}}, $_;
3549 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3550 $esc_color*[\+\-]*$esc_color$/x) {
3551 $stat = 1;
3552 push @{$c->{stat}}, $_;
3553 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3554 push @{$c->{stat}}, $_;
3555 $stat = undef;
3556 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3557 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3558 } elsif (s/^${esc_color} //o) {
3559 push @{$c->{l}}, $_;
3562 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3563 $r_last = $c->{r};
3564 process_commit($c, $r_min, $r_max, \@k);
3566 if (@k) {
3567 my $swap = $r_max;
3568 $r_max = $r_min;
3569 $r_min = $swap;
3570 process_commit($_, $r_min, $r_max) foreach reverse @k;
3572 out:
3573 close $log;
3574 print '-' x72,"\n" unless $incremental || $oneline;
3577 package Git::SVN::Migration;
3578 # these version numbers do NOT correspond to actual version numbers
3579 # of git nor git-svn. They are just relative.
3581 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3583 # v1 layout: .git/$id/info/url, refs/remotes/$id
3585 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3587 # v3 layout: .git/svn/$id, refs/remotes/$id
3588 # - info/url may remain for backwards compatibility
3589 # - this is what we migrate up to this layout automatically,
3590 # - this will be used by git svn init on single branches
3591 # v3.1 layout (auto migrated):
3592 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3593 # for backwards compatibility
3595 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3596 # - this is only created for newly multi-init-ed
3597 # repositories. Similar in spirit to the
3598 # --use-separate-remotes option in git-clone (now default)
3599 # - we do not automatically migrate to this (following
3600 # the example set by core git)
3601 use strict;
3602 use warnings;
3603 use Carp qw/croak/;
3604 use File::Path qw/mkpath/;
3605 use File::Basename qw/dirname basename/;
3606 use vars qw/$_minimize/;
3608 sub migrate_from_v0 {
3609 my $git_dir = $ENV{GIT_DIR};
3610 return undef unless -d $git_dir;
3611 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3612 my $migrated = 0;
3613 while (<$fh>) {
3614 chomp;
3615 my ($id, $orig_ref) = ($_, $_);
3616 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3617 next unless -f "$git_dir/$id/info/url";
3618 my $new_ref = "refs/remotes/$id";
3619 if (::verify_ref("$new_ref^0")) {
3620 print STDERR "W: $orig_ref is probably an old ",
3621 "branch used by an ancient version of ",
3622 "git-svn.\n",
3623 "However, $new_ref also exists.\n",
3624 "We will not be able ",
3625 "to use this branch until this ",
3626 "ambiguity is resolved.\n";
3627 next;
3629 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3630 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3631 command_noisy('update-ref', $new_ref, $orig_ref);
3632 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3633 $migrated++;
3635 command_close_pipe($fh, $ctx);
3636 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3637 $migrated;
3640 sub migrate_from_v1 {
3641 my $git_dir = $ENV{GIT_DIR};
3642 my $migrated = 0;
3643 return $migrated unless -d $git_dir;
3644 my $svn_dir = "$git_dir/svn";
3646 # just in case somebody used 'svn' as their $id at some point...
3647 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3649 print STDERR "Migrating from a git-svn v1 layout...\n";
3650 mkpath([$svn_dir]);
3651 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3652 "$svn_dir\n\t(required for this version ",
3653 "($::VERSION) of git-svn) does not. exist\n";
3654 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3655 while (<$fh>) {
3656 my $x = $_;
3657 next unless $x =~ s#^refs/remotes/##;
3658 chomp $x;
3659 next unless -f "$git_dir/$x/info/url";
3660 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3661 next unless $u;
3662 my $dn = dirname("$git_dir/svn/$x");
3663 mkpath([$dn]) unless -d $dn;
3664 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3665 mkpath(["$git_dir/svn/svn"]);
3666 print STDERR " - $git_dir/$x/info => ",
3667 "$git_dir/svn/$x/info\n";
3668 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3669 croak "$!: $x";
3670 # don't worry too much about these, they probably
3671 # don't exist with repos this old (save for index,
3672 # and we can easily regenerate that)
3673 foreach my $f (qw/unhandled.log index .rev_db/) {
3674 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3676 } else {
3677 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3678 rename "$git_dir/$x", "$git_dir/svn/$x" or
3679 croak "$!: $x";
3681 $migrated++;
3683 command_close_pipe($fh, $ctx);
3684 print STDERR "Done migrating from a git-svn v1 layout\n";
3685 $migrated;
3688 sub read_old_urls {
3689 my ($l_map, $pfx, $path) = @_;
3690 my @dir;
3691 foreach (<$path/*>) {
3692 if (-r "$_/info/url") {
3693 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3694 my $ref_id = $pfx . basename $_;
3695 my $url = ::file_to_s("$_/info/url");
3696 $l_map->{$ref_id} = $url;
3697 } elsif (-d $_) {
3698 push @dir, $_;
3701 foreach (@dir) {
3702 my $x = $_;
3703 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3704 read_old_urls($l_map, $x, $_);
3708 sub migrate_from_v2 {
3709 my @cfg = command(qw/config -l/);
3710 return if grep /^svn-remote\..+\.url=/, @cfg;
3711 my %l_map;
3712 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3713 my $migrated = 0;
3715 foreach my $ref_id (sort keys %l_map) {
3716 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3717 if ($@) {
3718 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3720 $migrated++;
3722 $migrated;
3725 sub minimize_connections {
3726 my $r = Git::SVN::read_all_remotes();
3727 my $new_urls = {};
3728 my $root_repos = {};
3729 foreach my $repo_id (keys %$r) {
3730 my $url = $r->{$repo_id}->{url} or next;
3731 my $fetch = $r->{$repo_id}->{fetch} or next;
3732 my $ra = Git::SVN::Ra->new($url);
3734 # skip existing cases where we already connect to the root
3735 if (($ra->{url} eq $ra->{repos_root}) ||
3736 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3737 $repo_id)) {
3738 $root_repos->{$ra->{url}} = $repo_id;
3739 next;
3742 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3743 my $root_path = $ra->{url};
3744 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3745 foreach my $path (keys %$fetch) {
3746 my $ref_id = $fetch->{$path};
3747 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3749 # make sure we can read when connecting to
3750 # a higher level of a repository
3751 my ($last_rev, undef) = $gs->last_rev_commit;
3752 if (!defined $last_rev) {
3753 $last_rev = eval {
3754 $root_ra->get_latest_revnum;
3756 next if $@;
3758 my $new = $root_path;
3759 $new .= length $path ? "/$path" : '';
3760 eval {
3761 $root_ra->get_log([$new], $last_rev, $last_rev,
3762 0, 0, 1, sub { });
3764 next if $@;
3765 $new_urls->{$ra->{repos_root}}->{$new} =
3766 { ref_id => $ref_id,
3767 old_repo_id => $repo_id,
3768 old_path => $path };
3772 my @emptied;
3773 foreach my $url (keys %$new_urls) {
3774 # see if we can re-use an existing [svn-remote "repo_id"]
3775 # instead of creating a(n ugly) new section:
3776 my $repo_id = $root_repos->{$url} ||
3777 Git::SVN::sanitize_remote_name($url);
3779 my $fetch = $new_urls->{$url};
3780 foreach my $path (keys %$fetch) {
3781 my $x = $fetch->{$path};
3782 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3783 my $pfx = "svn-remote.$x->{old_repo_id}";
3785 my $old_fetch = quotemeta("$x->{old_path}:".
3786 "refs/remotes/$x->{ref_id}");
3787 command_noisy(qw/config --unset/,
3788 "$pfx.fetch", '^'. $old_fetch . '$');
3789 delete $r->{$x->{old_repo_id}}->
3790 {fetch}->{$x->{old_path}};
3791 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3792 command_noisy(qw/config --unset/,
3793 "$pfx.url");
3794 push @emptied, $x->{old_repo_id}
3798 if (@emptied) {
3799 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3800 "$ENV{GIT_DIR}/config";
3801 print STDERR <<EOF;
3802 The following [svn-remote] sections in your config file ($file) are empty
3803 and can be safely removed:
3805 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3809 sub migration_check {
3810 migrate_from_v0();
3811 migrate_from_v1();
3812 migrate_from_v2();
3813 minimize_connections() if $_minimize;
3816 package Git::IndexInfo;
3817 use strict;
3818 use warnings;
3819 use Git qw/command_input_pipe command_close_pipe/;
3821 sub new {
3822 my ($class) = @_;
3823 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3824 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3827 sub remove {
3828 my ($self, $path) = @_;
3829 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3830 return ++$self->{nr};
3832 undef;
3835 sub update {
3836 my ($self, $mode, $hash, $path) = @_;
3837 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3838 return ++$self->{nr};
3840 undef;
3843 sub DESTROY {
3844 my ($self) = @_;
3845 command_close_pipe($self->{gui}, $self->{ctx});
3848 package Git::SVN::GlobSpec;
3849 use strict;
3850 use warnings;
3852 sub new {
3853 my ($class, $glob) = @_;
3854 my $re = $glob;
3855 $re =~ s!/+$!!g; # no need for trailing slashes
3856 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3857 my ($left, $right) = ($1, $2);
3858 if ($nr > 1) {
3859 die "Only one '*' wildcard expansion ",
3860 "is supported (got $nr): '$glob'\n";
3861 } elsif ($nr == 0) {
3862 die "One '*' is needed for glob: '$glob'\n";
3864 $re = quotemeta($left) . $re . quotemeta($right);
3865 if (length $left && !($left =~ s!/+$!!g)) {
3866 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3868 if (length $right && !($right =~ s!^/+!!g)) {
3869 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3871 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3872 bless { left => $left, right => $right, left_regex => $left_re,
3873 regex => qr/$re/, glob => $glob }, $class;
3876 sub full_path {
3877 my ($self, $path) = @_;
3878 return (length $self->{left} ? "$self->{left}/" : '') .
3879 $path . (length $self->{right} ? "/$self->{right}" : '');
3882 __END__
3884 Data structures:
3887 $remotes = { # returned by read_all_remotes()
3888 'svn' => {
3889 # svn-remote.svn.url=https://svn.musicpd.org
3890 url => 'https://svn.musicpd.org',
3891 # svn-remote.svn.fetch=mpd/trunk:trunk
3892 fetch => {
3893 'mpd/trunk' => 'trunk',
3895 # svn-remote.svn.tags=mpd/tags/*:tags/*
3896 tags => {
3897 path => {
3898 left => 'mpd/tags',
3899 right => '',
3900 regex => qr!mpd/tags/([^/]+)$!,
3901 glob => 'tags/*',
3903 ref => {
3904 left => 'tags',
3905 right => '',
3906 regex => qr!tags/([^/]+)$!,
3907 glob => 'tags/*',
3913 $log_entry hashref as returned by libsvn_log_entry()
3915 log => 'whitespace-formatted log entry
3916 ', # trailing newline is preserved
3917 revision => '8', # integer
3918 date => '2004-02-24T17:01:44.108345Z', # commit date
3919 author => 'committer name'
3923 # this is generated by generate_diff();
3924 @mods = array of diff-index line hashes, each element represents one line
3925 of diff-index output
3927 diff-index line ($m hash)
3929 mode_a => first column of diff-index output, no leading ':',
3930 mode_b => second column of diff-index output,
3931 sha1_b => sha1sum of the final blob,
3932 chg => change type [MCRADT],
3933 file_a => original file name of a file (iff chg is 'C' or 'R')
3934 file_b => new/current file name of a file (any chg)
3938 # retval of read_url_paths{,_all}();
3939 $l_map = {
3940 # repository root url
3941 'https://svn.musicpd.org' => {
3942 # repository path # GIT_SVN_ID
3943 'mpd/trunk' => 'trunk',
3944 'mpd/tags/0.11.5' => 'tags/0.11.5',
3948 Notes:
3949 I don't trust the each() function on unless I created %hash myself
3950 because the internal iterator may not have started at base.