git-svn: convert show-ignore over to Git::SVN
[git/gitbuild.git] / git-svn.perl
blobe0bccbcdc970d856db69033c60a2d84d790cc5b3
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 $SVN_URL
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 use Cwd qw/abs_path/;
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
17 my $LC_ALL = $ENV{LC_ALL};
18 my $TZ = $ENV{TZ};
19 # make sure the svn binary gives consistent output between locales and TZs:
20 $ENV{TZ} = 'UTC';
21 $ENV{LC_ALL} = 'C';
22 $| = 1; # unbuffer STDOUT
24 # properties that we do not log:
25 my %SKIP = ( 'svn:wc:ra_dav:version-url' => 1,
26 'svn:special' => 1,
27 'svn:executable' => 1,
28 'svn:entry:committed-rev' => 1,
29 'svn:entry:last-author' => 1,
30 'svn:entry:uuid' => 1,
31 'svn:entry:committed-date' => 1,
34 sub fatal (@) { print STDERR @_; exit 1 }
35 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
36 require SVN::Ra;
37 require SVN::Delta;
38 if ($SVN::Core::VERSION lt '1.1.0') {
39 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
41 push @Git::SVN::Ra::ISA, 'SVN::Ra';
42 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
43 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
44 use Carp qw/croak/;
45 use IO::File qw//;
46 use File::Basename qw/dirname basename/;
47 use File::Path qw/mkpath/;
48 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
49 use POSIX qw/strftime/;
50 use IPC::Open3;
51 use Memoize;
52 use Git;
53 memoize('revisions_eq');
54 memoize('cmt_metadata');
55 memoize('get_commit_time');
57 BEGIN {
58 my $s;
59 foreach (qw/command command_oneline command_noisy command_output_pipe
60 command_input_pipe command_close_pipe/) {
61 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
62 "*$_ = *Git::$_; ";
64 eval $s;
67 my ($SVN);
69 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
70 my $sha1 = qr/[a-f\d]{40}/;
71 my $sha1_short = qr/[a-f\d]{4,40}/;
72 my $_esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
73 my ($_revision,$_stdin,$_help,$_rmdir,$_edit,
74 $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
75 $_repack, $_repack_nr, $_repack_flags, $_q,
76 $_message, $_file, $_no_metadata,
77 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
78 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
79 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
80 $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
81 $_pager, $_color, $_prefix);
82 my (@_branch_from, %tree_map, %users, %rusers);
83 my @repo_path_split_cache;
84 use vars qw/$_follow_parent/;
86 my %fc_opts = ( 'branch|b=s' => \@_branch_from,
87 'follow-parent|follow' => \$_follow_parent,
88 'branch-all-refs|B' => \$_branch_all_refs,
89 'authors-file|A=s' => \$_authors,
90 'repack:i' => \$_repack,
91 'no-metadata' => \$_no_metadata,
92 'quiet|q' => \$_q,
93 'username=s' => \$Git::SVN::Prompt::_username,
94 'config-dir=s' => \$Git::SVN::Ra::config_dir,
95 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96 'ignore-nodate' => \$_ignore_nodate,
97 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
99 my ($_trunk, $_tags, $_branches);
100 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
101 'tags|t=s' => \$_tags,
102 'branches|b=s' => \$_branches );
103 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
104 my %cmt_opts = ( 'edit|e' => \$_edit,
105 'rmdir' => \$_rmdir,
106 'find-copies-harder' => \$_find_copies_harder,
107 'l=i' => \$_l,
108 'copy-similarity|C=i'=> \$_cp_similarity
111 my %cmd = (
112 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
113 { 'revision|r=s' => \$_revision, %fc_opts } ],
114 init => [ \&cmd_init, "Initialize a repo for tracking" .
115 " (requires URL argument)",
116 \%init_opts ],
117 dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
118 { 'merge|m|M' => \$_merge,
119 'strategy|s=s' => \$_strategy,
120 'dry-run|n' => \$_dry_run,
121 %cmt_opts, %fc_opts } ],
122 'set-tree' => [ \&commit, "Set an SVN repository to a git tree-ish",
123 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
124 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
125 { 'revision|r=i' => \$_revision } ],
126 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
127 { 'copy-remote|remote=s' => \$_cp_remote,
128 'upgrade' => \$_upgrade } ],
129 'graft-branches' => [ \&graft_branches,
130 'Detect merges/branches from already imported history',
131 { 'merge-rx|m' => \@_opt_m,
132 'branch|b=s' => \@_branch_from,
133 'branch-all-refs|B' => \$_branch_all_refs,
134 'no-default-regex' => \$_no_default_regex,
135 'no-graft-copy' => \$_no_graft_copy } ],
136 'multi-init' => [ \&cmd_multi_init,
137 'Initialize multiple trees (like git-svnimport)',
138 { %multi_opts, %init_opts,
139 'revision|r=i' => \$_revision,
140 'username=s' => \$Git::SVN::Prompt::_username,
141 'config-dir=s' => \$Git::SVN::Ra::config_dir,
142 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
143 'prefix=s' => \$_prefix,
144 } ],
145 'multi-fetch' => [ \&multi_fetch,
146 'Fetch multiple trees (like git-svnimport)',
147 \%fc_opts ],
148 'log' => [ \&show_log, 'Show commit logs',
149 { 'limit=i' => \$_limit,
150 'revision|r=s' => \$_revision,
151 'verbose|v' => \$_verbose,
152 'incremental' => \$_incremental,
153 'oneline' => \$_oneline,
154 'show-commit' => \$_show_commit,
155 'non-recursive' => \$_non_recursive,
156 'authors-file|A=s' => \$_authors,
157 'color' => \$_color,
158 'pager=s' => \$_pager,
159 } ],
160 'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
161 { 'message|m=s' => \$_message,
162 'file|F=s' => \$_file,
163 'revision|r=s' => \$_revision,
164 %cmt_opts } ],
167 my $cmd;
168 for (my $i = 0; $i < @ARGV; $i++) {
169 if (defined $cmd{$ARGV[$i]}) {
170 $cmd = $ARGV[$i];
171 splice @ARGV, $i, 1;
172 last;
176 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
178 read_repo_config(\%opts);
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
180 'version|V' => \$_version,
181 'id|i=s' => \$GIT_SVN);
182 exit 1 if (!$rv && $cmd ne 'log');
184 set_default_vals();
185 usage(0) if $_help;
186 version() if $_version;
187 usage(1) unless defined $cmd;
188 init_vars();
189 load_authors() if $_authors;
190 load_all_refs() if $_branch_all_refs;
191 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
192 $cmd{$cmd}->[0]->(@ARGV);
193 exit 0;
195 ####################### primary functions ######################
196 sub usage {
197 my $exit = shift || 0;
198 my $fd = $exit ? \*STDERR : \*STDOUT;
199 print $fd <<"";
200 git-svn - bidirectional operations between a single Subversion tree and git
201 Usage: $0 <command> [options] [arguments]\n
203 print $fd "Available commands:\n" unless $cmd;
205 foreach (sort keys %cmd) {
206 next if $cmd && $cmd ne $_;
207 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
208 foreach (keys %{$cmd{$_}->[2]}) {
209 # prints out arguments as they should be passed:
210 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
211 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
212 "--$_" : "-$_" }
213 split /\|/,$_)," $x\n";
216 print $fd <<"";
217 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
218 arbitrary identifier if you're tracking multiple SVN branches/repositories in
219 one git repository and want to keep them separate. See git-svn(1) for more
220 information.
222 exit $exit;
225 sub version {
226 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
227 exit 0;
230 sub rebuild {
231 if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
232 copy_remote_ref();
234 $SVN_URL = shift or undef;
235 my $newest_rev = 0;
236 if ($_upgrade) {
237 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
238 $GIT_SVN-HEAD");
239 } else {
240 check_upgrade_needed();
243 my ($rev_list, $ctx) = command_output_pipe("rev-list",
244 "refs/remotes/$GIT_SVN");
245 my $latest;
246 my $svn_uuid;
247 while (<$rev_list>) {
248 chomp;
249 my $c = $_;
250 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
251 my @commit = grep(/^git-svn-id: /,
252 command(qw/cat-file commit/, $c));
253 next if (!@commit); # skip merges
254 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
255 if (!defined $rev || !$uuid) {
256 croak "Unable to extract revision or UUID from ",
257 "$c, $commit[$#commit]\n";
260 # if we merged or otherwise started elsewhere, this is
261 # how we break out of it
262 next if (defined $svn_uuid && ($uuid ne $svn_uuid));
263 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
265 unless (defined $latest) {
266 if (!$SVN_URL && !$url) {
267 croak "SVN repository location required: $url\n";
269 $SVN_URL ||= $url;
270 $svn_uuid ||= $uuid;
271 setup_git_svn();
272 $latest = $rev;
274 revdb_set($REVDB, $rev, $c);
275 print "r$rev = $c\n";
276 $newest_rev = $rev if ($rev > $newest_rev);
278 command_close_pipe($rev_list, $ctx);
281 sub do_git_init_db {
282 unless (-d $ENV{GIT_DIR}) {
283 my @init_db = ('init');
284 push @init_db, "--template=$_template" if defined $_template;
285 push @init_db, "--shared" if defined $_shared;
286 command_noisy(@init_db);
290 sub cmd_init {
291 my $url = shift or die "SVN repository location required " .
292 "as a command-line argument\n";
293 if (my $repo_path = shift) {
294 unless (-d $repo_path) {
295 mkpath([$repo_path]);
297 chdir $repo_path or croak $!;
298 $ENV{GIT_DIR} = $repo_path . "/.git";
300 do_git_init_db();
302 Git::SVN->init(undef, $url);
305 sub cmd_fetch {
306 fetch_child_id($GIT_SVN, @_);
309 sub fetch {
310 check_upgrade_needed();
311 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
312 my $ret = fetch_lib(@_);
313 if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
314 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
316 return $ret;
319 sub fetch_lib {
320 my (@parents) = @_;
321 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
322 $SVN ||= Git::SVN::Ra->new($SVN_URL);
323 my ($last_rev, $last_commit) = svn_grab_base_rev();
324 my ($base, $head) = libsvn_parse_revision($last_rev);
325 if ($base > $head) {
326 return { revision => $last_rev, commit => $last_commit }
328 my $index = set_index($GIT_SVN_INDEX);
330 # limit ourselves and also fork() since get_log won't release memory
331 # after processing a revision and SVN stuff seems to leak
332 my $inc = 1000;
333 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
334 if (defined $last_commit) {
335 unless (-e $GIT_SVN_INDEX) {
336 command_noisy('read-tree', $last_commit);
338 my $x = command_oneline('write-tree');
339 my ($y) = (command(qw/cat-file commit/, $last_commit)
340 =~ /^tree ($sha1)/m);
341 if ($y ne $x) {
342 unlink $GIT_SVN_INDEX or croak $!;
343 command_noisy('read-tree', $last_commit);
345 $x = command_oneline('write-tree');
346 if ($y ne $x) {
347 print STDERR "trees ($last_commit) $y != $x\n",
348 "Something is seriously wrong...\n";
351 while (1) {
352 # fork, because using SVN::Pool with get_log() still doesn't
353 # seem to help enough to keep memory usage down.
354 defined(my $pid = fork) or croak $!;
355 if (!$pid) {
356 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
358 # Yes I'm perfectly aware that the fourth argument
359 # below is the limit revisions number. Unfortunately
360 # performance sucks with it enabled, so it's much
361 # faster to fetch revision ranges instead of relying
362 # on the limiter.
363 $SVN->dup->get_log([''], $min, $max, 0, 1, 1,
364 sub {
365 my $log_msg;
366 if ($last_commit) {
367 $log_msg = libsvn_fetch(
368 $last_commit, @_);
369 $last_commit = git_commit(
370 $log_msg,
371 $last_commit,
372 @parents);
373 } else {
374 $log_msg = libsvn_new_tree(@_);
375 $last_commit = git_commit(
376 $log_msg, @parents);
379 exit 0;
381 waitpid $pid, 0;
382 croak $? if $?;
383 ($last_rev, $last_commit) = svn_grab_base_rev();
384 last if ($max >= $head);
385 $min = $max + 1;
386 $max += $inc;
387 $max = $head if ($max > $head);
388 $SVN = Git::SVN::Ra->new($SVN_URL);
390 restore_index($index);
391 return { revision => $last_rev, commit => $last_commit };
394 sub commit {
395 my (@commits) = @_;
396 check_upgrade_needed();
397 if ($_stdin || !@commits) {
398 print "Reading from stdin...\n";
399 @commits = ();
400 while (<STDIN>) {
401 if (/\b($sha1_short)\b/o) {
402 unshift @commits, $1;
406 my @revs;
407 foreach my $c (@commits) {
408 my @tmp = command('rev-parse',$c);
409 if (scalar @tmp == 1) {
410 push @revs, $tmp[0];
411 } elsif (scalar @tmp > 1) {
412 push @revs, reverse(command('rev-list',@tmp));
413 } else {
414 die "Failed to rev-parse $c\n";
417 commit_lib(@revs);
418 print "Done committing ",scalar @revs," revisions to SVN\n";
421 sub commit_lib {
422 my (@revs) = @_;
423 my ($r_last, $cmt_last) = svn_grab_base_rev();
424 defined $r_last or die "Must have an existing revision to commit\n";
425 my $fetched = fetch();
426 if ($r_last != $fetched->{revision}) {
427 print STDERR "There are new revisions that were fetched ",
428 "and need to be merged (or acknowledged) ",
429 "before committing.\n",
430 "last rev: $r_last\n",
431 " current: $fetched->{revision}\n";
432 exit 1;
434 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
436 my $repo;
437 set_svn_commit_env();
438 foreach my $c (@revs) {
439 my $log_msg = get_commit_message($c, $commit_msg);
441 # fork for each commit because there's a memory leak I
442 # can't track down... (it's probably in the SVN code)
443 defined(my $pid = open my $fh, '-|') or croak $!;
444 if (!$pid) {
445 my $pool = SVN::Pool->new;
446 my $ed = SVN::Git::Editor->new(
447 { r => $r_last,
448 ra => $SVN->dup,
449 c => $c,
450 svn_path => $SVN->{svn_path},
452 $SVN->get_commit_editor(
453 $log_msg->{msg},
454 sub {
455 libsvn_commit_cb(
456 @_, $c,
457 $log_msg->{msg},
458 $r_last,
459 $cmt_last)
460 }, $pool)
462 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
463 if (@$mods == 0) {
464 print "No changes\nr$r_last = $cmt_last\n";
465 $ed->abort_edit;
466 } else {
467 $ed->close_edit;
469 $pool->clear;
470 exit 0;
472 my ($r_new, $cmt_new, $no);
473 while (<$fh>) {
474 print $_;
475 chomp;
476 if (/^r(\d+) = ($sha1)$/o) {
477 ($r_new, $cmt_new) = ($1, $2);
478 } elsif ($_ eq 'No changes') {
479 $no = 1;
482 close $fh or exit 1;
483 if (! defined $r_new && ! defined $cmt_new) {
484 unless ($no) {
485 die "Failed to parse revision information\n";
487 } else {
488 ($r_last, $cmt_last) = ($r_new, $cmt_new);
491 $ENV{LC_ALL} = 'C';
492 unlink $commit_msg;
495 sub dcommit {
496 my $head = shift || 'HEAD';
497 my $gs = "refs/remotes/$GIT_SVN";
498 my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
499 my $last_rev;
500 foreach my $d (reverse @refs) {
501 if (!verify_ref("$d~1")) {
502 die "Commit $d\n",
503 "has no parent commit, and therefore ",
504 "nothing to diff against.\n",
505 "You should be working from a repository ",
506 "originally created by git-svn\n";
508 unless (defined $last_rev) {
509 (undef, $last_rev, undef) = cmt_metadata("$d~1");
510 unless (defined $last_rev) {
511 die "Unable to extract revision information ",
512 "from commit $d~1\n";
515 if ($_dry_run) {
516 print "diff-tree $d~1 $d\n";
517 } else {
518 if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
519 $last_rev = $r;
520 } # else: no changes, same $last_rev
523 return if $_dry_run;
524 fetch();
525 my @diff = command('diff-tree', 'HEAD', $gs, '--');
526 my @finish;
527 if (@diff) {
528 @finish = qw/rebase/;
529 push @finish, qw/--merge/ if $_merge;
530 push @finish, "--strategy=$_strategy" if $_strategy;
531 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
532 } else {
533 print "No changes between current HEAD and $gs\n",
534 "Resetting to the latest $gs\n";
535 @finish = qw/reset --mixed/;
537 command_noisy(@finish, $gs);
540 sub cmd_show_ignore {
541 my $gs = Git::SVN->new;
542 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
543 $gs->traverse_ignore(\*STDOUT, '', $r);
546 sub graft_branches {
547 my $gr_file = "$GIT_DIR/info/grafts";
548 my ($grafts, $comments) = read_grafts($gr_file);
549 my $gr_sha1;
551 if (%$grafts) {
552 # temporarily disable our grafts file to make this idempotent
553 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
554 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
557 my $l_map = read_url_paths();
558 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
559 unless ($_no_default_regex) {
560 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
561 qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
562 qr/\b(?:from|of)\s+([\w\.\-]+)/i );
564 foreach my $u (keys %$l_map) {
565 if (@re) {
566 foreach my $p (keys %{$l_map->{$u}}) {
567 graft_merge_msg($grafts,$l_map,$u,$p,@re);
570 unless ($_no_graft_copy) {
571 graft_file_copy_lib($grafts,$l_map,$u);
574 graft_tree_joins($grafts);
576 write_grafts($grafts, $comments, $gr_file);
577 unlink "$gr_file~$gr_sha1" if $gr_sha1;
580 sub cmd_multi_init {
581 my $url = shift;
582 unless (defined $_trunk || defined $_branches || defined $_tags) {
583 usage(1);
585 do_git_init_db();
586 $_prefix = '' unless defined $_prefix;
587 if (defined $_trunk) {
588 my $gs_trunk = eval { Git::SVN->new($_prefix . 'trunk') };
589 unless ($gs_trunk) {
590 my $trunk_url = complete_svn_url($url, $_trunk);
591 $gs_trunk = Git::SVN->init($_prefix . 'trunk',
592 $trunk_url);
593 command_noisy('config', 'svn.trunk', $trunk_url);
596 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
597 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
598 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
601 sub multi_fetch {
602 # try to do trunk first, since branches/tags
603 # may be descended from it.
604 if (-e "$GIT_DIR/svn/trunk/info/url") {
605 fetch_child_id('trunk', @_);
607 rec_fetch('', "$GIT_DIR/svn", @_);
610 sub show_log {
611 my (@args) = @_;
612 my ($r_min, $r_max);
613 my $r_last = -1; # prevent dupes
614 rload_authors() if $_authors;
615 if (defined $TZ) {
616 $ENV{TZ} = $TZ;
617 } else {
618 delete $ENV{TZ};
620 if (defined $_revision) {
621 if ($_revision =~ /^(\d+):(\d+)$/) {
622 ($r_min, $r_max) = ($1, $2);
623 } elsif ($_revision =~ /^\d+$/) {
624 $r_min = $r_max = $_revision;
625 } else {
626 print STDERR "-r$_revision is not supported, use ",
627 "standard \'git log\' arguments instead\n";
628 exit 1;
632 config_pager();
633 @args = (git_svn_log_cmd($r_min, $r_max), @args);
634 my $log = command_output_pipe(@args);
635 run_pager();
636 my (@k, $c, $d);
638 while (<$log>) {
639 if (/^${_esc_color}commit ($sha1_short)/o) {
640 my $cmt = $1;
641 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
642 $r_last = $c->{r};
643 process_commit($c, $r_min, $r_max, \@k) or
644 goto out;
646 $d = undef;
647 $c = { c => $cmt };
648 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
649 get_author_info($c, $1, $2, $3);
650 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
651 # ignore
652 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
653 push @{$c->{raw}}, $_;
654 } elsif (/^${_esc_color}[ACRMDT]\t/) {
655 # we could add $SVN->{svn_path} here, but that requires
656 # remote access at the moment (repo_path_split)...
657 s#^(${_esc_color})([ACRMDT])\t#$1 $2 #;
658 push @{$c->{changed}}, $_;
659 } elsif (/^${_esc_color}diff /) {
660 $d = 1;
661 push @{$c->{diff}}, $_;
662 } elsif ($d) {
663 push @{$c->{diff}}, $_;
664 } elsif (/^${_esc_color} (git-svn-id:.+)$/) {
665 ($c->{url}, $c->{r}, undef) = extract_metadata($1);
666 } elsif (s/^${_esc_color} //) {
667 push @{$c->{l}}, $_;
670 if ($c && defined $c->{r} && $c->{r} != $r_last) {
671 $r_last = $c->{r};
672 process_commit($c, $r_min, $r_max, \@k);
674 if (@k) {
675 my $swap = $r_max;
676 $r_max = $r_min;
677 $r_min = $swap;
678 process_commit($_, $r_min, $r_max) foreach reverse @k;
680 out:
681 close $log;
682 print '-' x72,"\n" unless $_incremental || $_oneline;
685 sub commit_diff_usage {
686 print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
687 exit 1
690 sub commit_diff {
691 my $ta = shift or commit_diff_usage();
692 my $tb = shift or commit_diff_usage();
693 if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
694 print STDERR "Needed URL or usable git-svn id command-line\n";
695 commit_diff_usage();
697 my $r = shift;
698 unless (defined $r) {
699 if (defined $_revision) {
700 $r = $_revision
701 } else {
702 die "-r|--revision is a required argument\n";
705 if (defined $_message && defined $_file) {
706 print STDERR "Both --message/-m and --file/-F specified ",
707 "for the commit message.\n",
708 "I have no idea what you mean\n";
709 exit 1;
711 if (defined $_file) {
712 $_message = file_to_s($_file);
713 } else {
714 $_message ||= get_commit_message($tb,
715 "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
717 $SVN ||= Git::SVN::Ra->new($SVN_URL);
718 if ($r eq 'HEAD') {
719 $r = $SVN->get_latest_revnum;
720 } elsif ($r !~ /^\d+$/) {
721 die "revision argument: $r not understood by git-svn\n";
723 my $rev_committed;
724 my $pool = SVN::Pool->new;
725 my $ed = SVN::Git::Editor->new({ r => $r,
726 ra => $SVN->dup,
727 c => $tb,
728 svn_path => $SVN->{svn_path}
730 $SVN->get_commit_editor($_message,
731 sub {
732 $rev_committed = $_[0];
733 print "Committed $_[0]\n";
735 $pool)
737 eval {
738 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
739 if (@$mods == 0) {
740 print "No changes\n$ta == $tb\n";
741 $ed->abort_edit;
742 } else {
743 $ed->close_edit;
746 $pool->clear;
747 fatal "$@\n" if $@;
748 $_message = $_file = undef;
749 return $rev_committed;
752 ########################### utility functions #########################
754 sub cmt_showable {
755 my ($c) = @_;
756 return 1 if defined $c->{r};
757 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
758 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
759 my @msg = command(qw/cat-file commit/, $c->{c});
760 shift @msg while ($msg[0] ne "\n");
761 shift @msg;
762 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
764 (undef, $c->{r}, undef) = extract_metadata(
765 (grep(/^git-svn-id: /, @msg))[-1]);
767 return defined $c->{r};
770 sub log_use_color {
771 return 1 if $_color;
772 my ($dc, $dcvar);
773 $dcvar = 'color.diff';
774 $dc = `git-config --get $dcvar`;
775 if ($dc eq '') {
776 # nothing at all; fallback to "diff.color"
777 $dcvar = 'diff.color';
778 $dc = `git-config --get $dcvar`;
780 chomp($dc);
781 if ($dc eq 'auto') {
782 my $pc;
783 $pc = `git-config --get color.pager`;
784 if ($pc eq '') {
785 # does not have it -- fallback to pager.color
786 $pc = `git-config --bool --get pager.color`;
788 else {
789 $pc = `git-config --bool --get color.pager`;
790 if ($?) {
791 $pc = 'false';
794 chomp($pc);
795 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
796 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
798 return 0;
800 return 0 if $dc eq 'never';
801 return 1 if $dc eq 'always';
802 chomp($dc = `git-config --bool --get $dcvar`);
803 return ($dc eq 'true');
806 sub git_svn_log_cmd {
807 my ($r_min, $r_max) = @_;
808 my @cmd = (qw/log --abbrev-commit --pretty=raw
809 --default/, "refs/remotes/$GIT_SVN");
810 push @cmd, '-r' unless $_non_recursive;
811 push @cmd, qw/--raw --name-status/ if $_verbose;
812 push @cmd, '--color' if log_use_color();
813 return @cmd unless defined $r_max;
814 if ($r_max == $r_min) {
815 push @cmd, '--max-count=1';
816 if (my $c = revdb_get($REVDB, $r_max)) {
817 push @cmd, $c;
819 } else {
820 my ($c_min, $c_max);
821 $c_max = revdb_get($REVDB, $r_max);
822 $c_min = revdb_get($REVDB, $r_min);
823 if (defined $c_min && defined $c_max) {
824 if ($r_max > $r_max) {
825 push @cmd, "$c_min..$c_max";
826 } else {
827 push @cmd, "$c_max..$c_min";
829 } elsif ($r_max > $r_min) {
830 push @cmd, $c_max;
831 } else {
832 push @cmd, $c_min;
835 return @cmd;
838 sub fetch_child_id {
839 my $id = shift;
840 print "Fetching $id\n";
841 my $ref = "$GIT_DIR/refs/remotes/$id";
842 defined(my $pid = open my $fh, '-|') or croak $!;
843 if (!$pid) {
844 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
845 init_vars();
846 fetch(@_);
847 exit 0;
849 while (<$fh>) {
850 print $_;
851 check_repack() if (/^r\d+ = $sha1/o);
853 close $fh or croak $?;
856 sub rec_fetch {
857 my ($pfx, $p, @args) = @_;
858 my @dir;
859 foreach (sort <$p/*>) {
860 if (-r "$_/info/url") {
861 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
862 my $id = $pfx . basename $_;
863 next if $id eq 'trunk';
864 fetch_child_id($id, @args);
865 } elsif (-d $_) {
866 push @dir, $_;
869 foreach (@dir) {
870 my $x = $_;
871 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
872 rec_fetch($x, $_);
876 sub complete_svn_url {
877 my ($url, $path) = @_;
878 $path =~ s#/+$##;
879 $url =~ s#/+$## if $url;
880 if ($path !~ m#^[a-z\+]+://#) {
881 $path = '/' . $path if ($path !~ m#^/#);
882 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
883 fatal("E: '$path' is not a complete URL ",
884 "and a separate URL is not specified\n");
886 $path = $url . $path;
888 return $path;
891 sub complete_url_ls_init {
892 my ($ra, $path, $switch, $pfx) = @_;
893 unless ($path) {
894 print STDERR "W: $switch not specified\n";
895 return;
897 $path =~ s#/+$##;
898 if ($path =~ m#^[a-z\+]+://#) {
899 $ra = Git::SVN::Ra->new($path);
900 $path = '';
901 } else {
902 $path =~ s#^/+##;
903 unless ($ra) {
904 fatal("E: '$path' is not a complete URL ",
905 "and a separate URL is not specified\n");
908 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
909 my ($dirent, undef, undef) = $ra->get_dir($path, $r);
910 my $url = $ra->{url} . (length $path ? "/$path" : '');
911 foreach my $d (sort keys %$dirent) {
912 next if ($dirent->{$d}->kind != $SVN::Node::dir);
913 my $u = "$url/$d";
914 my $id = "$pfx$d";
915 my $gs = eval { Git::SVN->new($id) };
916 # don't try to init already existing refs
917 unless ($gs) {
918 print "init $u => $id\n";
919 Git::SVN->init($id, $u);
922 my ($n) = ($switch =~ /^--(\w+)/);
923 command_noisy('config', "svn.$n", $url);
926 sub common_prefix {
927 my $paths = shift;
928 my %common;
929 foreach (@$paths) {
930 my @tmp = split m#/#, $_;
931 my $p = '';
932 while (my $x = shift @tmp) {
933 $p .= "/$x";
934 $common{$p} ||= 0;
935 $common{$p}++;
938 foreach (sort {length $b <=> length $a} keys %common) {
939 if ($common{$_} == @$paths) {
940 return $_;
943 return '';
946 # grafts set here are 'stronger' in that they're based on actual tree
947 # matches, and won't be deleted from merge-base checking in write_grafts()
948 sub graft_tree_joins {
949 my $grafts = shift;
950 map_tree_joins() if (@_branch_from && !%tree_map);
951 return unless %tree_map;
953 git_svn_each(sub {
954 my $i = shift;
955 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
956 my ($fh, $ctx) = command_output_pipe(@args);
957 while (<$fh>) {
958 next unless /^commit ($sha1)$/o;
959 my $c = $1;
960 my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
961 next unless $tree_map{$t};
963 my $l;
964 do {
965 $l = readline $fh;
966 } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
968 my ($s, $tz) = ($1, $2);
969 if ($tz =~ s/^\+//) {
970 $s += tz_to_s_offset($tz);
971 } elsif ($tz =~ s/^\-//) {
972 $s -= tz_to_s_offset($tz);
975 my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
977 foreach my $p (@{$tree_map{$t}}) {
978 next if $p eq $c;
979 my $mb = eval { command('merge-base', $c, $p) };
980 next unless ($@ || $?);
981 if (defined $r_a) {
982 # see if SVN says it's a relative
983 my ($url_b, $r_b, $uuid_b) =
984 cmt_metadata($p);
985 next if (defined $url_b &&
986 defined $url_a &&
987 ($url_a eq $url_b) &&
988 ($uuid_a eq $uuid_b));
989 if ($uuid_a eq $uuid_b) {
990 if ($r_b < $r_a) {
991 $grafts->{$c}->{$p} = 2;
992 next;
993 } elsif ($r_b > $r_a) {
994 $grafts->{$p}->{$c} = 2;
995 next;
999 my $ct = get_commit_time($p);
1000 if ($ct < $s) {
1001 $grafts->{$c}->{$p} = 2;
1002 } elsif ($ct > $s) {
1003 $grafts->{$p}->{$c} = 2;
1005 # what should we do when $ct == $s ?
1008 command_close_pipe($fh, $ctx);
1012 sub graft_file_copy_lib {
1013 my ($grafts, $l_map, $u) = @_;
1014 my $tree_paths = $l_map->{$u};
1015 my $pfx = common_prefix([keys %$tree_paths]);
1016 my ($repo, $path) = repo_path_split($u.$pfx);
1017 $SVN = Git::SVN::Ra->new($repo);
1019 my ($base, $head) = libsvn_parse_revision();
1020 my $inc = 1000;
1021 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1022 my $eh = $SVN::Error::handler;
1023 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1024 while (1) {
1025 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
1026 sub {
1027 libsvn_graft_file_copies($grafts, $tree_paths,
1028 $path, @_);
1030 last if ($max >= $head);
1031 $min = $max + 1;
1032 $max += $inc;
1033 $max = $head if ($max > $head);
1035 $SVN::Error::handler = $eh;
1038 sub process_merge_msg_matches {
1039 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1040 my (@strong, @weak);
1041 foreach (@matches) {
1042 # merging with ourselves is not interesting
1043 next if $_ eq $p;
1044 if ($l_map->{$u}->{$_}) {
1045 push @strong, $_;
1046 } else {
1047 push @weak, $_;
1050 foreach my $w (@weak) {
1051 last if @strong;
1052 # no exact match, use branch name as regexp.
1053 my $re = qr/\Q$w\E/i;
1054 foreach (keys %{$l_map->{$u}}) {
1055 if (/$re/) {
1056 push @strong, $l_map->{$u}->{$_};
1057 last;
1060 last if @strong;
1061 $w = basename($w);
1062 $re = qr/\Q$w\E/i;
1063 foreach (keys %{$l_map->{$u}}) {
1064 if (/$re/) {
1065 push @strong, $l_map->{$u}->{$_};
1066 last;
1070 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1071 \s(?:[a-f\d\-]+)$/xsm);
1072 unless (defined $rev) {
1073 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1074 \@(?:[a-f\d\-]+)/xsm);
1075 return unless defined $rev;
1077 foreach my $m (@strong) {
1078 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1079 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1083 sub graft_merge_msg {
1084 my ($grafts, $l_map, $u, $p, @re) = @_;
1086 my $x = $l_map->{$u}->{$p};
1087 my $rl = rev_list_raw("refs/remotes/$x");
1088 while (my $c = next_rev_list_entry($rl)) {
1089 foreach my $re (@re) {
1090 my (@br) = ($c->{m} =~ /$re/g);
1091 next unless @br;
1092 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1097 sub verify_ref {
1098 my ($ref) = @_;
1099 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1100 { STDERR => 0 }); };
1103 sub repo_path_split {
1104 my $full_url = shift;
1105 $full_url =~ s#/+$##;
1107 foreach (@repo_path_split_cache) {
1108 if ($full_url =~ s#$_##) {
1109 my $u = $1;
1110 $full_url =~ s#^/+##;
1111 return ($u, $full_url);
1114 my $tmp = Git::SVN::Ra->new($full_url);
1115 return ($tmp->{repos_root}, $tmp->{svn_path});
1118 sub setup_git_svn {
1119 defined $SVN_URL or croak "SVN repository location required\n";
1120 unless (-d $GIT_DIR) {
1121 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1123 mkpath([$GIT_SVN_DIR]);
1124 mkpath(["$GIT_SVN_DIR/info"]);
1125 open my $fh, '>>',$REVDB or croak $!;
1126 close $fh;
1127 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1131 sub get_tree_from_treeish {
1132 my ($treeish) = @_;
1133 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1134 my $type = command_oneline(qw/cat-file -t/, $treeish);
1135 my $expected;
1136 while ($type eq 'tag') {
1137 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1139 if ($type eq 'commit') {
1140 $expected = (grep /^tree /, command(qw/cat-file commit/,
1141 $treeish))[0];
1142 ($expected) = ($expected =~ /^tree ($sha1)$/);
1143 die "Unable to get tree from $treeish\n" unless $expected;
1144 } elsif ($type eq 'tree') {
1145 $expected = $treeish;
1146 } else {
1147 die "$treeish is a $type, expected tree, tag or commit\n";
1149 return $expected;
1152 sub get_diff {
1153 my ($from, $treeish) = @_;
1154 print "diff-tree $from $treeish\n";
1155 my @diff_tree = qw(diff-tree -z -r);
1156 if ($_cp_similarity) {
1157 push @diff_tree, "-C$_cp_similarity";
1158 } else {
1159 push @diff_tree, '-C';
1161 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1162 push @diff_tree, "-l$_l" if defined $_l;
1163 push @diff_tree, $from, $treeish;
1164 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1165 local $/ = "\0";
1166 my $state = 'meta';
1167 my @mods;
1168 while (<$diff_fh>) {
1169 chomp $_; # this gets rid of the trailing "\0"
1170 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1171 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1172 push @mods, { mode_a => $1, mode_b => $2,
1173 sha1_b => $3, chg => $4 };
1174 if ($4 =~ /^(?:C|R)$/) {
1175 $state = 'file_a';
1176 } else {
1177 $state = 'file_b';
1179 } elsif ($state eq 'file_a') {
1180 my $x = $mods[$#mods] or croak "Empty array\n";
1181 if ($x->{chg} !~ /^(?:C|R)$/) {
1182 croak "Error parsing $_, $x->{chg}\n";
1184 $x->{file_a} = $_;
1185 $state = 'file_b';
1186 } elsif ($state eq 'file_b') {
1187 my $x = $mods[$#mods] or croak "Empty array\n";
1188 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1189 croak "Error parsing $_, $x->{chg}\n";
1191 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1192 croak "Error parsing $_, $x->{chg}\n";
1194 $x->{file_b} = $_;
1195 $state = 'meta';
1196 } else {
1197 croak "Error parsing $_\n";
1200 command_close_pipe($diff_fh, $ctx);
1201 return \@mods;
1204 sub libsvn_checkout_tree {
1205 my ($from, $treeish, $ed) = @_;
1206 my $mods = get_diff($from, $treeish);
1207 return $mods unless (scalar @$mods);
1208 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1209 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1210 my $f = $m->{chg};
1211 if (defined $o{$f}) {
1212 $ed->$f($m, $_q);
1213 } else {
1214 croak "Invalid change type: $f\n";
1217 $ed->rmdirs($_q) if $_rmdir;
1218 return $mods;
1221 sub get_commit_message {
1222 my ($commit, $commit_msg) = (@_);
1223 my %log_msg = ( msg => '' );
1224 open my $msg, '>', $commit_msg or croak $!;
1226 my $type = command_oneline(qw/cat-file -t/, $commit);
1227 if ($type eq 'commit' || $type eq 'tag') {
1228 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1229 $type, $commit);
1230 my $in_msg = 0;
1231 while (<$msg_fh>) {
1232 if (!$in_msg) {
1233 $in_msg = 1 if (/^\s*$/);
1234 } elsif (/^git-svn-id: /) {
1235 # skip this, we regenerate the correct one
1236 # on re-fetch anyways
1237 } else {
1238 print $msg $_ or croak $!;
1241 command_close_pipe($msg_fh, $ctx);
1243 close $msg or croak $!;
1245 if ($_edit || ($type eq 'tree')) {
1246 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1247 system($editor, $commit_msg);
1250 # file_to_s removes all trailing newlines, so just use chomp() here:
1251 open $msg, '<', $commit_msg or croak $!;
1252 { local $/; chomp($log_msg{msg} = <$msg>); }
1253 close $msg or croak $!;
1255 return \%log_msg;
1258 sub set_svn_commit_env {
1259 if (defined $LC_ALL) {
1260 $ENV{LC_ALL} = $LC_ALL;
1261 } else {
1262 delete $ENV{LC_ALL};
1266 sub rev_list_raw {
1267 my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1268 return { fh => $fh, ctx => $c, t => { } };
1271 sub next_rev_list_entry {
1272 my $rl = shift;
1273 my $fh = $rl->{fh};
1274 my $x = $rl->{t};
1275 while (<$fh>) {
1276 if (/^commit ($sha1)$/o) {
1277 if ($x->{c}) {
1278 $rl->{t} = { c => $1 };
1279 return $x;
1280 } else {
1281 $x->{c} = $1;
1283 } elsif (/^parent ($sha1)$/o) {
1284 $x->{p}->{$1} = 1;
1285 } elsif (s/^ //) {
1286 $x->{m} ||= '';
1287 $x->{m} .= $_;
1290 command_close_pipe($fh, $rl->{ctx});
1291 return ($x != $rl->{t}) ? $x : undef;
1294 sub s_to_file {
1295 my ($str, $file, $mode) = @_;
1296 open my $fd,'>',$file or croak $!;
1297 print $fd $str,"\n" or croak $!;
1298 close $fd or croak $!;
1299 chmod ($mode &~ umask, $file) if (defined $mode);
1302 sub file_to_s {
1303 my $file = shift;
1304 open my $fd,'<',$file or croak "$!: file: $file\n";
1305 local $/;
1306 my $ret = <$fd>;
1307 close $fd or croak $!;
1308 $ret =~ s/\s*$//s;
1309 return $ret;
1312 sub assert_revision_unknown {
1313 my $r = shift;
1314 if (my $c = revdb_get($REVDB, $r)) {
1315 croak "$r = $c already exists! Why are we refetching it?";
1319 sub git_commit {
1320 my ($log_msg, @parents) = @_;
1321 assert_revision_unknown($log_msg->{revision});
1322 map_tree_joins() if (@_branch_from && !%tree_map);
1324 my (@tmp_parents, @exec_parents, %seen_parent);
1325 if (my $lparents = $log_msg->{parents}) {
1326 @tmp_parents = @$lparents
1328 # commit parents can be conditionally bound to a particular
1329 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1330 foreach my $p (@parents) {
1331 next unless defined $p;
1332 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1333 if ($1 == $log_msg->{revision}) {
1334 push @tmp_parents, $2;
1336 } else {
1337 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1340 my $tree = $log_msg->{tree};
1341 if (!defined $tree) {
1342 my $index = set_index($GIT_SVN_INDEX);
1343 $tree = command_oneline('write-tree');
1344 croak $? if $?;
1345 restore_index($index);
1347 # just in case we clobber the existing ref, we still want that ref
1348 # as our parent:
1349 if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1350 chomp $cur;
1351 push @tmp_parents, $cur;
1354 if (exists $tree_map{$tree}) {
1355 foreach my $p (@{$tree_map{$tree}}) {
1356 my $skip;
1357 foreach (@tmp_parents) {
1358 # see if a common parent is found
1359 my $mb = eval { command('merge-base', $_, $p) };
1360 next if ($@ || $?);
1361 $skip = 1;
1362 last;
1364 next if $skip;
1365 my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1366 next if (($SVN->uuid eq $uuid_p) &&
1367 ($log_msg->{revision} > $r_p));
1368 next if (defined $url_p && defined $SVN_URL &&
1369 ($SVN->uuid eq $uuid_p) &&
1370 ($url_p eq $SVN_URL));
1371 push @tmp_parents, $p;
1374 foreach (@tmp_parents) {
1375 next if $seen_parent{$_};
1376 $seen_parent{$_} = 1;
1377 push @exec_parents, $_;
1378 # MAXPARENT is defined to 16 in commit-tree.c:
1379 last if @exec_parents > 16;
1382 set_commit_env($log_msg);
1383 my @exec = ('git-commit-tree', $tree);
1384 push @exec, '-p', $_ foreach @exec_parents;
1385 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1386 or croak $!;
1387 print $msg_fh $log_msg->{msg} or croak $!;
1388 unless ($_no_metadata) {
1389 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1390 $SVN->uuid,"\n" or croak $!;
1392 $msg_fh->flush == 0 or croak $!;
1393 close $msg_fh or croak $!;
1394 chomp(my $commit = do { local $/; <$out_fh> });
1395 close $out_fh or croak $!;
1396 waitpid $pid, 0;
1397 croak $? if $?;
1398 if ($commit !~ /^$sha1$/o) {
1399 die "Failed to commit, invalid sha1: $commit\n";
1401 command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1402 revdb_set($REVDB, $log_msg->{revision}, $commit);
1404 # this output is read via pipe, do not change:
1405 print "r$log_msg->{revision} = $commit\n";
1406 return $commit;
1409 sub check_repack {
1410 if ($_repack && (--$_repack_nr == 0)) {
1411 $_repack_nr = $_repack;
1412 # repack doesn't use any arguments with spaces in them, does it?
1413 command_noisy('repack', split(/\s+/, $_repack_flags));
1417 sub set_commit_env {
1418 my ($log_msg) = @_;
1419 my $author = $log_msg->{author};
1420 if (!defined $author || length $author == 0) {
1421 $author = '(no author)';
1423 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1424 : ($author,$author . '@' . $SVN->uuid);
1425 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1426 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1427 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1430 sub check_upgrade_needed {
1431 if (!-r $REVDB) {
1432 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1433 open my $fh, '>>',$REVDB or croak $!;
1434 close $fh;
1436 return unless eval {
1437 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1438 {STDERR => 0});
1440 my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1441 if ($@ || !$head) {
1442 print STDERR "Please run: $0 rebuild --upgrade\n";
1443 exit 1;
1447 # fills %tree_map with a reverse mapping of trees to commits. Useful
1448 # for finding parents to commit on.
1449 sub map_tree_joins {
1450 my %seen;
1451 foreach my $br (@_branch_from) {
1452 my $pipe = command_output_pipe(qw/rev-list
1453 --topo-order --pretty=raw/, $br);
1454 while (<$pipe>) {
1455 if (/^commit ($sha1)$/o) {
1456 my $commit = $1;
1458 # if we've seen a commit,
1459 # we've seen its parents
1460 last if $seen{$commit};
1461 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1462 unless (defined $tree) {
1463 die "Failed to parse commit $commit\n";
1465 push @{$tree_map{$tree}}, $commit;
1466 $seen{$commit} = 1;
1469 close $pipe;
1473 sub load_all_refs {
1474 if (@_branch_from) {
1475 print STDERR '--branch|-b parameters are ignored when ',
1476 "--branch-all-refs|-B is passed\n";
1479 # don't worry about rev-list on non-commit objects/tags,
1480 # it shouldn't blow up if a ref is a blob or tree...
1481 @_branch_from = command(qw/rev-parse --symbolic --all/);
1484 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1485 sub load_authors {
1486 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1487 while (<$authors>) {
1488 chomp;
1489 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1490 my ($user, $name, $email) = ($1, $2, $3);
1491 $users{$user} = [$name, $email];
1493 close $authors or croak $!;
1496 sub rload_authors {
1497 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1498 while (<$authors>) {
1499 chomp;
1500 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1501 my ($user, $name, $email) = ($1, $2, $3);
1502 $rusers{"$name <$email>"} = $user;
1504 close $authors or croak $!;
1507 sub git_svn_each {
1508 my $sub = shift;
1509 foreach (command(qw/rev-parse --symbolic --all/)) {
1510 next unless s#^refs/remotes/##;
1511 chomp $_;
1512 next unless -f "$GIT_DIR/svn/$_/info/url";
1513 &$sub($_);
1517 sub migrate_revdb {
1518 git_svn_each(sub {
1519 my $id = shift;
1520 defined(my $pid = fork) or croak $!;
1521 if (!$pid) {
1522 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1523 init_vars();
1524 exit 0 if -r $REVDB;
1525 print "Upgrading svn => git mapping...\n";
1526 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1527 open my $fh, '>>',$REVDB or croak $!;
1528 close $fh;
1529 rebuild();
1530 print "Done upgrading. You may now delete the ",
1531 "deprecated $GIT_SVN_DIR/revs directory\n";
1532 exit 0;
1534 waitpid $pid, 0;
1535 croak $? if $?;
1539 sub migration_check {
1540 migrate_revdb() unless (-e $REVDB);
1541 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1542 print "Upgrading repository...\n";
1543 unless (-d "$GIT_DIR/svn") {
1544 mkdir "$GIT_DIR/svn" or croak $!;
1546 print "Data from a previous version of git-svn exists, but\n\t",
1547 "$GIT_SVN_DIR\n\t(required for this version ",
1548 "($VERSION) of git-svn) does not.\n";
1550 foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1551 next unless $x =~ s#^refs/remotes/##;
1552 chomp $x;
1553 next unless -f "$GIT_DIR/$x/info/url";
1554 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1555 next unless $u;
1556 my $dn = dirname("$GIT_DIR/svn/$x");
1557 mkpath([$dn]) unless -d $dn;
1558 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1560 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1561 print "Done upgrading.\n";
1564 sub find_rev_before {
1565 my ($r, $id, $eq_ok) = @_;
1566 my $f = "$GIT_DIR/svn/$id/.rev_db";
1567 return (undef,undef) unless -r $f;
1568 --$r unless $eq_ok;
1569 while ($r > 0) {
1570 if (my $c = revdb_get($f, $r)) {
1571 return ($r, $c);
1573 --$r;
1575 return (undef, undef);
1578 sub init_vars {
1579 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1580 $Git::SVN::default = $GIT_SVN;
1581 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1582 $REVDB = "$GIT_SVN_DIR/.rev_db";
1583 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1584 $SVN_URL = undef;
1585 %tree_map = ();
1588 # convert GetOpt::Long specs for use by git-config
1589 sub read_repo_config {
1590 return unless -d $GIT_DIR;
1591 my $opts = shift;
1592 foreach my $o (keys %$opts) {
1593 my $v = $opts->{$o};
1594 my ($key) = ($o =~ /^([a-z\-]+)/);
1595 $key =~ s/-//g;
1596 my $arg = 'git-config';
1597 $arg .= ' --int' if ($o =~ /[:=]i$/);
1598 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1599 if (ref $v eq 'ARRAY') {
1600 chomp(my @tmp = `$arg --get-all svn.$key`);
1601 @$v = @tmp if @tmp;
1602 } else {
1603 chomp(my $tmp = `$arg --get svn.$key`);
1604 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1605 $$v = $tmp;
1611 sub set_default_vals {
1612 if (defined $_repack) {
1613 $_repack = 1000 if ($_repack <= 0);
1614 $_repack_nr = $_repack;
1615 $_repack_flags ||= '-d';
1619 sub read_grafts {
1620 my $gr_file = shift;
1621 my ($grafts, $comments) = ({}, {});
1622 if (open my $fh, '<', $gr_file) {
1623 my @tmp;
1624 while (<$fh>) {
1625 if (/^($sha1)\s+/) {
1626 my $c = $1;
1627 if (@tmp) {
1628 @{$comments->{$c}} = @tmp;
1629 @tmp = ();
1631 foreach my $p (split /\s+/, $_) {
1632 $grafts->{$c}->{$p} = 1;
1634 } else {
1635 push @tmp, $_;
1638 close $fh or croak $!;
1639 @{$comments->{'END'}} = @tmp if @tmp;
1641 return ($grafts, $comments);
1644 sub write_grafts {
1645 my ($grafts, $comments, $gr_file) = @_;
1647 open my $fh, '>', $gr_file or croak $!;
1648 foreach my $c (sort keys %$grafts) {
1649 if ($comments->{$c}) {
1650 print $fh $_ foreach @{$comments->{$c}};
1652 my $p = $grafts->{$c};
1653 my %x; # real parents
1654 delete $p->{$c}; # commits are not self-reproducing...
1655 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1656 while (<$ch>) {
1657 if (/^parent ($sha1)/) {
1658 $x{$1} = $p->{$1} = 1;
1659 } else {
1660 last unless /^\S/;
1663 close $ch; # breaking the pipe
1665 # if real parents are the only ones in the grafts, drop it
1666 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1668 my (@ip, @jp, $mb);
1669 my %del = %x;
1670 @ip = @jp = keys %$p;
1671 foreach my $i (@ip) {
1672 next if $del{$i} || $p->{$i} == 2;
1673 foreach my $j (@jp) {
1674 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1675 $mb = eval { command('merge-base', $i, $j) };
1676 next unless $mb;
1677 chomp $mb;
1678 next if $x{$mb};
1679 if ($mb eq $j) {
1680 delete $p->{$i};
1681 $del{$i} = 1;
1682 } elsif ($mb eq $i) {
1683 delete $p->{$j};
1684 $del{$j} = 1;
1689 # if real parents are the only ones in the grafts, drop it
1690 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1692 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1694 if ($comments->{'END'}) {
1695 print $fh $_ foreach @{$comments->{'END'}};
1697 close $fh or croak $!;
1700 sub read_url_paths_all {
1701 my ($l_map, $pfx, $p) = @_;
1702 my @dir;
1703 foreach (<$p/*>) {
1704 if (-r "$_/info/url") {
1705 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1706 my $id = $pfx . basename $_;
1707 my $url = file_to_s("$_/info/url");
1708 my ($u, $p) = repo_path_split($url);
1709 $l_map->{$u}->{$p} = $id;
1710 } elsif (-d $_) {
1711 push @dir, $_;
1714 foreach (@dir) {
1715 my $x = $_;
1716 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1717 read_url_paths_all($l_map, $x, $_);
1721 # this one only gets ids that have been imported, not new ones
1722 sub read_url_paths {
1723 my $l_map = {};
1724 git_svn_each(sub { my $x = shift;
1725 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1726 my ($u, $p) = repo_path_split($url);
1727 $l_map->{$u}->{$p} = $x;
1729 return $l_map;
1732 sub extract_metadata {
1733 my $id = shift or return (undef, undef, undef);
1734 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1735 \s([a-f\d\-]+)$/x);
1736 if (!defined $rev || !$uuid || !$url) {
1737 # some of the original repositories I made had
1738 # identifiers like this:
1739 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1741 return ($url, $rev, $uuid);
1744 sub cmt_metadata {
1745 return extract_metadata((grep(/^git-svn-id: /,
1746 command(qw/cat-file commit/, shift)))[-1]);
1749 sub get_commit_time {
1750 my $cmt = shift;
1751 my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1752 while (<$fh>) {
1753 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1754 my ($s, $tz) = ($1, $2);
1755 if ($tz =~ s/^\+//) {
1756 $s += tz_to_s_offset($tz);
1757 } elsif ($tz =~ s/^\-//) {
1758 $s -= tz_to_s_offset($tz);
1760 close $fh;
1761 return $s;
1763 die "Can't get commit time for commit: $cmt\n";
1766 sub tz_to_s_offset {
1767 my ($tz) = @_;
1768 $tz =~ s/(\d\d)$//;
1769 return ($1 * 60) + ($tz * 3600);
1772 # adapted from pager.c
1773 sub config_pager {
1774 $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
1775 if (!defined $_pager) {
1776 $_pager = 'less';
1777 } elsif (length $_pager == 0 || $_pager eq 'cat') {
1778 $_pager = undef;
1782 sub run_pager {
1783 return unless -t *STDOUT;
1784 pipe my $rfd, my $wfd or return;
1785 defined(my $pid = fork) or croak $!;
1786 if (!$pid) {
1787 open STDOUT, '>&', $wfd or croak $!;
1788 return;
1790 open STDIN, '<&', $rfd or croak $!;
1791 $ENV{LESS} ||= 'FRSX';
1792 exec $_pager or croak "Can't run pager: $! ($_pager)\n";
1795 sub get_author_info {
1796 my ($dest, $author, $t, $tz) = @_;
1797 $author =~ s/(?:^\s*|\s*$)//g;
1798 $dest->{a_raw} = $author;
1799 my $_a;
1800 if ($_authors) {
1801 $_a = $rusers{$author} || undef;
1803 if (!$_a) {
1804 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
1806 $dest->{t} = $t;
1807 $dest->{tz} = $tz;
1808 $dest->{a} = $_a;
1809 # Date::Parse isn't in the standard Perl distro :(
1810 if ($tz =~ s/^\+//) {
1811 $t += tz_to_s_offset($tz);
1812 } elsif ($tz =~ s/^\-//) {
1813 $t -= tz_to_s_offset($tz);
1815 $dest->{t_utc} = $t;
1818 sub process_commit {
1819 my ($c, $r_min, $r_max, $defer) = @_;
1820 if (defined $r_min && defined $r_max) {
1821 if ($r_min == $c->{r} && $r_min == $r_max) {
1822 show_commit($c);
1823 return 0;
1825 return 1 if $r_min == $r_max;
1826 if ($r_min < $r_max) {
1827 # we need to reverse the print order
1828 return 0 if (defined $_limit && --$_limit < 0);
1829 push @$defer, $c;
1830 return 1;
1832 if ($r_min != $r_max) {
1833 return 1 if ($r_min < $c->{r});
1834 return 1 if ($r_max > $c->{r});
1837 return 0 if (defined $_limit && --$_limit < 0);
1838 show_commit($c);
1839 return 1;
1842 sub show_commit {
1843 my $c = shift;
1844 if ($_oneline) {
1845 my $x = "\n";
1846 if (my $l = $c->{l}) {
1847 while ($l->[0] =~ /^\s*$/) { shift @$l }
1848 $x = $l->[0];
1850 $_l_fmt ||= 'A' . length($c->{r});
1851 print 'r',pack($_l_fmt, $c->{r}),' | ';
1852 print "$c->{c} | " if $_show_commit;
1853 print $x;
1854 } else {
1855 show_commit_normal($c);
1859 sub show_commit_changed_paths {
1860 my ($c) = @_;
1861 return unless $c->{changed};
1862 print "Changed paths:\n", @{$c->{changed}};
1865 sub show_commit_normal {
1866 my ($c) = @_;
1867 print '-' x72, "\nr$c->{r} | ";
1868 print "$c->{c} | " if $_show_commit;
1869 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
1870 localtime($c->{t_utc})), ' | ';
1871 my $nr_line = 0;
1873 if (my $l = $c->{l}) {
1874 while ($l->[$#$l] eq "\n" && $#$l > 0
1875 && $l->[($#$l - 1)] eq "\n") {
1876 pop @$l;
1878 $nr_line = scalar @$l;
1879 if (!$nr_line) {
1880 print "1 line\n\n\n";
1881 } else {
1882 if ($nr_line == 1) {
1883 $nr_line = '1 line';
1884 } else {
1885 $nr_line .= ' lines';
1887 print $nr_line, "\n";
1888 show_commit_changed_paths($c);
1889 print "\n";
1890 print $_ foreach @$l;
1892 } else {
1893 print "1 line\n";
1894 show_commit_changed_paths($c);
1895 print "\n";
1898 foreach my $x (qw/raw diff/) {
1899 if ($c->{$x}) {
1900 print "\n";
1901 print $_ foreach @{$c->{$x}}
1906 package Git::SVN;
1907 use strict;
1908 use warnings;
1909 use vars qw/$default/;
1910 use Carp qw/croak/;
1911 use File::Path qw/mkpath/;
1912 use IPC::Open3;
1914 # properties that we do not log:
1915 my %SKIP_PROP;
1916 BEGIN {
1917 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1918 svn:special svn:executable
1919 svn:entry:committed-rev
1920 svn:entry:last-author
1921 svn:entry:uuid
1922 svn:entry:committed-date/;
1925 sub init {
1926 my ($class, $id, $url) = @_;
1927 my $self = _new($class, $id);
1928 mkpath(["$self->{dir}/info"]);
1929 if (defined $url) {
1930 $url =~ s!/+$!!; # strip trailing slash
1931 ::s_to_file($url, "$self->{dir}/info/url");
1933 $self->{url} = $url;
1934 open my $fh, '>>', $self->{db_path} or croak $!;
1935 close $fh or croak $!;
1936 $self;
1939 sub new {
1940 my ($class, $id) = @_;
1941 my $self = _new($class, $id);
1942 $self->{url} = ::file_to_s("$self->{dir}/info/url");
1943 $self;
1946 sub refname { "refs/remotes/$_[0]->{id}" }
1948 sub ra {
1949 my ($self) = shift;
1950 $self->{ra} ||= Git::SVN::Ra->new($self->{url});
1953 sub copy_remote_ref {
1954 my ($self) = @_;
1955 my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
1956 my $ref = $self->refname;
1957 if (command('ls-remote', $origin, $ref)) {
1958 command_noisy('fetch', $origin, "$ref:$ref");
1959 } elsif ($::_cp_remote && !$::_upgrade) {
1960 die "Unable to find remote reference: $ref on $origin\n";
1964 sub traverse_ignore {
1965 my ($self, $fh, $path, $r) = @_;
1966 $path =~ s#^/+##g;
1967 my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
1968 my $p = $path;
1969 $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
1970 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1971 if (my $s = $props->{'svn:ignore'}) {
1972 $s =~ s/[\r\n]+/\n/g;
1973 chomp $s;
1974 if (length $p == 0) {
1975 $s =~ s#\n#\n/$p#g;
1976 print $fh "/$s\n";
1977 } else {
1978 $s =~ s#\n#\n/$p/#g;
1979 print $fh "/$p/$s\n";
1982 foreach (sort keys %$dirent) {
1983 next if $dirent->{$_}->kind != $SVN::Node::dir;
1984 $self->traverse_ignore($fh, "$path/$_", $r);
1988 # returns the newest SVN revision number and newest commit SHA1
1989 sub last_rev_commit {
1990 my ($self) = @_;
1991 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1992 return ($self->{last_rev}, $self->{last_commit});
1994 my $c = ::verify_ref($self->refname.'^0');
1995 if (defined $c && length $c) {
1996 my $rev = (::cmt_metadata($c))[1];
1997 if (defined $rev) {
1998 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1999 return ($rev, $c);
2002 my $offset = -41; # from tail
2003 my $rl;
2004 open my $fh, '<', $self->{db_path} or
2005 croak "$self->{db_path} not readable: $!\n";
2006 seek $fh, $offset, 2;
2007 $rl = readline $fh;
2008 defined $rl or return (undef, undef);
2009 chomp $rl;
2010 while ($c ne $rl && tell $fh != 0) {
2011 $offset -= 41;
2012 seek $fh, $offset, 2;
2013 $rl = readline $fh;
2014 defined $rl or return (undef, undef);
2015 chomp $rl;
2017 my $rev = tell $fh;
2018 croak $! if ($rev < 0);
2019 $rev = ($rev - 41) / 41;
2020 close $fh or croak $!;
2021 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2022 return ($rev, $c);
2025 sub parse_revision {
2026 my ($self, $base) = @_;
2027 my $head = $self->ra->get_latest_revnum;
2028 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2029 return ($base + 1, $head) if (defined $base);
2030 return (0, $head);
2032 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2033 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2034 if ($::_revision =~ /^BASE:(\d+)$/) {
2035 return ($base + 1, $1) if (defined $base);
2036 return (0, $head);
2038 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2039 die "revision argument: $::_revision not understood by git-svn\n",
2040 "Try using the command-line svn client instead\n";
2043 sub tmp_index_do {
2044 my ($self, $sub) = @_;
2045 my $old_index = $ENV{GIT_INDEX_FILE};
2046 $ENV{GIT_INDEX_FILE} = $self->{index};
2047 my @ret = &$sub;
2048 if ($old_index) {
2049 $ENV{GIT_INDEX_FILE} = $old_index;
2050 } else {
2051 delete $ENV{GIT_INDEX_FILE};
2053 wantarray ? @ret : $ret[0];
2056 sub assert_index_clean {
2057 my ($self, $treeish) = @_;
2059 $self->tmp_index_do(sub {
2060 command_noisy('read-tree', $treeish) unless -e $self->{index};
2061 my $x = command_oneline('write-tree');
2062 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2063 /^tree ($::sha1)/mo);
2064 if ($y ne $x) {
2065 unlink $self->{index} or croak $!;
2066 command_noisy('read-tree', $treeish);
2068 $x = command_oneline('write-tree');
2069 if ($y ne $x) {
2070 ::fatal "trees ($treeish) $y != $x\n",
2071 "Something is seriously wrong...\n";
2076 sub get_commit_parents {
2077 my ($self, $log_msg, @parents) = @_;
2078 my (%seen, @ret, @tmp);
2079 # commit parents can be conditionally bound to a particular
2080 # svn revision via: "svn_revno=commit_sha1", filter them out here:
2081 foreach my $p (@parents) {
2082 next unless defined $p;
2083 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
2084 push @tmp, $2 if $1 == $log_msg->{revision};
2085 } else {
2086 push @tmp, $p if $p =~ /^$::sha1_short$/o;
2089 if (my $cur = ::verify_ref($self->refname.'^0')) {
2090 push @tmp, $cur;
2092 push @tmp, $_ foreach (@{$log_msg->{parents}}, @tmp);
2093 while (my $p = shift @tmp) {
2094 next if $seen{$p};
2095 $seen{$p} = 1;
2096 push @ret, $p;
2097 # MAXPARENT is defined to 16 in commit-tree.c:
2098 last if @ret >= 16;
2100 if (@tmp) {
2101 die "r$log_msg->{revision}: No room for parents:\n\t",
2102 join("\n\t", @tmp), "\n";
2104 @ret;
2107 sub check_upgrade_needed {
2108 my ($self) = @_;
2109 if (!-r $self->{db_path}) {
2110 -d $self->{dir} or mkpath([$self->{dir}]);
2111 open my $fh, '>>', $self->{db_path} or croak $!;
2112 close $fh;
2114 return unless ::verify_ref($self->{id}.'-HEAD^0');
2115 my $head = ::verify_ref($self->refname.'^0');
2116 if ($@ || !$head) {
2117 ::fatal("Please run: $0 rebuild --upgrade\n");
2121 sub do_git_commit {
2122 my ($self, $log_msg, @parents) = @_;
2123 if (my $c = $self->rev_db_get($log_msg->{revision})) {
2124 croak "$log_msg->{revision} = $c already exists! ",
2125 "Why are we refetching it?\n";
2127 my ($name, $email) = ::author_name_email($log_msg->{author}, $self->ra);
2128 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2129 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2130 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2132 my $tree = $log_msg->{tree};
2133 if (!defined $tree) {
2134 $tree = $self->tmp_index_do(sub {
2135 command_oneline('write-tree') });
2137 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2139 my @exec = ('git-commit-tree', $tree);
2140 foreach ($self->get_commit_parents($log_msg, @parents)) {
2141 push @exec, '-p', $_;
2143 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2144 or croak $!;
2145 print $msg_fh $log_msg->{log} or croak $!;
2146 print $msg_fh "\ngit-svn-id: $self->{ra}->{url}\@$log_msg->{revision}",
2147 " ", $self->ra->uuid,"\n" or croak $!;
2148 $msg_fh->flush == 0 or croak $!;
2149 close $msg_fh or croak $!;
2150 chomp(my $commit = do { local $/; <$out_fh> });
2151 close $out_fh or croak $!;
2152 waitpid $pid, 0;
2153 croak $? if $?;
2154 if ($commit !~ /^$::sha1$/o) {
2155 die "Failed to commit, invalid sha1: $commit\n";
2158 command_noisy('update-ref',$self->refname, $commit);
2159 $self->rev_db_set($log_msg->{revision}, $commit);
2161 $self->{last_rev} = $log_msg->{revision};
2162 $self->{last_commit} = $commit;
2163 print "r$log_msg->{revision} = $commit\n";
2164 return $commit;
2167 sub do_fetch {
2168 my ($self, $paths, $rev) = @_; #, $author, $date, $msg) = @_;
2169 my $ed = SVN::Git::Fetcher->new($self);
2170 my ($last_rev, @parents);
2171 if ($self->{last_commit}) {
2172 $last_rev = $self->{last_rev};
2173 $ed->{c} = $self->{last_commit};
2174 @parents = ($self->{last_commit});
2175 } else {
2176 $last_rev = $rev;
2178 unless ($self->ra->do_update($last_rev, $rev, '', 1, $ed)) {
2179 die "SVN connection failed somewhere...\n";
2181 $self->make_log_entry($rev, \@parents, $ed);
2184 sub write_untracked {
2185 my ($self, $rev, $fh, $untracked) = @_;
2186 my $h;
2187 print $fh "r$rev\n" or croak $!;
2188 $h = $untracked->{empty};
2189 foreach (sort keys %$h) {
2190 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2191 print $fh " $act: ", uri_encode($_), "\n" or croak $!;
2192 warn "W: $act: $_\n";
2194 foreach my $t (qw/dir_prop file_prop/) {
2195 $h = $untracked->{$t} or next;
2196 foreach my $path (sort keys %$h) {
2197 my $ppath = $path eq '' ? '.' : $path;
2198 foreach my $prop (sort keys %{$h->{$path}}) {
2199 next if $SKIP{$prop};
2200 my $v = $h->{$path}->{$prop};
2201 if (defined $v) {
2202 print $fh " +$t: ",
2203 uri_encode($ppath), ' ',
2204 uri_encode($prop), ' ',
2205 uri_encode($v), "\n"
2206 or croak $!;
2207 } else {
2208 print $fh " -$t: ",
2209 uri_encode($ppath), ' ',
2210 uri_encode($prop), "\n"
2211 or croak $!;
2216 foreach my $t (qw/absent_file absent_directory/) {
2217 $h = $untracked->{$t} or next;
2218 foreach my $parent (sort keys %$h) {
2219 foreach my $path (sort @{$h->{$parent}}) {
2220 print $fh " $t: ",
2221 uri_encode("$parent/$path"), "\n"
2222 or croak $!;
2223 warn "W: $t: $parent/$path ",
2224 "Insufficient permissions?\n";
2230 sub make_log_entry {
2231 my ($self, $rev, $parents, $untracked) = @_;
2232 my $rp = $self->ra->rev_proplist($rev);
2233 my %log_entry = ( parents => $parents || [], revision => $rev,
2234 revprops => $rp, log => '');
2235 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2236 $self->write_untracked($rev, $un, $untracked);
2237 foreach (sort keys %$rp) {
2238 my $v = $rp->{$_};
2239 if (/^svn:(author|date|log)$/) {
2240 $log_entry{$1} = $v;
2241 } else {
2242 print $un " rev_prop: ", uri_encode($_), ' ',
2243 uri_encode($v), "\n";
2246 close $un or croak $!;
2247 $log_entry{date} = parse_svn_date($log_entry{date});
2248 $log_entry{author} = check_author($log_entry{author});
2249 $log_entry{log} .= "\n";
2250 \%log_entry;
2253 sub fetch {
2254 my ($self, @parents) = @_;
2255 my ($last_rev, $last_commit) = $self->last_rev_commit;
2256 my ($base, $head) = $self->parse_revision($last_rev);
2257 return if ($base > $head);
2258 if (defined $last_commit) {
2259 $self->assert_index_clean($last_commit);
2261 my $inc = 1000;
2262 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2263 my $err_handler = $SVN::Error::handler;
2264 $SVN::Error::handler = \&skip_unknown_revs;
2265 while (1) {
2266 my @revs;
2267 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
2268 my ($paths, $rev, $author, $date, $msg) = @_;
2269 push @revs, $rev });
2270 foreach (@revs) {
2271 my $log_entry = $self->do_fetch(undef, $_);
2272 $self->do_git_commit($log_entry, @parents);
2274 last if $max >= $head;
2275 $min = $max + 1;
2276 $max += $inc;
2277 $max = $head if ($max > $head);
2279 $SVN::Error::handler = $err_handler;
2282 sub set_tree_cb {
2283 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2284 # TODO: enable and test optimized commits:
2285 if (0 && $rev == ($self->{last_rev} + 1)) {
2286 $log_entry->{revision} = $rev;
2287 $log_entry->{author} = $author;
2288 $self->do_git_commit($log_entry, "$rev=$tree");
2289 } else {
2290 $self->fetch("$rev=$tree");
2294 sub set_tree {
2295 my ($self, $tree) = (shift, shift);
2296 my $log_entry = get_commit_entry($tree);
2297 unless ($self->{last_rev}) {
2298 fatal("Must have an existing revision to commit\n");
2300 my $pool = SVN::Pool->new;
2301 my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
2302 ra => $self->ra->dup,
2303 c => $tree,
2304 svn_path => $self->ra->{svn_path}
2306 $self->ra->get_commit_editor(
2307 $log_entry->{log}, sub {
2308 $self->set_tree_cb($log_entry,
2309 $tree, @_);
2311 $pool);
2312 my $mods = $ed->apply_diff($self->{last_commit}, $tree);
2313 if (@$mods == 0) {
2314 print "No changes\nr$self->{last_rev} = $tree\n";
2316 $pool->clear;
2319 sub skip_unknown_revs {
2320 my ($err) = @_;
2321 my $errno = $err->apr_err();
2322 # Maybe the branch we're tracking didn't
2323 # exist when the repo started, so it's
2324 # not an error if it doesn't, just continue
2326 # Wonderfully consistent library, eh?
2327 # 160013 - svn:// and file://
2328 # 175002 - http(s)://
2329 # 175007 - http(s):// (this repo required authorization, too...)
2330 # More codes may be discovered later...
2331 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2332 return;
2334 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2337 # rev_db:
2338 # Tie::File seems to be prone to offset errors if revisions get sparse,
2339 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2340 # one of my favorite modules is out :< Next up would be one of the DBM
2341 # modules, but I'm not sure which is most portable... So I'll just
2342 # go with something that's plain-text, but still capable of
2343 # being randomly accessed. So here's my ultra-simple fixed-width
2344 # database. All records are 40 characters + "\n", so it's easy to seek
2345 # to a revision: (41 * rev) is the byte offset.
2346 # A record of 40 0s denotes an empty revision.
2347 # And yes, it's still pretty fast (faster than Tie::File).
2349 sub rev_db_set {
2350 my ($self, $rev, $commit) = @_;
2351 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2352 open my $fh, '+<', $self->{db_path} or croak $!;
2353 my $offset = $rev * 41;
2354 # assume that append is the common case:
2355 seek $fh, 0, 2 or croak $!;
2356 my $pos = tell $fh;
2357 if ($pos < $offset) {
2358 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
2359 or croak $!;
2361 seek $fh, $offset, 0 or croak $!;
2362 print $fh $commit,"\n" or croak $!;
2363 close $fh or croak $!;
2366 sub rev_db_get {
2367 my ($self, $rev) = @_;
2368 my $ret;
2369 my $offset = $rev * 41;
2370 open my $fh, '<', $self->{db_path} or croak $!;
2371 if (seek $fh, $offset, 0) {
2372 $ret = readline $fh;
2373 if (defined $ret) {
2374 chomp $ret;
2375 $ret = undef if ($ret =~ /^0{40}$/);
2378 close $fh or croak $!;
2379 $ret;
2382 sub _new {
2383 my ($class, $id) = @_;
2384 $id ||= $Git::SVN::default;
2385 my $dir = "$ENV{GIT_DIR}/svn/$id";
2386 bless { id => $id, dir => $dir, index => "$dir/index",
2387 db_path => "$dir/.rev_db" }, $class;
2391 package Git::SVN::Prompt;
2392 use strict;
2393 use warnings;
2394 require SVN::Core;
2395 use vars qw/$_no_auth_cache $_username/;
2397 sub simple {
2398 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2399 $may_save = undef if $_no_auth_cache;
2400 $default_username = $_username if defined $_username;
2401 if (defined $default_username && length $default_username) {
2402 if (defined $realm && length $realm) {
2403 print STDERR "Authentication realm: $realm\n";
2404 STDERR->flush;
2406 $cred->username($default_username);
2407 } else {
2408 username($cred, $realm, $may_save, $pool);
2410 $cred->password(_read_password("Password for '" .
2411 $cred->username . "': ", $realm));
2412 $cred->may_save($may_save);
2413 $SVN::_Core::SVN_NO_ERROR;
2416 sub ssl_server_trust {
2417 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2418 $may_save = undef if $_no_auth_cache;
2419 print STDERR "Error validating server certificate for '$realm':\n";
2420 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2421 print STDERR " - The certificate is not issued by a trusted ",
2422 "authority. Use the\n",
2423 " fingerprint to validate the certificate manually!\n";
2425 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2426 print STDERR " - The certificate hostname does not match.\n";
2428 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2429 print STDERR " - The certificate is not yet valid.\n";
2431 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2432 print STDERR " - The certificate has expired.\n";
2434 if ($failures & $SVN::Auth::SSL::OTHER) {
2435 print STDERR " - The certificate has an unknown error.\n";
2437 printf STDERR
2438 "Certificate information:\n".
2439 " - Hostname: %s\n".
2440 " - Valid: from %s until %s\n".
2441 " - Issuer: %s\n".
2442 " - Fingerprint: %s\n",
2443 map $cert_info->$_, qw(hostname valid_from valid_until
2444 issuer_dname fingerprint);
2445 my $choice;
2446 prompt:
2447 print STDERR $may_save ?
2448 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2449 "(R)eject or accept (t)emporarily? ";
2450 STDERR->flush;
2451 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2452 if ($choice =~ /^t$/i) {
2453 $cred->may_save(undef);
2454 } elsif ($choice =~ /^r$/i) {
2455 return -1;
2456 } elsif ($may_save && $choice =~ /^p$/i) {
2457 $cred->may_save($may_save);
2458 } else {
2459 goto prompt;
2461 $cred->accepted_failures($failures);
2462 $SVN::_Core::SVN_NO_ERROR;
2465 sub ssl_client_cert {
2466 my ($cred, $realm, $may_save, $pool) = @_;
2467 $may_save = undef if $_no_auth_cache;
2468 print STDERR "Client certificate filename: ";
2469 STDERR->flush;
2470 chomp(my $filename = <STDIN>);
2471 $cred->cert_file($filename);
2472 $cred->may_save($may_save);
2473 $SVN::_Core::SVN_NO_ERROR;
2476 sub ssl_client_cert_pw {
2477 my ($cred, $realm, $may_save, $pool) = @_;
2478 $may_save = undef if $_no_auth_cache;
2479 $cred->password(_read_password("Password: ", $realm));
2480 $cred->may_save($may_save);
2481 $SVN::_Core::SVN_NO_ERROR;
2484 sub username {
2485 my ($cred, $realm, $may_save, $pool) = @_;
2486 $may_save = undef if $_no_auth_cache;
2487 if (defined $realm && length $realm) {
2488 print STDERR "Authentication realm: $realm\n";
2490 my $username;
2491 if (defined $_username) {
2492 $username = $_username;
2493 } else {
2494 print STDERR "Username: ";
2495 STDERR->flush;
2496 chomp($username = <STDIN>);
2498 $cred->username($username);
2499 $cred->may_save($may_save);
2500 $SVN::_Core::SVN_NO_ERROR;
2503 sub _read_password {
2504 my ($prompt, $realm) = @_;
2505 print STDERR $prompt;
2506 STDERR->flush;
2507 require Term::ReadKey;
2508 Term::ReadKey::ReadMode('noecho');
2509 my $password = '';
2510 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2511 last if $key =~ /[\012\015]/; # \n\r
2512 $password .= $key;
2514 Term::ReadKey::ReadMode('restore');
2515 print STDERR "\n";
2516 STDERR->flush;
2517 $password;
2520 package main;
2522 sub uri_encode {
2523 my ($f) = @_;
2524 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2528 sub uri_decode {
2529 my ($f) = @_;
2530 $f =~ tr/+/ /;
2531 $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2535 sub libsvn_log_entry {
2536 my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2537 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2538 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2539 or die "Unable to parse date: $date\n";
2540 if (defined $author && length $author > 0 &&
2541 defined $_authors && ! defined $users{$author}) {
2542 die "Author: $author not defined in $_authors file\n";
2544 $msg = '' if ($rev == 0 && !defined $msg);
2546 open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2547 my $h;
2548 print $un "r$rev\n" or croak $!;
2549 $h = $untracked->{empty};
2550 foreach (sort keys %$h) {
2551 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2552 print $un " $act: ", uri_encode($_), "\n" or croak $!;
2553 warn "W: $act: $_\n";
2555 foreach my $t (qw/dir_prop file_prop/) {
2556 $h = $untracked->{$t} or next;
2557 foreach my $path (sort keys %$h) {
2558 my $ppath = $path eq '' ? '.' : $path;
2559 foreach my $prop (sort keys %{$h->{$path}}) {
2560 next if $SKIP{$prop};
2561 my $v = $h->{$path}->{$prop};
2562 if (defined $v) {
2563 print $un " +$t: ",
2564 uri_encode($ppath), ' ',
2565 uri_encode($prop), ' ',
2566 uri_encode($v), "\n"
2567 or croak $!;
2568 } else {
2569 print $un " -$t: ",
2570 uri_encode($ppath), ' ',
2571 uri_encode($prop), "\n"
2572 or croak $!;
2577 foreach my $t (qw/absent_file absent_directory/) {
2578 $h = $untracked->{$t} or next;
2579 foreach my $parent (sort keys %$h) {
2580 foreach my $path (sort @{$h->{$parent}}) {
2581 print $un " $t: ",
2582 uri_encode("$parent/$path"), "\n"
2583 or croak $!;
2584 warn "W: $t: $parent/$path ",
2585 "Insufficient permissions?\n";
2590 # revprops (make this optional? it's an extra network trip...)
2591 my $rp = $SVN->rev_proplist($rev);
2592 foreach (sort keys %$rp) {
2593 next if /^svn:(?:author|date|log)$/;
2594 print $un " rev_prop: ", uri_encode($_), ' ',
2595 uri_encode($rp->{$_}), "\n";
2597 close $un or croak $!;
2599 { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2600 author => $author, msg => $msg."\n", parents => $parents || [],
2601 revprops => $rp }
2604 sub libsvn_fetch {
2605 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2606 my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2607 my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2608 unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2609 die "SVN connection failed somewhere...\n";
2611 libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2614 sub svn_grab_base_rev {
2615 my $c = eval { command_oneline([qw/rev-parse --verify/,
2616 "refs/remotes/$GIT_SVN^0"],
2617 { STDERR => 0 }) };
2618 if (defined $c && length $c) {
2619 my ($url, $rev, $uuid) = cmt_metadata($c);
2620 return ($rev, $c) if defined $rev;
2622 if ($_no_metadata) {
2623 my $offset = -41; # from tail
2624 my $rl;
2625 open my $fh, '<', $REVDB or
2626 die "--no-metadata specified and $REVDB not readable\n";
2627 seek $fh, $offset, 2;
2628 $rl = readline $fh;
2629 defined $rl or return (undef, undef);
2630 chomp $rl;
2631 while ($c ne $rl && tell $fh != 0) {
2632 $offset -= 41;
2633 seek $fh, $offset, 2;
2634 $rl = readline $fh;
2635 defined $rl or return (undef, undef);
2636 chomp $rl;
2638 my $rev = tell $fh;
2639 croak $! if ($rev < -1);
2640 $rev = ($rev - 41) / 41;
2641 close $fh or croak $!;
2642 return ($rev, $c);
2644 return (undef, undef);
2647 sub libsvn_parse_revision {
2648 my $base = shift;
2649 my $head = $SVN->get_latest_revnum();
2650 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2651 return ($base + 1, $head) if (defined $base);
2652 return (0, $head);
2654 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2655 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2656 if ($_revision =~ /^BASE:(\d+)$/) {
2657 return ($base + 1, $1) if (defined $base);
2658 return (0, $head);
2660 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2661 die "revision argument: $_revision not understood by git-svn\n",
2662 "Try using the command-line svn client instead\n";
2665 sub libsvn_traverse_ignore {
2666 my ($fh, $path, $r) = @_;
2667 $path =~ s#^/+##g;
2668 my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2669 my $p = $path;
2670 $p =~ s#^\Q$SVN->{svn_path}\E/##;
2671 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2672 if (my $s = $props->{'svn:ignore'}) {
2673 $s =~ s/[\r\n]+/\n/g;
2674 chomp $s;
2675 if (length $p == 0) {
2676 $s =~ s#\n#\n/$p#g;
2677 print $fh "/$s\n";
2678 } else {
2679 $s =~ s#\n#\n/$p/#g;
2680 print $fh "/$p/$s\n";
2683 foreach (sort keys %$dirent) {
2684 next if $dirent->{$_}->kind != $SVN::Node::dir;
2685 libsvn_traverse_ignore($fh, "$path/$_", $r);
2689 sub revisions_eq {
2690 my ($path, $r0, $r1) = @_;
2691 return 1 if $r0 == $r1;
2692 my $nr = 0;
2693 # should be OK to use Pool here (r1 - r0) should be small
2694 $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2695 return 0 if ($nr > 1);
2696 return 1;
2699 sub libsvn_find_parent_branch {
2700 my ($paths, $rev, $author, $date, $msg) = @_;
2701 my $svn_path = '/'.$SVN->{svn_path};
2703 # look for a parent from another branch:
2704 my $i = $paths->{$svn_path} or return;
2705 my $branch_from = $i->copyfrom_path or return;
2706 my $r = $i->copyfrom_rev;
2707 print STDERR "Found possible branch point: ",
2708 "$branch_from => $svn_path, $r\n";
2709 $branch_from =~ s#^/##;
2710 my $l_map = {};
2711 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2712 my $url = $SVN->{repos_root};
2713 defined $l_map->{$url} or return;
2714 my $id = $l_map->{$url}->{$branch_from};
2715 if (!defined $id && $_follow_parent) {
2716 print STDERR "Following parent: $branch_from\@$r\n";
2717 # auto create a new branch and follow it
2718 $id = basename($branch_from);
2719 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2720 while (-r "$GIT_DIR/svn/$id") {
2721 # just grow a tail if we're not unique enough :x
2722 $id .= '-';
2725 return unless defined $id;
2727 my ($r0, $parent) = find_rev_before($r,$id,1);
2728 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2729 defined(my $pid = fork) or croak $!;
2730 if (!$pid) {
2731 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2732 init_vars();
2733 $SVN_URL = "$url/$branch_from";
2734 $SVN = undef;
2735 setup_git_svn();
2736 # we can't assume SVN_URL exists at r+1:
2737 $_revision = "0:$r";
2738 fetch_lib();
2739 exit 0;
2741 waitpid $pid, 0;
2742 croak $? if $?;
2743 ($r0, $parent) = find_rev_before($r,$id,1);
2745 return unless (defined $r0 && defined $parent);
2746 if (revisions_eq($branch_from, $r0, $r)) {
2747 unlink $GIT_SVN_INDEX;
2748 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2749 command_noisy('read-tree', $parent);
2750 unless ($SVN->can_do_switch) {
2751 return _libsvn_new_tree($paths, $rev, $author, $date,
2752 $msg, [$parent]);
2754 # do_switch works with svn/trunk >= r22312, but that is not
2755 # included with SVN 1.4.2 (the latest version at the moment),
2756 # so we can't rely on it.
2757 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2758 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2759 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2760 die "SVN connection failed somewhere...\n";
2761 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2763 print STDERR "Nope, branch point not imported or unknown\n";
2764 return undef;
2767 sub libsvn_new_tree {
2768 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2769 return $log_entry;
2771 my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2772 _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2775 sub _libsvn_new_tree {
2776 my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2777 my $ed = SVN::Git::Fetcher->new({q => $_q});
2778 unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2779 die "SVN connection failed somewhere...\n";
2781 libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2784 sub find_graft_path_commit {
2785 my ($tree_paths, $p1, $r1) = @_;
2786 foreach my $x (keys %$tree_paths) {
2787 next unless ($p1 =~ /^\Q$x\E/);
2788 my $i = $tree_paths->{$x};
2789 my ($r0, $parent) = find_rev_before($r1,$i,1);
2790 return $parent if (defined $r0 && $r0 == $r1);
2791 print STDERR "r$r1 of $i not imported\n";
2792 next;
2794 return undef;
2797 sub find_graft_path_parents {
2798 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2799 foreach my $x (keys %$tree_paths) {
2800 next unless ($p0 =~ /^\Q$x\E/);
2801 my $i = $tree_paths->{$x};
2802 my ($r, $parent) = find_rev_before($r0, $i, 1);
2803 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2804 my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2805 my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2806 next if ($url_a && $url_b && $url_a eq $url_b &&
2807 $uuid_b eq $uuid_a);
2808 $grafts->{$c}->{$parent} = 1;
2813 sub libsvn_graft_file_copies {
2814 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2815 foreach (keys %$paths) {
2816 my $i = $paths->{$_};
2817 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2818 $i->copyfrom_rev);
2819 next unless (defined $p0 && defined $r0);
2821 my $p1 = $_;
2822 $p1 =~ s#^/##;
2823 $p0 =~ s#^/##;
2824 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2825 next unless $c;
2826 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2830 sub set_index {
2831 my $old = $ENV{GIT_INDEX_FILE};
2832 $ENV{GIT_INDEX_FILE} = shift;
2833 return $old;
2836 sub restore_index {
2837 my ($old) = @_;
2838 if (defined $old) {
2839 $ENV{GIT_INDEX_FILE} = $old;
2840 } else {
2841 delete $ENV{GIT_INDEX_FILE};
2845 sub libsvn_commit_cb {
2846 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2847 if ($_optimize_commits && $rev == ($r_last + 1)) {
2848 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2849 $log->{tree} = get_tree_from_treeish($c);
2850 my $cmt = git_commit($log, $cmt_last, $c);
2851 my @diff = command('diff-tree', $cmt, $c);
2852 if (@diff) {
2853 print STDERR "Trees differ: $cmt $c\n",
2854 join('',@diff),"\n";
2855 exit 1;
2857 } else {
2858 fetch("$rev=$c");
2862 sub libsvn_skip_unknown_revs {
2863 my $err = shift;
2864 my $errno = $err->apr_err();
2865 # Maybe the branch we're tracking didn't
2866 # exist when the repo started, so it's
2867 # not an error if it doesn't, just continue
2869 # Wonderfully consistent library, eh?
2870 # 160013 - svn:// and file://
2871 # 175002 - http(s)://
2872 # 175007 - http(s):// (this repo required authorization, too...)
2873 # More codes may be discovered later...
2874 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2875 return;
2877 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2880 # Tie::File seems to be prone to offset errors if revisions get sparse,
2881 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2882 # one of my favorite modules is out :< Next up would be one of the DBM
2883 # modules, but I'm not sure which is most portable... So I'll just
2884 # go with something that's plain-text, but still capable of
2885 # being randomly accessed. So here's my ultra-simple fixed-width
2886 # database. All records are 40 characters + "\n", so it's easy to seek
2887 # to a revision: (41 * rev) is the byte offset.
2888 # A record of 40 0s denotes an empty revision.
2889 # And yes, it's still pretty fast (faster than Tie::File).
2890 sub revdb_set {
2891 my ($file, $rev, $commit) = @_;
2892 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2893 open my $fh, '+<', $file or croak $!;
2894 my $offset = $rev * 41;
2895 # assume that append is the common case:
2896 seek $fh, 0, 2 or croak $!;
2897 my $pos = tell $fh;
2898 if ($pos < $offset) {
2899 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2901 seek $fh, $offset, 0 or croak $!;
2902 print $fh $commit,"\n";
2903 close $fh or croak $!;
2906 sub revdb_get {
2907 my ($file, $rev) = @_;
2908 my $ret;
2909 my $offset = $rev * 41;
2910 open my $fh, '<', $file or croak $!;
2911 seek $fh, $offset, 0;
2912 if (tell $fh == $offset) {
2913 $ret = readline $fh;
2914 if (defined $ret) {
2915 chomp $ret;
2916 $ret = undef if ($ret =~ /^0{40}$/);
2919 close $fh or croak $!;
2920 return $ret;
2923 sub copy_remote_ref {
2924 my $origin = $_cp_remote ? $_cp_remote : 'origin';
2925 my $ref = "refs/remotes/$GIT_SVN";
2926 if (command('ls-remote', $origin, $ref)) {
2927 command_noisy('fetch', $origin, "$ref:$ref");
2928 } elsif ($_cp_remote && !$_upgrade) {
2929 die "Unable to find remote reference: ",
2930 "refs/remotes/$GIT_SVN on $origin\n";
2935 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2936 $SVN::Node::dir.$SVN::Node::unknown.
2937 $SVN::Node::none.$SVN::Node::file.
2938 $SVN::Node::dir.$SVN::Node::unknown.
2939 $SVN::Auth::SSL::CNMISMATCH.
2940 $SVN::Auth::SSL::NOTYETVALID.
2941 $SVN::Auth::SSL::EXPIRED.
2942 $SVN::Auth::SSL::UNKNOWNCA.
2943 $SVN::Auth::SSL::OTHER;
2946 package SVN::Git::Fetcher;
2947 use vars qw/@ISA/;
2948 use strict;
2949 use warnings;
2950 use Carp qw/croak/;
2951 use IO::File qw//;
2953 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2954 sub new {
2955 my ($class, $git_svn) = @_;
2956 my $self = SVN::Delta::Editor->new;
2957 bless $self, $class;
2958 $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2959 $self->{q} = $git_svn->{q};
2960 $self->{empty} = {};
2961 $self->{dir_prop} = {};
2962 $self->{file_prop} = {};
2963 $self->{absent_dir} = {};
2964 $self->{absent_file} = {};
2965 ($self->{gui}, $self->{ctx}) = command_input_pipe(
2966 qw/update-index -z --index-info/);
2967 require Digest::MD5;
2968 $self;
2971 sub open_root {
2972 { path => '' };
2975 sub open_directory {
2976 my ($self, $path, $pb, $rev) = @_;
2977 { path => $path };
2980 sub delete_entry {
2981 my ($self, $path, $rev, $pb) = @_;
2982 my $gui = $self->{gui};
2984 # remove entire directories.
2985 if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2986 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2987 -r --name-only -z/,
2988 $self->{c}, '--', $path);
2989 local $/ = "\0";
2990 while (<$ls>) {
2991 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2992 print "\tD\t$_\n" unless $self->{q};
2994 print "\tD\t$path/\n" unless $self->{q};
2995 command_close_pipe($ls, $ctx);
2996 $self->{empty}->{$path} = 0
2997 } else {
2998 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
2999 print "\tD\t$path\n" unless $self->{q};
3001 undef;
3004 sub open_file {
3005 my ($self, $path, $pb, $rev) = @_;
3006 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
3007 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3008 unless (defined $mode && defined $blob) {
3009 die "$path was not found in commit $self->{c} (r$rev)\n";
3011 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3012 pool => SVN::Pool->new, action => 'M' };
3015 sub add_file {
3016 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3017 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3018 delete $self->{empty}->{$dir};
3019 { path => $path, mode_a => 100644, mode_b => 100644,
3020 pool => SVN::Pool->new, action => 'A' };
3023 sub add_directory {
3024 my ($self, $path, $cp_path, $cp_rev) = @_;
3025 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3026 delete $self->{empty}->{$dir};
3027 $self->{empty}->{$path} = 1;
3028 { path => $path };
3031 sub change_dir_prop {
3032 my ($self, $db, $prop, $value) = @_;
3033 $self->{dir_prop}->{$db->{path}} ||= {};
3034 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3035 undef;
3038 sub absent_directory {
3039 my ($self, $path, $pb) = @_;
3040 $self->{absent_dir}->{$pb->{path}} ||= [];
3041 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3042 undef;
3045 sub absent_file {
3046 my ($self, $path, $pb) = @_;
3047 $self->{absent_file}->{$pb->{path}} ||= [];
3048 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3049 undef;
3052 sub change_file_prop {
3053 my ($self, $fb, $prop, $value) = @_;
3054 if ($prop eq 'svn:executable') {
3055 if ($fb->{mode_b} != 120000) {
3056 $fb->{mode_b} = defined $value ? 100755 : 100644;
3058 } elsif ($prop eq 'svn:special') {
3059 $fb->{mode_b} = defined $value ? 120000 : 100644;
3060 } else {
3061 $self->{file_prop}->{$fb->{path}} ||= {};
3062 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3064 undef;
3067 sub apply_textdelta {
3068 my ($self, $fb, $exp) = @_;
3069 my $fh = IO::File->new_tmpfile;
3070 $fh->autoflush(1);
3071 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3072 # (but $base does not,) so dup() it for reading in close_file
3073 open my $dup, '<&', $fh or croak $!;
3074 my $base = IO::File->new_tmpfile;
3075 $base->autoflush(1);
3076 if ($fb->{blob}) {
3077 defined (my $pid = fork) or croak $!;
3078 if (!$pid) {
3079 open STDOUT, '>&', $base or croak $!;
3080 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
3081 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
3083 waitpid $pid, 0;
3084 croak $? if $?;
3086 if (defined $exp) {
3087 seek $base, 0, 0 or croak $!;
3088 my $md5 = Digest::MD5->new;
3089 $md5->addfile($base);
3090 my $got = $md5->hexdigest;
3091 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3092 "expected: $exp\n",
3093 " got: $got\n" if ($got ne $exp);
3096 seek $base, 0, 0 or croak $!;
3097 $fb->{fh} = $dup;
3098 $fb->{base} = $base;
3099 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3102 sub close_file {
3103 my ($self, $fb, $exp) = @_;
3104 my $hash;
3105 my $path = $fb->{path};
3106 if (my $fh = $fb->{fh}) {
3107 seek($fh, 0, 0) or croak $!;
3108 my $md5 = Digest::MD5->new;
3109 $md5->addfile($fh);
3110 my $got = $md5->hexdigest;
3111 die "Checksum mismatch: $path\n",
3112 "expected: $exp\n got: $got\n" if ($got ne $exp);
3113 seek($fh, 0, 0) or croak $!;
3114 if ($fb->{mode_b} == 120000) {
3115 read($fh, my $buf, 5) == 5 or croak $!;
3116 $buf eq 'link ' or die "$path has mode 120000",
3117 "but is not a link\n";
3119 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3120 if (!$pid) {
3121 open STDIN, '<&', $fh or croak $!;
3122 exec qw/git-hash-object -w --stdin/ or croak $!;
3124 chomp($hash = do { local $/; <$out> });
3125 close $out or croak $!;
3126 close $fh or croak $!;
3127 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3128 close $fb->{base} or croak $!;
3129 } else {
3130 $hash = $fb->{blob} or die "no blob information\n";
3132 $fb->{pool}->clear;
3133 my $gui = $self->{gui};
3134 print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
3135 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
3136 undef;
3139 sub abort_edit {
3140 my $self = shift;
3141 eval { command_close_pipe($self->{gui}, $self->{ctx}) };
3142 $self->SUPER::abort_edit(@_);
3145 sub close_edit {
3146 my $self = shift;
3147 command_close_pipe($self->{gui}, $self->{ctx});
3148 $self->{git_commit_ok} = 1;
3149 $self->SUPER::close_edit(@_);
3152 package SVN::Git::Editor;
3153 use vars qw/@ISA/;
3154 use strict;
3155 use warnings;
3156 use Carp qw/croak/;
3157 use IO::File;
3159 sub new {
3160 my $class = shift;
3161 my $git_svn = shift;
3162 my $self = SVN::Delta::Editor->new(@_);
3163 bless $self, $class;
3164 foreach (qw/svn_path c r ra /) {
3165 die "$_ required!\n" unless (defined $git_svn->{$_});
3166 $self->{$_} = $git_svn->{$_};
3168 $self->{pool} = SVN::Pool->new;
3169 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3170 $self->{rm} = { };
3171 require Digest::MD5;
3172 return $self;
3175 sub split_path {
3176 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3179 sub repo_path {
3180 (defined $_[1] && length $_[1]) ? $_[1] : ''
3183 sub url_path {
3184 my ($self, $path) = @_;
3185 $self->{ra}->{url} . '/' . $self->repo_path($path);
3188 sub rmdirs {
3189 my ($self, $q) = @_;
3190 my $rm = $self->{rm};
3191 delete $rm->{''}; # we never delete the url we're tracking
3192 return unless %$rm;
3194 foreach (keys %$rm) {
3195 my @d = split m#/#, $_;
3196 my $c = shift @d;
3197 $rm->{$c} = 1;
3198 while (@d) {
3199 $c .= '/' . shift @d;
3200 $rm->{$c} = 1;
3203 delete $rm->{$self->{svn_path}};
3204 delete $rm->{''}; # we never delete the url we're tracking
3205 return unless %$rm;
3207 my ($fh, $ctx) = command_output_pipe(
3208 qw/ls-tree --name-only -r -z/, $self->{c});
3209 local $/ = "\0";
3210 while (<$fh>) {
3211 chomp;
3212 my @dn = split m#/#, $_;
3213 while (pop @dn) {
3214 delete $rm->{join '/', @dn};
3216 unless (%$rm) {
3217 close $fh;
3218 return;
3221 command_close_pipe($fh, $ctx);
3223 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3224 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3225 $self->close_directory($bat->{$d}, $p);
3226 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3227 print "\tD+\t$d/\n" unless $q;
3228 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3229 delete $bat->{$d};
3233 sub open_or_add_dir {
3234 my ($self, $full_path, $baton) = @_;
3235 my $t = $self->{ra}->check_path($full_path, $self->{r});
3236 if ($t == $SVN::Node::none) {
3237 return $self->add_directory($full_path, $baton,
3238 undef, -1, $self->{pool});
3239 } elsif ($t == $SVN::Node::dir) {
3240 return $self->open_directory($full_path, $baton,
3241 $self->{r}, $self->{pool});
3243 print STDERR "$full_path already exists in repository at ",
3244 "r$self->{r} and it is not a directory (",
3245 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3246 exit 1;
3249 sub ensure_path {
3250 my ($self, $path) = @_;
3251 my $bat = $self->{bat};
3252 $path = $self->repo_path($path);
3253 return $bat->{''} unless (length $path);
3254 my @p = split m#/+#, $path;
3255 my $c = shift @p;
3256 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3257 while (@p) {
3258 my $c0 = $c;
3259 $c .= '/' . shift @p;
3260 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3262 return $bat->{$c};
3265 sub A {
3266 my ($self, $m, $q) = @_;
3267 my ($dir, $file) = split_path($m->{file_b});
3268 my $pbat = $self->ensure_path($dir);
3269 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3270 undef, -1);
3271 print "\tA\t$m->{file_b}\n" unless $q;
3272 $self->chg_file($fbat, $m);
3273 $self->close_file($fbat,undef,$self->{pool});
3276 sub C {
3277 my ($self, $m, $q) = @_;
3278 my ($dir, $file) = split_path($m->{file_b});
3279 my $pbat = $self->ensure_path($dir);
3280 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3281 $self->url_path($m->{file_a}), $self->{r});
3282 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3283 $self->chg_file($fbat, $m);
3284 $self->close_file($fbat,undef,$self->{pool});
3287 sub delete_entry {
3288 my ($self, $path, $pbat) = @_;
3289 my $rpath = $self->repo_path($path);
3290 my ($dir, $file) = split_path($rpath);
3291 $self->{rm}->{$dir} = 1;
3292 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3295 sub R {
3296 my ($self, $m, $q) = @_;
3297 my ($dir, $file) = split_path($m->{file_b});
3298 my $pbat = $self->ensure_path($dir);
3299 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3300 $self->url_path($m->{file_a}), $self->{r});
3301 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3302 $self->chg_file($fbat, $m);
3303 $self->close_file($fbat,undef,$self->{pool});
3305 ($dir, $file) = split_path($m->{file_a});
3306 $pbat = $self->ensure_path($dir);
3307 $self->delete_entry($m->{file_a}, $pbat);
3310 sub M {
3311 my ($self, $m, $q) = @_;
3312 my ($dir, $file) = split_path($m->{file_b});
3313 my $pbat = $self->ensure_path($dir);
3314 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3315 $pbat,$self->{r},$self->{pool});
3316 print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3317 $self->chg_file($fbat, $m);
3318 $self->close_file($fbat,undef,$self->{pool});
3321 sub T { shift->M(@_) }
3323 sub change_file_prop {
3324 my ($self, $fbat, $pname, $pval) = @_;
3325 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3328 sub chg_file {
3329 my ($self, $fbat, $m) = @_;
3330 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3331 $self->change_file_prop($fbat,'svn:executable','*');
3332 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3333 $self->change_file_prop($fbat,'svn:executable',undef);
3335 my $fh = IO::File->new_tmpfile or croak $!;
3336 if ($m->{mode_b} =~ /^120/) {
3337 print $fh 'link ' or croak $!;
3338 $self->change_file_prop($fbat,'svn:special','*');
3339 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3340 $self->change_file_prop($fbat,'svn:special',undef);
3342 defined(my $pid = fork) or croak $!;
3343 if (!$pid) {
3344 open STDOUT, '>&', $fh or croak $!;
3345 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3347 waitpid $pid, 0;
3348 croak $? if $?;
3349 $fh->flush == 0 or croak $!;
3350 seek $fh, 0, 0 or croak $!;
3352 my $md5 = Digest::MD5->new;
3353 $md5->addfile($fh) or croak $!;
3354 seek $fh, 0, 0 or croak $!;
3356 my $exp = $md5->hexdigest;
3357 my $pool = SVN::Pool->new;
3358 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3359 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3360 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3361 $pool->clear;
3363 close $fh or croak $!;
3366 sub D {
3367 my ($self, $m, $q) = @_;
3368 my ($dir, $file) = split_path($m->{file_b});
3369 my $pbat = $self->ensure_path($dir);
3370 print "\tD\t$m->{file_b}\n" unless $q;
3371 $self->delete_entry($m->{file_b}, $pbat);
3374 sub close_edit {
3375 my ($self) = @_;
3376 my ($p,$bat) = ($self->{pool}, $self->{bat});
3377 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3378 $self->close_directory($bat->{$_}, $p);
3380 $self->SUPER::close_edit($p);
3381 $p->clear;
3384 sub abort_edit {
3385 my ($self) = @_;
3386 $self->SUPER::abort_edit($self->{pool});
3387 $self->{pool}->clear;
3390 package Git::SVN::Ra;
3391 use vars qw/@ISA $config_dir/;
3392 use strict;
3393 use warnings;
3394 my ($can_do_switch);
3396 BEGIN {
3397 # enforce temporary pool usage for some simple functions
3398 my $e;
3399 foreach (qw/get_latest_revnum rev_proplist get_file
3400 check_path get_dir get_uuid get_repos_root/) {
3401 $e .= "sub $_ {
3402 my \$self = shift;
3403 my \$pool = SVN::Pool->new;
3404 my \@ret = \$self->SUPER::$_(\@_,\$pool);
3405 \$pool->clear;
3406 wantarray ? \@ret : \$ret[0]; }\n";
3408 eval $e;
3411 sub new {
3412 my ($class, $url) = @_;
3413 SVN::_Core::svn_config_ensure($config_dir, undef);
3414 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3415 SVN::Client::get_simple_provider(),
3416 SVN::Client::get_ssl_server_trust_file_provider(),
3417 SVN::Client::get_simple_prompt_provider(
3418 \&Git::SVN::Prompt::simple, 2),
3419 SVN::Client::get_ssl_client_cert_prompt_provider(
3420 \&Git::SVN::Prompt::ssl_client_cert, 2),
3421 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3422 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3423 SVN::Client::get_username_provider(),
3424 SVN::Client::get_ssl_server_trust_prompt_provider(
3425 \&Git::SVN::Prompt::ssl_server_trust),
3426 SVN::Client::get_username_prompt_provider(
3427 \&Git::SVN::Prompt::username, 2),
3429 my $config = SVN::Core::config_get_config($config_dir);
3430 my $self = SVN::Ra->new(url => $url, auth => $baton,
3431 config => $config,
3432 pool => SVN::Pool->new,
3433 auth_provider_callbacks => $callbacks);
3434 $self->{svn_path} = $url;
3435 $self->{repos_root} = $self->get_repos_root;
3436 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
3437 bless $self, $class;
3440 sub DESTROY {
3441 my $self = shift;
3442 $self->{pool}->clear if $self->{pool};
3443 $self->SUPER::DESTROY(@_);
3446 sub dup {
3447 my ($self) = @_;
3448 my $dup = SVN::Ra->new(pool => SVN::Pool->new,
3449 map { $_ => $self->{$_} } qw/config url
3450 auth auth_provider_callbacks repos_root svn_path/);
3451 bless $dup, ref $self;
3454 sub get_log {
3455 my ($self, @args) = @_;
3456 my $pool = SVN::Pool->new;
3457 $args[4]-- if $args[4] && ! $::_follow_parent;
3458 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3459 my $ret = $self->SUPER::get_log(@args, $pool);
3460 $pool->clear;
3461 $ret;
3464 sub get_commit_editor {
3465 my ($self, $msg, $cb, $pool) = @_;
3466 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3467 $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3470 sub uuid {
3471 my ($self) = @_;
3472 $self->{uuid} ||= $self->get_uuid;
3475 sub gs_do_update {
3476 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3477 my $pool = SVN::Pool->new;
3478 my $reporter = $self->do_update($rev_b, $path, $recurse,
3479 $editor, $pool);
3480 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3481 my $new = ($rev_a == $rev_b);
3482 $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3483 $reporter->finish_report($pool);
3484 $pool->clear;
3485 $editor->{git_commit_ok};
3488 sub gs_do_switch {
3489 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3490 my $pool = SVN::Pool->new;
3491 my $reporter = $self->do_switch($rev_b, $path, $recurse,
3492 $url_b, $editor, $pool);
3493 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3494 $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3495 $reporter->finish_report($pool);
3496 $pool->clear;
3497 $editor->{git_commit_ok};
3500 sub can_do_switch {
3501 my $self = shift;
3502 unless (defined $can_do_switch) {
3503 my $pool = SVN::Pool->new;
3504 my $rep = eval {
3505 $self->do_switch(1, '', 0, $self->{url},
3506 SVN::Delta::Editor->new, $pool);
3508 if ($@) {
3509 $can_do_switch = 0;
3510 } else {
3511 $rep->abort_report($pool);
3512 $can_do_switch = 1;
3514 $pool->clear;
3516 $can_do_switch;
3519 __END__
3521 Data structures:
3523 $log_msg hashref as returned by libsvn_log_entry()
3525 msg => 'whitespace-formatted log entry
3526 ', # trailing newline is preserved
3527 revision => '8', # integer
3528 date => '2004-02-24T17:01:44.108345Z', # commit date
3529 author => 'committer name'
3532 @mods = array of diff-index line hashes, each element represents one line
3533 of diff-index output
3535 diff-index line ($m hash)
3537 mode_a => first column of diff-index output, no leading ':',
3538 mode_b => second column of diff-index output,
3539 sha1_b => sha1sum of the final blob,
3540 chg => change type [MCRADT],
3541 file_a => original file name of a file (iff chg is 'C' or 'R')
3542 file_b => new/current file name of a file (any chg)
3546 # retval of read_url_paths{,_all}();
3547 $l_map = {
3548 # repository root url
3549 'https://svn.musicpd.org' => {
3550 # repository path # GIT_SVN_ID
3551 'mpd/trunk' => 'trunk',
3552 'mpd/tags/0.11.5' => 'tags/0.11.5',
3556 Notes:
3557 I don't trust the each() function on unless I created %hash myself
3558 because the internal iterator may not have started at base.