72f73ea623ddb58e3d9d68d519e7fa6ed4fb7891
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,
32 );
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";
40 }
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::$_; ";
63 }
64 eval $s;
65 }
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
109 );
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' => [ \&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 } ],
165 );
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;
173 }
174 };
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";
214 }
215 }
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;
223 }
225 sub version {
226 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
227 exit 0;
228 }
230 sub rebuild {
231 if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
232 copy_remote_ref();
233 }
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();
241 }
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";
258 }
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";
268 }
269 $SVN_URL ||= $url;
270 $svn_uuid ||= $uuid;
271 setup_git_svn();
272 $latest = $rev;
273 }
274 revdb_set($REVDB, $rev, $c);
275 print "r$rev = $c\n";
276 $newest_rev = $rev if ($rev > $newest_rev);
277 }
278 command_close_pipe($rev_list, $ctx);
279 }
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);
287 }
288 }
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]);
296 }
297 chdir $repo_path or croak $!;
298 $ENV{GIT_DIR} = $repo_path . "/.git";
299 }
300 do_git_init_db();
302 Git::SVN->init(undef, $url);
303 }
305 sub cmd_fetch {
306 fetch_child_id($GIT_SVN, @_);
307 }
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});
315 }
316 return $ret;
317 }
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 }
327 }
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);
337 }
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);
344 }
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";
349 }
350 }
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);
377 }
378 });
379 exit 0;
380 }
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);
389 }
390 restore_index($index);
391 return { revision => $last_rev, commit => $last_commit };
392 }
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;
403 }
404 }
405 }
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";
415 }
416 }
417 commit_lib(@revs);
418 print "Done committing ",scalar @revs," revisions to SVN\n";
419 }
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;
433 }
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},
451 },
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)
461 );
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;
468 }
469 $pool->clear;
470 exit 0;
471 }
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;
480 }
481 }
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";
486 }
487 } else {
488 ($r_last, $cmt_last) = ($r_new, $cmt_new);
489 }
490 }
491 $ENV{LC_ALL} = 'C';
492 unlink $commit_msg;
493 }
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";
507 }
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";
513 }
514 }
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
521 }
522 }
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/;
536 }
537 command_noisy(@finish, $gs);
538 }
540 sub show_ignore {
541 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
542 my $repo;
543 $SVN ||= Git::SVN::Ra->new($SVN_URL);
544 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
545 libsvn_traverse_ignore(\*STDOUT, '', $r);
546 }
548 sub graft_branches {
549 my $gr_file = "$GIT_DIR/info/grafts";
550 my ($grafts, $comments) = read_grafts($gr_file);
551 my $gr_sha1;
553 if (%$grafts) {
554 # temporarily disable our grafts file to make this idempotent
555 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
556 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
557 }
559 my $l_map = read_url_paths();
560 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
561 unless ($_no_default_regex) {
562 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
563 qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
564 qr/\b(?:from|of)\s+([\w\.\-]+)/i );
565 }
566 foreach my $u (keys %$l_map) {
567 if (@re) {
568 foreach my $p (keys %{$l_map->{$u}}) {
569 graft_merge_msg($grafts,$l_map,$u,$p,@re);
570 }
571 }
572 unless ($_no_graft_copy) {
573 graft_file_copy_lib($grafts,$l_map,$u);
574 }
575 }
576 graft_tree_joins($grafts);
578 write_grafts($grafts, $comments, $gr_file);
579 unlink "$gr_file~$gr_sha1" if $gr_sha1;
580 }
582 sub cmd_multi_init {
583 my $url = shift;
584 unless (defined $_trunk || defined $_branches || defined $_tags) {
585 usage(1);
586 }
587 do_git_init_db();
588 $_prefix = '' unless defined $_prefix;
589 if (defined $_trunk) {
590 my $gs_trunk = eval { Git::SVN->new($_prefix . 'trunk') };
591 unless ($gs_trunk) {
592 my $trunk_url = complete_svn_url($url, $_trunk);
593 $gs_trunk = Git::SVN->init($_prefix . 'trunk',
594 $trunk_url);
595 command_noisy('config', 'svn.trunk', $trunk_url);
596 }
597 }
598 complete_url_ls_init($url, $_branches, '--branches/-b', $_prefix);
599 complete_url_ls_init($url, $_tags, '--tags/-t', $_prefix . 'tags/');
600 }
602 sub multi_fetch {
603 # try to do trunk first, since branches/tags
604 # may be descended from it.
605 if (-e "$GIT_DIR/svn/trunk/info/url") {
606 fetch_child_id('trunk', @_);
607 }
608 rec_fetch('', "$GIT_DIR/svn", @_);
609 }
611 sub show_log {
612 my (@args) = @_;
613 my ($r_min, $r_max);
614 my $r_last = -1; # prevent dupes
615 rload_authors() if $_authors;
616 if (defined $TZ) {
617 $ENV{TZ} = $TZ;
618 } else {
619 delete $ENV{TZ};
620 }
621 if (defined $_revision) {
622 if ($_revision =~ /^(\d+):(\d+)$/) {
623 ($r_min, $r_max) = ($1, $2);
624 } elsif ($_revision =~ /^\d+$/) {
625 $r_min = $r_max = $_revision;
626 } else {
627 print STDERR "-r$_revision is not supported, use ",
628 "standard \'git log\' arguments instead\n";
629 exit 1;
630 }
631 }
633 config_pager();
634 @args = (git_svn_log_cmd($r_min, $r_max), @args);
635 my $log = command_output_pipe(@args);
636 run_pager();
637 my (@k, $c, $d);
639 while (<$log>) {
640 if (/^${_esc_color}commit ($sha1_short)/o) {
641 my $cmt = $1;
642 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
643 $r_last = $c->{r};
644 process_commit($c, $r_min, $r_max, \@k) or
645 goto out;
646 }
647 $d = undef;
648 $c = { c => $cmt };
649 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
650 get_author_info($c, $1, $2, $3);
651 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
652 # ignore
653 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
654 push @{$c->{raw}}, $_;
655 } elsif (/^${_esc_color}[ACRMDT]\t/) {
656 # we could add $SVN->{svn_path} here, but that requires
657 # remote access at the moment (repo_path_split)...
658 s#^(${_esc_color})([ACRMDT])\t#$1 $2 #;
659 push @{$c->{changed}}, $_;
660 } elsif (/^${_esc_color}diff /) {
661 $d = 1;
662 push @{$c->{diff}}, $_;
663 } elsif ($d) {
664 push @{$c->{diff}}, $_;
665 } elsif (/^${_esc_color} (git-svn-id:.+)$/) {
666 ($c->{url}, $c->{r}, undef) = extract_metadata($1);
667 } elsif (s/^${_esc_color} //) {
668 push @{$c->{l}}, $_;
669 }
670 }
671 if ($c && defined $c->{r} && $c->{r} != $r_last) {
672 $r_last = $c->{r};
673 process_commit($c, $r_min, $r_max, \@k);
674 }
675 if (@k) {
676 my $swap = $r_max;
677 $r_max = $r_min;
678 $r_min = $swap;
679 process_commit($_, $r_min, $r_max) foreach reverse @k;
680 }
681 out:
682 close $log;
683 print '-' x72,"\n" unless $_incremental || $_oneline;
684 }
686 sub commit_diff_usage {
687 print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
688 exit 1
689 }
691 sub commit_diff {
692 my $ta = shift or commit_diff_usage();
693 my $tb = shift or commit_diff_usage();
694 if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
695 print STDERR "Needed URL or usable git-svn id command-line\n";
696 commit_diff_usage();
697 }
698 my $r = shift;
699 unless (defined $r) {
700 if (defined $_revision) {
701 $r = $_revision
702 } else {
703 die "-r|--revision is a required argument\n";
704 }
705 }
706 if (defined $_message && defined $_file) {
707 print STDERR "Both --message/-m and --file/-F specified ",
708 "for the commit message.\n",
709 "I have no idea what you mean\n";
710 exit 1;
711 }
712 if (defined $_file) {
713 $_message = file_to_s($_file);
714 } else {
715 $_message ||= get_commit_message($tb,
716 "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
717 }
718 $SVN ||= Git::SVN::Ra->new($SVN_URL);
719 if ($r eq 'HEAD') {
720 $r = $SVN->get_latest_revnum;
721 } elsif ($r !~ /^\d+$/) {
722 die "revision argument: $r not understood by git-svn\n";
723 }
724 my $rev_committed;
725 my $pool = SVN::Pool->new;
726 my $ed = SVN::Git::Editor->new({ r => $r,
727 ra => $SVN->dup,
728 c => $tb,
729 svn_path => $SVN->{svn_path}
730 },
731 $SVN->get_commit_editor($_message,
732 sub {
733 $rev_committed = $_[0];
734 print "Committed $_[0]\n";
735 },
736 $pool)
737 );
738 eval {
739 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
740 if (@$mods == 0) {
741 print "No changes\n$ta == $tb\n";
742 $ed->abort_edit;
743 } else {
744 $ed->close_edit;
745 }
746 };
747 $pool->clear;
748 fatal "$@\n" if $@;
749 $_message = $_file = undef;
750 return $rev_committed;
751 }
753 ########################### utility functions #########################
755 sub cmt_showable {
756 my ($c) = @_;
757 return 1 if defined $c->{r};
758 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
759 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
760 my @msg = command(qw/cat-file commit/, $c->{c});
761 shift @msg while ($msg[0] ne "\n");
762 shift @msg;
763 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
765 (undef, $c->{r}, undef) = extract_metadata(
766 (grep(/^git-svn-id: /, @msg))[-1]);
767 }
768 return defined $c->{r};
769 }
771 sub log_use_color {
772 return 1 if $_color;
773 my ($dc, $dcvar);
774 $dcvar = 'color.diff';
775 $dc = `git-config --get $dcvar`;
776 if ($dc eq '') {
777 # nothing at all; fallback to "diff.color"
778 $dcvar = 'diff.color';
779 $dc = `git-config --get $dcvar`;
780 }
781 chomp($dc);
782 if ($dc eq 'auto') {
783 my $pc;
784 $pc = `git-config --get color.pager`;
785 if ($pc eq '') {
786 # does not have it -- fallback to pager.color
787 $pc = `git-config --bool --get pager.color`;
788 }
789 else {
790 $pc = `git-config --bool --get color.pager`;
791 if ($?) {
792 $pc = 'false';
793 }
794 }
795 chomp($pc);
796 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
797 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
798 }
799 return 0;
800 }
801 return 0 if $dc eq 'never';
802 return 1 if $dc eq 'always';
803 chomp($dc = `git-config --bool --get $dcvar`);
804 return ($dc eq 'true');
805 }
807 sub git_svn_log_cmd {
808 my ($r_min, $r_max) = @_;
809 my @cmd = (qw/log --abbrev-commit --pretty=raw
810 --default/, "refs/remotes/$GIT_SVN");
811 push @cmd, '-r' unless $_non_recursive;
812 push @cmd, qw/--raw --name-status/ if $_verbose;
813 push @cmd, '--color' if log_use_color();
814 return @cmd unless defined $r_max;
815 if ($r_max == $r_min) {
816 push @cmd, '--max-count=1';
817 if (my $c = revdb_get($REVDB, $r_max)) {
818 push @cmd, $c;
819 }
820 } else {
821 my ($c_min, $c_max);
822 $c_max = revdb_get($REVDB, $r_max);
823 $c_min = revdb_get($REVDB, $r_min);
824 if (defined $c_min && defined $c_max) {
825 if ($r_max > $r_max) {
826 push @cmd, "$c_min..$c_max";
827 } else {
828 push @cmd, "$c_max..$c_min";
829 }
830 } elsif ($r_max > $r_min) {
831 push @cmd, $c_max;
832 } else {
833 push @cmd, $c_min;
834 }
835 }
836 return @cmd;
837 }
839 sub fetch_child_id {
840 my $id = shift;
841 print "Fetching $id\n";
842 my $ref = "$GIT_DIR/refs/remotes/$id";
843 defined(my $pid = open my $fh, '-|') or croak $!;
844 if (!$pid) {
845 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
846 init_vars();
847 fetch(@_);
848 exit 0;
849 }
850 while (<$fh>) {
851 print $_;
852 check_repack() if (/^r\d+ = $sha1/o);
853 }
854 close $fh or croak $?;
855 }
857 sub rec_fetch {
858 my ($pfx, $p, @args) = @_;
859 my @dir;
860 foreach (sort <$p/*>) {
861 if (-r "$_/info/url") {
862 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
863 my $id = $pfx . basename $_;
864 next if $id eq 'trunk';
865 fetch_child_id($id, @args);
866 } elsif (-d $_) {
867 push @dir, $_;
868 }
869 }
870 foreach (@dir) {
871 my $x = $_;
872 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
873 rec_fetch($x, $_);
874 }
875 }
877 sub complete_svn_url {
878 my ($url, $path) = @_;
879 $path =~ s#/+$##;
880 $url =~ s#/+$## if $url;
881 if ($path !~ m#^[a-z\+]+://#) {
882 $path = '/' . $path if ($path !~ m#^/#);
883 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
884 fatal("E: '$path' is not a complete URL ",
885 "and a separate URL is not specified\n");
886 }
887 $path = $url . $path;
888 }
889 return $path;
890 }
892 sub complete_url_ls_init {
893 my ($url, $path, $switch, $pfx) = @_;
894 unless ($path) {
895 print STDERR "W: $switch not specified\n";
896 return;
897 }
898 my $full_url = complete_svn_url($url, $path);
899 my @ls = libsvn_ls_fullurl($full_url);
900 foreach my $u (map { "$full_url/$_" } (grep m!/$!, @ls)) {
901 $u =~ s#/+$##;
902 if ($u !~ m!\Q$full_url\E/(.+)$!) {
903 print STDERR "W: Unrecognized URL: $u\n";
904 die "This should never happen\n";
905 }
906 # don't try to init already existing refs
907 my $id = $pfx.$1;
908 my $gs = eval { Git::SVN->new($id) };
909 unless ($gs) {
910 print "init $u => $id\n";
911 Git::SVN->init($id, $u);
912 }
913 }
914 my ($n) = ($switch =~ /^--(\w+)/);
915 command_noisy('config', "svn.$n", $full_url);
916 }
918 sub common_prefix {
919 my $paths = shift;
920 my %common;
921 foreach (@$paths) {
922 my @tmp = split m#/#, $_;
923 my $p = '';
924 while (my $x = shift @tmp) {
925 $p .= "/$x";
926 $common{$p} ||= 0;
927 $common{$p}++;
928 }
929 }
930 foreach (sort {length $b <=> length $a} keys %common) {
931 if ($common{$_} == @$paths) {
932 return $_;
933 }
934 }
935 return '';
936 }
938 # grafts set here are 'stronger' in that they're based on actual tree
939 # matches, and won't be deleted from merge-base checking in write_grafts()
940 sub graft_tree_joins {
941 my $grafts = shift;
942 map_tree_joins() if (@_branch_from && !%tree_map);
943 return unless %tree_map;
945 git_svn_each(sub {
946 my $i = shift;
947 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
948 my ($fh, $ctx) = command_output_pipe(@args);
949 while (<$fh>) {
950 next unless /^commit ($sha1)$/o;
951 my $c = $1;
952 my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
953 next unless $tree_map{$t};
955 my $l;
956 do {
957 $l = readline $fh;
958 } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
960 my ($s, $tz) = ($1, $2);
961 if ($tz =~ s/^\+//) {
962 $s += tz_to_s_offset($tz);
963 } elsif ($tz =~ s/^\-//) {
964 $s -= tz_to_s_offset($tz);
965 }
967 my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
969 foreach my $p (@{$tree_map{$t}}) {
970 next if $p eq $c;
971 my $mb = eval { command('merge-base', $c, $p) };
972 next unless ($@ || $?);
973 if (defined $r_a) {
974 # see if SVN says it's a relative
975 my ($url_b, $r_b, $uuid_b) =
976 cmt_metadata($p);
977 next if (defined $url_b &&
978 defined $url_a &&
979 ($url_a eq $url_b) &&
980 ($uuid_a eq $uuid_b));
981 if ($uuid_a eq $uuid_b) {
982 if ($r_b < $r_a) {
983 $grafts->{$c}->{$p} = 2;
984 next;
985 } elsif ($r_b > $r_a) {
986 $grafts->{$p}->{$c} = 2;
987 next;
988 }
989 }
990 }
991 my $ct = get_commit_time($p);
992 if ($ct < $s) {
993 $grafts->{$c}->{$p} = 2;
994 } elsif ($ct > $s) {
995 $grafts->{$p}->{$c} = 2;
996 }
997 # what should we do when $ct == $s ?
998 }
999 }
1000 command_close_pipe($fh, $ctx);
1001 });
1002 }
1004 sub graft_file_copy_lib {
1005 my ($grafts, $l_map, $u) = @_;
1006 my $tree_paths = $l_map->{$u};
1007 my $pfx = common_prefix([keys %$tree_paths]);
1008 my ($repo, $path) = repo_path_split($u.$pfx);
1009 $SVN = Git::SVN::Ra->new($repo);
1011 my ($base, $head) = libsvn_parse_revision();
1012 my $inc = 1000;
1013 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1014 my $eh = $SVN::Error::handler;
1015 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1016 while (1) {
1017 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
1018 sub {
1019 libsvn_graft_file_copies($grafts, $tree_paths,
1020 $path, @_);
1021 });
1022 last if ($max >= $head);
1023 $min = $max + 1;
1024 $max += $inc;
1025 $max = $head if ($max > $head);
1026 }
1027 $SVN::Error::handler = $eh;
1028 }
1030 sub process_merge_msg_matches {
1031 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1032 my (@strong, @weak);
1033 foreach (@matches) {
1034 # merging with ourselves is not interesting
1035 next if $_ eq $p;
1036 if ($l_map->{$u}->{$_}) {
1037 push @strong, $_;
1038 } else {
1039 push @weak, $_;
1040 }
1041 }
1042 foreach my $w (@weak) {
1043 last if @strong;
1044 # no exact match, use branch name as regexp.
1045 my $re = qr/\Q$w\E/i;
1046 foreach (keys %{$l_map->{$u}}) {
1047 if (/$re/) {
1048 push @strong, $l_map->{$u}->{$_};
1049 last;
1050 }
1051 }
1052 last if @strong;
1053 $w = basename($w);
1054 $re = qr/\Q$w\E/i;
1055 foreach (keys %{$l_map->{$u}}) {
1056 if (/$re/) {
1057 push @strong, $l_map->{$u}->{$_};
1058 last;
1059 }
1060 }
1061 }
1062 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1063 \s(?:[a-f\d\-]+)$/xsm);
1064 unless (defined $rev) {
1065 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1066 \@(?:[a-f\d\-]+)/xsm);
1067 return unless defined $rev;
1068 }
1069 foreach my $m (@strong) {
1070 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1071 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1072 }
1073 }
1075 sub graft_merge_msg {
1076 my ($grafts, $l_map, $u, $p, @re) = @_;
1078 my $x = $l_map->{$u}->{$p};
1079 my $rl = rev_list_raw("refs/remotes/$x");
1080 while (my $c = next_rev_list_entry($rl)) {
1081 foreach my $re (@re) {
1082 my (@br) = ($c->{m} =~ /$re/g);
1083 next unless @br;
1084 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1085 }
1086 }
1087 }
1089 sub verify_ref {
1090 my ($ref) = @_;
1091 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1092 { STDERR => 0 }); };
1093 }
1095 sub repo_path_split {
1096 my $full_url = shift;
1097 $full_url =~ s#/+$##;
1099 foreach (@repo_path_split_cache) {
1100 if ($full_url =~ s#$_##) {
1101 my $u = $1;
1102 $full_url =~ s#^/+##;
1103 return ($u, $full_url);
1104 }
1105 }
1106 my $tmp = Git::SVN::Ra->new($full_url);
1107 return ($tmp->{repos_root}, $tmp->{svn_path});
1108 }
1110 sub setup_git_svn {
1111 defined $SVN_URL or croak "SVN repository location required\n";
1112 unless (-d $GIT_DIR) {
1113 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1114 }
1115 mkpath([$GIT_SVN_DIR]);
1116 mkpath(["$GIT_SVN_DIR/info"]);
1117 open my $fh, '>>',$REVDB or croak $!;
1118 close $fh;
1119 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1121 }
1123 sub get_tree_from_treeish {
1124 my ($treeish) = @_;
1125 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1126 my $type = command_oneline(qw/cat-file -t/, $treeish);
1127 my $expected;
1128 while ($type eq 'tag') {
1129 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1130 }
1131 if ($type eq 'commit') {
1132 $expected = (grep /^tree /, command(qw/cat-file commit/,
1133 $treeish))[0];
1134 ($expected) = ($expected =~ /^tree ($sha1)$/);
1135 die "Unable to get tree from $treeish\n" unless $expected;
1136 } elsif ($type eq 'tree') {
1137 $expected = $treeish;
1138 } else {
1139 die "$treeish is a $type, expected tree, tag or commit\n";
1140 }
1141 return $expected;
1142 }
1144 sub get_diff {
1145 my ($from, $treeish) = @_;
1146 print "diff-tree $from $treeish\n";
1147 my @diff_tree = qw(diff-tree -z -r);
1148 if ($_cp_similarity) {
1149 push @diff_tree, "-C$_cp_similarity";
1150 } else {
1151 push @diff_tree, '-C';
1152 }
1153 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1154 push @diff_tree, "-l$_l" if defined $_l;
1155 push @diff_tree, $from, $treeish;
1156 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1157 local $/ = "\0";
1158 my $state = 'meta';
1159 my @mods;
1160 while (<$diff_fh>) {
1161 chomp $_; # this gets rid of the trailing "\0"
1162 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1163 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1164 push @mods, { mode_a => $1, mode_b => $2,
1165 sha1_b => $3, chg => $4 };
1166 if ($4 =~ /^(?:C|R)$/) {
1167 $state = 'file_a';
1168 } else {
1169 $state = 'file_b';
1170 }
1171 } elsif ($state eq 'file_a') {
1172 my $x = $mods[$#mods] or croak "Empty array\n";
1173 if ($x->{chg} !~ /^(?:C|R)$/) {
1174 croak "Error parsing $_, $x->{chg}\n";
1175 }
1176 $x->{file_a} = $_;
1177 $state = 'file_b';
1178 } elsif ($state eq 'file_b') {
1179 my $x = $mods[$#mods] or croak "Empty array\n";
1180 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1181 croak "Error parsing $_, $x->{chg}\n";
1182 }
1183 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1184 croak "Error parsing $_, $x->{chg}\n";
1185 }
1186 $x->{file_b} = $_;
1187 $state = 'meta';
1188 } else {
1189 croak "Error parsing $_\n";
1190 }
1191 }
1192 command_close_pipe($diff_fh, $ctx);
1193 return \@mods;
1194 }
1196 sub libsvn_checkout_tree {
1197 my ($from, $treeish, $ed) = @_;
1198 my $mods = get_diff($from, $treeish);
1199 return $mods unless (scalar @$mods);
1200 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1201 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1202 my $f = $m->{chg};
1203 if (defined $o{$f}) {
1204 $ed->$f($m, $_q);
1205 } else {
1206 croak "Invalid change type: $f\n";
1207 }
1208 }
1209 $ed->rmdirs($_q) if $_rmdir;
1210 return $mods;
1211 }
1213 sub get_commit_message {
1214 my ($commit, $commit_msg) = (@_);
1215 my %log_msg = ( msg => '' );
1216 open my $msg, '>', $commit_msg or croak $!;
1218 my $type = command_oneline(qw/cat-file -t/, $commit);
1219 if ($type eq 'commit' || $type eq 'tag') {
1220 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1221 $type, $commit);
1222 my $in_msg = 0;
1223 while (<$msg_fh>) {
1224 if (!$in_msg) {
1225 $in_msg = 1 if (/^\s*$/);
1226 } elsif (/^git-svn-id: /) {
1227 # skip this, we regenerate the correct one
1228 # on re-fetch anyways
1229 } else {
1230 print $msg $_ or croak $!;
1231 }
1232 }
1233 command_close_pipe($msg_fh, $ctx);
1234 }
1235 close $msg or croak $!;
1237 if ($_edit || ($type eq 'tree')) {
1238 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1239 system($editor, $commit_msg);
1240 }
1242 # file_to_s removes all trailing newlines, so just use chomp() here:
1243 open $msg, '<', $commit_msg or croak $!;
1244 { local $/; chomp($log_msg{msg} = <$msg>); }
1245 close $msg or croak $!;
1247 return \%log_msg;
1248 }
1250 sub set_svn_commit_env {
1251 if (defined $LC_ALL) {
1252 $ENV{LC_ALL} = $LC_ALL;
1253 } else {
1254 delete $ENV{LC_ALL};
1255 }
1256 }
1258 sub rev_list_raw {
1259 my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1260 return { fh => $fh, ctx => $c, t => { } };
1261 }
1263 sub next_rev_list_entry {
1264 my $rl = shift;
1265 my $fh = $rl->{fh};
1266 my $x = $rl->{t};
1267 while (<$fh>) {
1268 if (/^commit ($sha1)$/o) {
1269 if ($x->{c}) {
1270 $rl->{t} = { c => $1 };
1271 return $x;
1272 } else {
1273 $x->{c} = $1;
1274 }
1275 } elsif (/^parent ($sha1)$/o) {
1276 $x->{p}->{$1} = 1;
1277 } elsif (s/^ //) {
1278 $x->{m} ||= '';
1279 $x->{m} .= $_;
1280 }
1281 }
1282 command_close_pipe($fh, $rl->{ctx});
1283 return ($x != $rl->{t}) ? $x : undef;
1284 }
1286 sub s_to_file {
1287 my ($str, $file, $mode) = @_;
1288 open my $fd,'>',$file or croak $!;
1289 print $fd $str,"\n" or croak $!;
1290 close $fd or croak $!;
1291 chmod ($mode &~ umask, $file) if (defined $mode);
1292 }
1294 sub file_to_s {
1295 my $file = shift;
1296 open my $fd,'<',$file or croak "$!: file: $file\n";
1297 local $/;
1298 my $ret = <$fd>;
1299 close $fd or croak $!;
1300 $ret =~ s/\s*$//s;
1301 return $ret;
1302 }
1304 sub assert_revision_unknown {
1305 my $r = shift;
1306 if (my $c = revdb_get($REVDB, $r)) {
1307 croak "$r = $c already exists! Why are we refetching it?";
1308 }
1309 }
1311 sub git_commit {
1312 my ($log_msg, @parents) = @_;
1313 assert_revision_unknown($log_msg->{revision});
1314 map_tree_joins() if (@_branch_from && !%tree_map);
1316 my (@tmp_parents, @exec_parents, %seen_parent);
1317 if (my $lparents = $log_msg->{parents}) {
1318 @tmp_parents = @$lparents
1319 }
1320 # commit parents can be conditionally bound to a particular
1321 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1322 foreach my $p (@parents) {
1323 next unless defined $p;
1324 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1325 if ($1 == $log_msg->{revision}) {
1326 push @tmp_parents, $2;
1327 }
1328 } else {
1329 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1330 }
1331 }
1332 my $tree = $log_msg->{tree};
1333 if (!defined $tree) {
1334 my $index = set_index($GIT_SVN_INDEX);
1335 $tree = command_oneline('write-tree');
1336 croak $? if $?;
1337 restore_index($index);
1338 }
1339 # just in case we clobber the existing ref, we still want that ref
1340 # as our parent:
1341 if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1342 chomp $cur;
1343 push @tmp_parents, $cur;
1344 }
1346 if (exists $tree_map{$tree}) {
1347 foreach my $p (@{$tree_map{$tree}}) {
1348 my $skip;
1349 foreach (@tmp_parents) {
1350 # see if a common parent is found
1351 my $mb = eval { command('merge-base', $_, $p) };
1352 next if ($@ || $?);
1353 $skip = 1;
1354 last;
1355 }
1356 next if $skip;
1357 my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1358 next if (($SVN->uuid eq $uuid_p) &&
1359 ($log_msg->{revision} > $r_p));
1360 next if (defined $url_p && defined $SVN_URL &&
1361 ($SVN->uuid eq $uuid_p) &&
1362 ($url_p eq $SVN_URL));
1363 push @tmp_parents, $p;
1364 }
1365 }
1366 foreach (@tmp_parents) {
1367 next if $seen_parent{$_};
1368 $seen_parent{$_} = 1;
1369 push @exec_parents, $_;
1370 # MAXPARENT is defined to 16 in commit-tree.c:
1371 last if @exec_parents > 16;
1372 }
1374 set_commit_env($log_msg);
1375 my @exec = ('git-commit-tree', $tree);
1376 push @exec, '-p', $_ foreach @exec_parents;
1377 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1378 or croak $!;
1379 print $msg_fh $log_msg->{msg} or croak $!;
1380 unless ($_no_metadata) {
1381 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1382 $SVN->uuid,"\n" or croak $!;
1383 }
1384 $msg_fh->flush == 0 or croak $!;
1385 close $msg_fh or croak $!;
1386 chomp(my $commit = do { local $/; <$out_fh> });
1387 close $out_fh or croak $!;
1388 waitpid $pid, 0;
1389 croak $? if $?;
1390 if ($commit !~ /^$sha1$/o) {
1391 die "Failed to commit, invalid sha1: $commit\n";
1392 }
1393 command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1394 revdb_set($REVDB, $log_msg->{revision}, $commit);
1396 # this output is read via pipe, do not change:
1397 print "r$log_msg->{revision} = $commit\n";
1398 return $commit;
1399 }
1401 sub check_repack {
1402 if ($_repack && (--$_repack_nr == 0)) {
1403 $_repack_nr = $_repack;
1404 # repack doesn't use any arguments with spaces in them, does it?
1405 command_noisy('repack', split(/\s+/, $_repack_flags));
1406 }
1407 }
1409 sub set_commit_env {
1410 my ($log_msg) = @_;
1411 my $author = $log_msg->{author};
1412 if (!defined $author || length $author == 0) {
1413 $author = '(no author)';
1414 }
1415 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1416 : ($author,$author . '@' . $SVN->uuid);
1417 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1418 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1419 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1420 }
1422 sub check_upgrade_needed {
1423 if (!-r $REVDB) {
1424 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1425 open my $fh, '>>',$REVDB or croak $!;
1426 close $fh;
1427 }
1428 return unless eval {
1429 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1430 {STDERR => 0});
1431 };
1432 my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1433 if ($@ || !$head) {
1434 print STDERR "Please run: $0 rebuild --upgrade\n";
1435 exit 1;
1436 }
1437 }
1439 # fills %tree_map with a reverse mapping of trees to commits. Useful
1440 # for finding parents to commit on.
1441 sub map_tree_joins {
1442 my %seen;
1443 foreach my $br (@_branch_from) {
1444 my $pipe = command_output_pipe(qw/rev-list
1445 --topo-order --pretty=raw/, $br);
1446 while (<$pipe>) {
1447 if (/^commit ($sha1)$/o) {
1448 my $commit = $1;
1450 # if we've seen a commit,
1451 # we've seen its parents
1452 last if $seen{$commit};
1453 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1454 unless (defined $tree) {
1455 die "Failed to parse commit $commit\n";
1456 }
1457 push @{$tree_map{$tree}}, $commit;
1458 $seen{$commit} = 1;
1459 }
1460 }
1461 close $pipe;
1462 }
1463 }
1465 sub load_all_refs {
1466 if (@_branch_from) {
1467 print STDERR '--branch|-b parameters are ignored when ',
1468 "--branch-all-refs|-B is passed\n";
1469 }
1471 # don't worry about rev-list on non-commit objects/tags,
1472 # it shouldn't blow up if a ref is a blob or tree...
1473 @_branch_from = command(qw/rev-parse --symbolic --all/);
1474 }
1476 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1477 sub load_authors {
1478 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1479 while (<$authors>) {
1480 chomp;
1481 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1482 my ($user, $name, $email) = ($1, $2, $3);
1483 $users{$user} = [$name, $email];
1484 }
1485 close $authors or croak $!;
1486 }
1488 sub rload_authors {
1489 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1490 while (<$authors>) {
1491 chomp;
1492 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1493 my ($user, $name, $email) = ($1, $2, $3);
1494 $rusers{"$name <$email>"} = $user;
1495 }
1496 close $authors or croak $!;
1497 }
1499 sub git_svn_each {
1500 my $sub = shift;
1501 foreach (command(qw/rev-parse --symbolic --all/)) {
1502 next unless s#^refs/remotes/##;
1503 chomp $_;
1504 next unless -f "$GIT_DIR/svn/$_/info/url";
1505 &$sub($_);
1506 }
1507 }
1509 sub migrate_revdb {
1510 git_svn_each(sub {
1511 my $id = shift;
1512 defined(my $pid = fork) or croak $!;
1513 if (!$pid) {
1514 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1515 init_vars();
1516 exit 0 if -r $REVDB;
1517 print "Upgrading svn => git mapping...\n";
1518 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1519 open my $fh, '>>',$REVDB or croak $!;
1520 close $fh;
1521 rebuild();
1522 print "Done upgrading. You may now delete the ",
1523 "deprecated $GIT_SVN_DIR/revs directory\n";
1524 exit 0;
1525 }
1526 waitpid $pid, 0;
1527 croak $? if $?;
1528 });
1529 }
1531 sub migration_check {
1532 migrate_revdb() unless (-e $REVDB);
1533 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1534 print "Upgrading repository...\n";
1535 unless (-d "$GIT_DIR/svn") {
1536 mkdir "$GIT_DIR/svn" or croak $!;
1537 }
1538 print "Data from a previous version of git-svn exists, but\n\t",
1539 "$GIT_SVN_DIR\n\t(required for this version ",
1540 "($VERSION) of git-svn) does not.\n";
1542 foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1543 next unless $x =~ s#^refs/remotes/##;
1544 chomp $x;
1545 next unless -f "$GIT_DIR/$x/info/url";
1546 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1547 next unless $u;
1548 my $dn = dirname("$GIT_DIR/svn/$x");
1549 mkpath([$dn]) unless -d $dn;
1550 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1551 }
1552 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1553 print "Done upgrading.\n";
1554 }
1556 sub find_rev_before {
1557 my ($r, $id, $eq_ok) = @_;
1558 my $f = "$GIT_DIR/svn/$id/.rev_db";
1559 return (undef,undef) unless -r $f;
1560 --$r unless $eq_ok;
1561 while ($r > 0) {
1562 if (my $c = revdb_get($f, $r)) {
1563 return ($r, $c);
1564 }
1565 --$r;
1566 }
1567 return (undef, undef);
1568 }
1570 sub init_vars {
1571 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1572 $Git::SVN::default = $GIT_SVN;
1573 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1574 $REVDB = "$GIT_SVN_DIR/.rev_db";
1575 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1576 $SVN_URL = undef;
1577 %tree_map = ();
1578 }
1580 # convert GetOpt::Long specs for use by git-config
1581 sub read_repo_config {
1582 return unless -d $GIT_DIR;
1583 my $opts = shift;
1584 foreach my $o (keys %$opts) {
1585 my $v = $opts->{$o};
1586 my ($key) = ($o =~ /^([a-z\-]+)/);
1587 $key =~ s/-//g;
1588 my $arg = 'git-config';
1589 $arg .= ' --int' if ($o =~ /[:=]i$/);
1590 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1591 if (ref $v eq 'ARRAY') {
1592 chomp(my @tmp = `$arg --get-all svn.$key`);
1593 @$v = @tmp if @tmp;
1594 } else {
1595 chomp(my $tmp = `$arg --get svn.$key`);
1596 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1597 $$v = $tmp;
1598 }
1599 }
1600 }
1601 }
1603 sub set_default_vals {
1604 if (defined $_repack) {
1605 $_repack = 1000 if ($_repack <= 0);
1606 $_repack_nr = $_repack;
1607 $_repack_flags ||= '-d';
1608 }
1609 }
1611 sub read_grafts {
1612 my $gr_file = shift;
1613 my ($grafts, $comments) = ({}, {});
1614 if (open my $fh, '<', $gr_file) {
1615 my @tmp;
1616 while (<$fh>) {
1617 if (/^($sha1)\s+/) {
1618 my $c = $1;
1619 if (@tmp) {
1620 @{$comments->{$c}} = @tmp;
1621 @tmp = ();
1622 }
1623 foreach my $p (split /\s+/, $_) {
1624 $grafts->{$c}->{$p} = 1;
1625 }
1626 } else {
1627 push @tmp, $_;
1628 }
1629 }
1630 close $fh or croak $!;
1631 @{$comments->{'END'}} = @tmp if @tmp;
1632 }
1633 return ($grafts, $comments);
1634 }
1636 sub write_grafts {
1637 my ($grafts, $comments, $gr_file) = @_;
1639 open my $fh, '>', $gr_file or croak $!;
1640 foreach my $c (sort keys %$grafts) {
1641 if ($comments->{$c}) {
1642 print $fh $_ foreach @{$comments->{$c}};
1643 }
1644 my $p = $grafts->{$c};
1645 my %x; # real parents
1646 delete $p->{$c}; # commits are not self-reproducing...
1647 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1648 while (<$ch>) {
1649 if (/^parent ($sha1)/) {
1650 $x{$1} = $p->{$1} = 1;
1651 } else {
1652 last unless /^\S/;
1653 }
1654 }
1655 close $ch; # breaking the pipe
1657 # if real parents are the only ones in the grafts, drop it
1658 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1660 my (@ip, @jp, $mb);
1661 my %del = %x;
1662 @ip = @jp = keys %$p;
1663 foreach my $i (@ip) {
1664 next if $del{$i} || $p->{$i} == 2;
1665 foreach my $j (@jp) {
1666 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1667 $mb = eval { command('merge-base', $i, $j) };
1668 next unless $mb;
1669 chomp $mb;
1670 next if $x{$mb};
1671 if ($mb eq $j) {
1672 delete $p->{$i};
1673 $del{$i} = 1;
1674 } elsif ($mb eq $i) {
1675 delete $p->{$j};
1676 $del{$j} = 1;
1677 }
1678 }
1679 }
1681 # if real parents are the only ones in the grafts, drop it
1682 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1684 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1685 }
1686 if ($comments->{'END'}) {
1687 print $fh $_ foreach @{$comments->{'END'}};
1688 }
1689 close $fh or croak $!;
1690 }
1692 sub read_url_paths_all {
1693 my ($l_map, $pfx, $p) = @_;
1694 my @dir;
1695 foreach (<$p/*>) {
1696 if (-r "$_/info/url") {
1697 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1698 my $id = $pfx . basename $_;
1699 my $url = file_to_s("$_/info/url");
1700 my ($u, $p) = repo_path_split($url);
1701 $l_map->{$u}->{$p} = $id;
1702 } elsif (-d $_) {
1703 push @dir, $_;
1704 }
1705 }
1706 foreach (@dir) {
1707 my $x = $_;
1708 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1709 read_url_paths_all($l_map, $x, $_);
1710 }
1711 }
1713 # this one only gets ids that have been imported, not new ones
1714 sub read_url_paths {
1715 my $l_map = {};
1716 git_svn_each(sub { my $x = shift;
1717 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1718 my ($u, $p) = repo_path_split($url);
1719 $l_map->{$u}->{$p} = $x;
1720 });
1721 return $l_map;
1722 }
1724 sub extract_metadata {
1725 my $id = shift or return (undef, undef, undef);
1726 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1727 \s([a-f\d\-]+)$/x);
1728 if (!defined $rev || !$uuid || !$url) {
1729 # some of the original repositories I made had
1730 # identifiers like this:
1731 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1732 }
1733 return ($url, $rev, $uuid);
1734 }
1736 sub cmt_metadata {
1737 return extract_metadata((grep(/^git-svn-id: /,
1738 command(qw/cat-file commit/, shift)))[-1]);
1739 }
1741 sub get_commit_time {
1742 my $cmt = shift;
1743 my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1744 while (<$fh>) {
1745 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1746 my ($s, $tz) = ($1, $2);
1747 if ($tz =~ s/^\+//) {
1748 $s += tz_to_s_offset($tz);
1749 } elsif ($tz =~ s/^\-//) {
1750 $s -= tz_to_s_offset($tz);
1751 }
1752 close $fh;
1753 return $s;
1754 }
1755 die "Can't get commit time for commit: $cmt\n";
1756 }
1758 sub tz_to_s_offset {
1759 my ($tz) = @_;
1760 $tz =~ s/(\d\d)$//;
1761 return ($1 * 60) + ($tz * 3600);
1762 }
1764 # adapted from pager.c
1765 sub config_pager {
1766 $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
1767 if (!defined $_pager) {
1768 $_pager = 'less';
1769 } elsif (length $_pager == 0 || $_pager eq 'cat') {
1770 $_pager = undef;
1771 }
1772 }
1774 sub run_pager {
1775 return unless -t *STDOUT;
1776 pipe my $rfd, my $wfd or return;
1777 defined(my $pid = fork) or croak $!;
1778 if (!$pid) {
1779 open STDOUT, '>&', $wfd or croak $!;
1780 return;
1781 }
1782 open STDIN, '<&', $rfd or croak $!;
1783 $ENV{LESS} ||= 'FRSX';
1784 exec $_pager or croak "Can't run pager: $! ($_pager)\n";
1785 }
1787 sub get_author_info {
1788 my ($dest, $author, $t, $tz) = @_;
1789 $author =~ s/(?:^\s*|\s*$)//g;
1790 $dest->{a_raw} = $author;
1791 my $_a;
1792 if ($_authors) {
1793 $_a = $rusers{$author} || undef;
1794 }
1795 if (!$_a) {
1796 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
1797 }
1798 $dest->{t} = $t;
1799 $dest->{tz} = $tz;
1800 $dest->{a} = $_a;
1801 # Date::Parse isn't in the standard Perl distro :(
1802 if ($tz =~ s/^\+//) {
1803 $t += tz_to_s_offset($tz);
1804 } elsif ($tz =~ s/^\-//) {
1805 $t -= tz_to_s_offset($tz);
1806 }
1807 $dest->{t_utc} = $t;
1808 }
1810 sub process_commit {
1811 my ($c, $r_min, $r_max, $defer) = @_;
1812 if (defined $r_min && defined $r_max) {
1813 if ($r_min == $c->{r} && $r_min == $r_max) {
1814 show_commit($c);
1815 return 0;
1816 }
1817 return 1 if $r_min == $r_max;
1818 if ($r_min < $r_max) {
1819 # we need to reverse the print order
1820 return 0 if (defined $_limit && --$_limit < 0);
1821 push @$defer, $c;
1822 return 1;
1823 }
1824 if ($r_min != $r_max) {
1825 return 1 if ($r_min < $c->{r});
1826 return 1 if ($r_max > $c->{r});
1827 }
1828 }
1829 return 0 if (defined $_limit && --$_limit < 0);
1830 show_commit($c);
1831 return 1;
1832 }
1834 sub show_commit {
1835 my $c = shift;
1836 if ($_oneline) {
1837 my $x = "\n";
1838 if (my $l = $c->{l}) {
1839 while ($l->[0] =~ /^\s*$/) { shift @$l }
1840 $x = $l->[0];
1841 }
1842 $_l_fmt ||= 'A' . length($c->{r});
1843 print 'r',pack($_l_fmt, $c->{r}),' | ';
1844 print "$c->{c} | " if $_show_commit;
1845 print $x;
1846 } else {
1847 show_commit_normal($c);
1848 }
1849 }
1851 sub show_commit_changed_paths {
1852 my ($c) = @_;
1853 return unless $c->{changed};
1854 print "Changed paths:\n", @{$c->{changed}};
1855 }
1857 sub show_commit_normal {
1858 my ($c) = @_;
1859 print '-' x72, "\nr$c->{r} | ";
1860 print "$c->{c} | " if $_show_commit;
1861 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
1862 localtime($c->{t_utc})), ' | ';
1863 my $nr_line = 0;
1865 if (my $l = $c->{l}) {
1866 while ($l->[$#$l] eq "\n" && $#$l > 0
1867 && $l->[($#$l - 1)] eq "\n") {
1868 pop @$l;
1869 }
1870 $nr_line = scalar @$l;
1871 if (!$nr_line) {
1872 print "1 line\n\n\n";
1873 } else {
1874 if ($nr_line == 1) {
1875 $nr_line = '1 line';
1876 } else {
1877 $nr_line .= ' lines';
1878 }
1879 print $nr_line, "\n";
1880 show_commit_changed_paths($c);
1881 print "\n";
1882 print $_ foreach @$l;
1883 }
1884 } else {
1885 print "1 line\n";
1886 show_commit_changed_paths($c);
1887 print "\n";
1889 }
1890 foreach my $x (qw/raw diff/) {
1891 if ($c->{$x}) {
1892 print "\n";
1893 print $_ foreach @{$c->{$x}}
1894 }
1895 }
1896 }
1898 package Git::SVN;
1899 use strict;
1900 use warnings;
1901 use vars qw/$default/;
1902 use Carp qw/croak/;
1903 use File::Path qw/mkpath/;
1904 use IPC::Open3;
1906 # properties that we do not log:
1907 my %SKIP_PROP;
1908 BEGIN {
1909 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1910 svn:special svn:executable
1911 svn:entry:committed-rev
1912 svn:entry:last-author
1913 svn:entry:uuid
1914 svn:entry:committed-date/;
1915 }
1917 sub init {
1918 my ($class, $id, $url) = @_;
1919 my $self = _new($class, $id);
1920 mkpath(["$self->{dir}/info"]);
1921 if (defined $url) {
1922 $url =~ s!/+$!!; # strip trailing slash
1923 ::s_to_file($url, "$self->{dir}/info/url");
1924 }
1925 $self->{url} = $url;
1926 open my $fh, '>>', $self->{db_path} or croak $!;
1927 close $fh or croak $!;
1928 $self;
1929 }
1931 sub new {
1932 my ($class, $id) = @_;
1933 my $self = _new($class, $id);
1934 $self->{url} = ::file_to_s("$self->{dir}/info/url");
1935 $self;
1936 }
1938 sub refname { "refs/remotes/$_[0]->{id}" }
1940 sub ra {
1941 my ($self) = shift;
1942 $self->{ra} ||= Git::SVN::Ra->new($self->{url});
1943 }
1945 sub copy_remote_ref {
1946 my ($self) = @_;
1947 my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
1948 my $ref = $self->refname;
1949 if (command('ls-remote', $origin, $ref)) {
1950 command_noisy('fetch', $origin, "$ref:$ref");
1951 } elsif ($::_cp_remote && !$::_upgrade) {
1952 die "Unable to find remote reference: $ref on $origin\n";
1953 }
1954 }
1956 sub traverse_ignore {
1957 my ($self, $fh, $path, $r) = @_;
1958 $path =~ s#^/+##g;
1959 my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
1960 my $p = $path;
1961 $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
1962 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1963 if (my $s = $props->{'svn:ignore'}) {
1964 $s =~ s/[\r\n]+/\n/g;
1965 chomp $s;
1966 if (length $p == 0) {
1967 $s =~ s#\n#\n/$p#g;
1968 print $fh "/$s\n";
1969 } else {
1970 $s =~ s#\n#\n/$p/#g;
1971 print $fh "/$p/$s\n";
1972 }
1973 }
1974 foreach (sort keys %$dirent) {
1975 next if $dirent->{$_}->kind != $SVN::Node::dir;
1976 $self->traverse_ignore($fh, "$path/$_", $r);
1977 }
1978 }
1980 # returns the newest SVN revision number and newest commit SHA1
1981 sub last_rev_commit {
1982 my ($self) = @_;
1983 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1984 return ($self->{last_rev}, $self->{last_commit});
1985 }
1986 my $c = ::verify_ref($self->refname.'^0');
1987 if (defined $c && length $c) {
1988 my $rev = (::cmt_metadata($c))[1];
1989 if (defined $rev) {
1990 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1991 return ($rev, $c);
1992 }
1993 }
1994 my $offset = -41; # from tail
1995 my $rl;
1996 open my $fh, '<', $self->{db_path} or
1997 croak "$self->{db_path} not readable: $!\n";
1998 seek $fh, $offset, 2;
1999 $rl = readline $fh;
2000 defined $rl or return (undef, undef);
2001 chomp $rl;
2002 while ($c ne $rl && tell $fh != 0) {
2003 $offset -= 41;
2004 seek $fh, $offset, 2;
2005 $rl = readline $fh;
2006 defined $rl or return (undef, undef);
2007 chomp $rl;
2008 }
2009 my $rev = tell $fh;
2010 croak $! if ($rev < 0);
2011 $rev = ($rev - 41) / 41;
2012 close $fh or croak $!;
2013 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2014 return ($rev, $c);
2015 }
2017 sub parse_revision {
2018 my ($self, $base) = @_;
2019 my $head = $self->ra->get_latest_revnum;
2020 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2021 return ($base + 1, $head) if (defined $base);
2022 return (0, $head);
2023 }
2024 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2025 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2026 if ($::_revision =~ /^BASE:(\d+)$/) {
2027 return ($base + 1, $1) if (defined $base);
2028 return (0, $head);
2029 }
2030 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2031 die "revision argument: $::_revision not understood by git-svn\n",
2032 "Try using the command-line svn client instead\n";
2033 }
2035 sub tmp_index_do {
2036 my ($self, $sub) = @_;
2037 my $old_index = $ENV{GIT_INDEX_FILE};
2038 $ENV{GIT_INDEX_FILE} = $self->{index};
2039 my @ret = &$sub;
2040 if ($old_index) {
2041 $ENV{GIT_INDEX_FILE} = $old_index;
2042 } else {
2043 delete $ENV{GIT_INDEX_FILE};
2044 }
2045 wantarray ? @ret : $ret[0];
2046 }
2048 sub assert_index_clean {
2049 my ($self, $treeish) = @_;
2051 $self->tmp_index_do(sub {
2052 command_noisy('read-tree', $treeish) unless -e $self->{index};
2053 my $x = command_oneline('write-tree');
2054 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2055 /^tree ($::sha1)/mo);
2056 if ($y ne $x) {
2057 unlink $self->{index} or croak $!;
2058 command_noisy('read-tree', $treeish);
2059 }
2060 $x = command_oneline('write-tree');
2061 if ($y ne $x) {
2062 ::fatal "trees ($treeish) $y != $x\n",
2063 "Something is seriously wrong...\n";
2064 }
2065 });
2066 }
2068 sub get_commit_parents {
2069 my ($self, $log_msg, @parents) = @_;
2070 my (%seen, @ret, @tmp);
2071 # commit parents can be conditionally bound to a particular
2072 # svn revision via: "svn_revno=commit_sha1", filter them out here:
2073 foreach my $p (@parents) {
2074 next unless defined $p;
2075 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
2076 push @tmp, $2 if $1 == $log_msg->{revision};
2077 } else {
2078 push @tmp, $p if $p =~ /^$::sha1_short$/o;
2079 }
2080 }
2081 if (my $cur = ::verify_ref($self->refname.'^0')) {
2082 push @tmp, $cur;
2083 }
2084 push @tmp, $_ foreach (@{$log_msg->{parents}}, @tmp);
2085 while (my $p = shift @tmp) {
2086 next if $seen{$p};
2087 $seen{$p} = 1;
2088 push @ret, $p;
2089 # MAXPARENT is defined to 16 in commit-tree.c:
2090 last if @ret >= 16;
2091 }
2092 if (@tmp) {
2093 die "r$log_msg->{revision}: No room for parents:\n\t",
2094 join("\n\t", @tmp), "\n";
2095 }
2096 @ret;
2097 }
2099 sub check_upgrade_needed {
2100 my ($self) = @_;
2101 if (!-r $self->{db_path}) {
2102 -d $self->{dir} or mkpath([$self->{dir}]);
2103 open my $fh, '>>', $self->{db_path} or croak $!;
2104 close $fh;
2105 }
2106 return unless ::verify_ref($self->{id}.'-HEAD^0');
2107 my $head = ::verify_ref($self->refname.'^0');
2108 if ($@ || !$head) {
2109 ::fatal("Please run: $0 rebuild --upgrade\n");
2110 }
2111 }
2113 sub do_git_commit {
2114 my ($self, $log_msg, @parents) = @_;
2115 if (my $c = $self->rev_db_get($log_msg->{revision})) {
2116 croak "$log_msg->{revision} = $c already exists! ",
2117 "Why are we refetching it?\n";
2118 }
2119 my ($name, $email) = ::author_name_email($log_msg->{author}, $self->ra);
2120 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2121 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2122 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2124 my $tree = $log_msg->{tree};
2125 if (!defined $tree) {
2126 $tree = $self->tmp_index_do(sub {
2127 command_oneline('write-tree') });
2128 }
2129 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2131 my @exec = ('git-commit-tree', $tree);
2132 foreach ($self->get_commit_parents($log_msg, @parents)) {
2133 push @exec, '-p', $_;
2134 }
2135 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2136 or croak $!;
2137 print $msg_fh $log_msg->{log} or croak $!;
2138 print $msg_fh "\ngit-svn-id: $self->{ra}->{url}\@$log_msg->{revision}",
2139 " ", $self->ra->uuid,"\n" or croak $!;
2140 $msg_fh->flush == 0 or croak $!;
2141 close $msg_fh or croak $!;
2142 chomp(my $commit = do { local $/; <$out_fh> });
2143 close $out_fh or croak $!;
2144 waitpid $pid, 0;
2145 croak $? if $?;
2146 if ($commit !~ /^$::sha1$/o) {
2147 die "Failed to commit, invalid sha1: $commit\n";
2148 }
2150 command_noisy('update-ref',$self->refname, $commit);
2151 $self->rev_db_set($log_msg->{revision}, $commit);
2153 $self->{last_rev} = $log_msg->{revision};
2154 $self->{last_commit} = $commit;
2155 print "r$log_msg->{revision} = $commit\n";
2156 return $commit;
2157 }
2159 sub do_fetch {
2160 my ($self, $paths, $rev) = @_; #, $author, $date, $msg) = @_;
2161 my $ed = SVN::Git::Fetcher->new($self);
2162 my ($last_rev, @parents);
2163 if ($self->{last_commit}) {
2164 $last_rev = $self->{last_rev};
2165 $ed->{c} = $self->{last_commit};
2166 @parents = ($self->{last_commit});
2167 } else {
2168 $last_rev = $rev;
2169 }
2170 unless ($self->ra->do_update($last_rev, $rev, '', 1, $ed)) {
2171 die "SVN connection failed somewhere...\n";
2172 }
2173 $self->make_log_entry($rev, \@parents, $ed);
2174 }
2176 sub write_untracked {
2177 my ($self, $rev, $fh, $untracked) = @_;
2178 my $h;
2179 print $fh "r$rev\n" or croak $!;
2180 $h = $untracked->{empty};
2181 foreach (sort keys %$h) {
2182 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2183 print $fh " $act: ", uri_encode($_), "\n" or croak $!;
2184 warn "W: $act: $_\n";
2185 }
2186 foreach my $t (qw/dir_prop file_prop/) {
2187 $h = $untracked->{$t} or next;
2188 foreach my $path (sort keys %$h) {
2189 my $ppath = $path eq '' ? '.' : $path;
2190 foreach my $prop (sort keys %{$h->{$path}}) {
2191 next if $SKIP{$prop};
2192 my $v = $h->{$path}->{$prop};
2193 if (defined $v) {
2194 print $fh " +$t: ",
2195 uri_encode($ppath), ' ',
2196 uri_encode($prop), ' ',
2197 uri_encode($v), "\n"
2198 or croak $!;
2199 } else {
2200 print $fh " -$t: ",
2201 uri_encode($ppath), ' ',
2202 uri_encode($prop), "\n"
2203 or croak $!;
2204 }
2205 }
2206 }
2207 }
2208 foreach my $t (qw/absent_file absent_directory/) {
2209 $h = $untracked->{$t} or next;
2210 foreach my $parent (sort keys %$h) {
2211 foreach my $path (sort @{$h->{$parent}}) {
2212 print $fh " $t: ",
2213 uri_encode("$parent/$path"), "\n"
2214 or croak $!;
2215 warn "W: $t: $parent/$path ",
2216 "Insufficient permissions?\n";
2217 }
2218 }
2219 }
2220 }
2222 sub make_log_entry {
2223 my ($self, $rev, $parents, $untracked) = @_;
2224 my $rp = $self->ra->rev_proplist($rev);
2225 my %log_entry = ( parents => $parents || [], revision => $rev,
2226 revprops => $rp, log => '');
2227 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2228 $self->write_untracked($rev, $un, $untracked);
2229 foreach (sort keys %$rp) {
2230 my $v = $rp->{$_};
2231 if (/^svn:(author|date|log)$/) {
2232 $log_entry{$1} = $v;
2233 } else {
2234 print $un " rev_prop: ", uri_encode($_), ' ',
2235 uri_encode($v), "\n";
2236 }
2237 }
2238 close $un or croak $!;
2239 $log_entry{date} = parse_svn_date($log_entry{date});
2240 $log_entry{author} = check_author($log_entry{author});
2241 $log_entry{log} .= "\n";
2242 \%log_entry;
2243 }
2245 sub fetch {
2246 my ($self, @parents) = @_;
2247 my ($last_rev, $last_commit) = $self->last_rev_commit;
2248 my ($base, $head) = $self->parse_revision($last_rev);
2249 return if ($base > $head);
2250 if (defined $last_commit) {
2251 $self->assert_index_clean($last_commit);
2252 }
2253 my $inc = 1000;
2254 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2255 my $err_handler = $SVN::Error::handler;
2256 $SVN::Error::handler = \&skip_unknown_revs;
2257 while (1) {
2258 my @revs;
2259 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
2260 my ($paths, $rev, $author, $date, $msg) = @_;
2261 push @revs, $rev });
2262 foreach (@revs) {
2263 my $log_entry = $self->do_fetch(undef, $_);
2264 $self->do_git_commit($log_entry, @parents);
2265 }
2266 last if $max >= $head;
2267 $min = $max + 1;
2268 $max += $inc;
2269 $max = $head if ($max > $head);
2270 }
2271 $SVN::Error::handler = $err_handler;
2272 }
2274 sub set_tree_cb {
2275 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2276 # TODO: enable and test optimized commits:
2277 if (0 && $rev == ($self->{last_rev} + 1)) {
2278 $log_entry->{revision} = $rev;
2279 $log_entry->{author} = $author;
2280 $self->do_git_commit($log_entry, "$rev=$tree");
2281 } else {
2282 $self->fetch("$rev=$tree");
2283 }
2284 }
2286 sub set_tree {
2287 my ($self, $tree) = (shift, shift);
2288 my $log_entry = get_commit_entry($tree);
2289 unless ($self->{last_rev}) {
2290 fatal("Must have an existing revision to commit\n");
2291 }
2292 my $pool = SVN::Pool->new;
2293 my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
2294 ra => $self->ra->dup,
2295 c => $tree,
2296 svn_path => $self->ra->{svn_path}
2297 },
2298 $self->ra->get_commit_editor(
2299 $log_entry->{log}, sub {
2300 $self->set_tree_cb($log_entry,
2301 $tree, @_);
2302 }),
2303 $pool);
2304 my $mods = $ed->apply_diff($self->{last_commit}, $tree);
2305 if (@$mods == 0) {
2306 print "No changes\nr$self->{last_rev} = $tree\n";
2307 }
2308 $pool->clear;
2309 }
2311 sub skip_unknown_revs {
2312 my ($err) = @_;
2313 my $errno = $err->apr_err();
2314 # Maybe the branch we're tracking didn't
2315 # exist when the repo started, so it's
2316 # not an error if it doesn't, just continue
2317 #
2318 # Wonderfully consistent library, eh?
2319 # 160013 - svn:// and file://
2320 # 175002 - http(s)://
2321 # 175007 - http(s):// (this repo required authorization, too...)
2322 # More codes may be discovered later...
2323 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2324 return;
2325 }
2326 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2327 }
2329 # rev_db:
2330 # Tie::File seems to be prone to offset errors if revisions get sparse,
2331 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2332 # one of my favorite modules is out :< Next up would be one of the DBM
2333 # modules, but I'm not sure which is most portable... So I'll just
2334 # go with something that's plain-text, but still capable of
2335 # being randomly accessed. So here's my ultra-simple fixed-width
2336 # database. All records are 40 characters + "\n", so it's easy to seek
2337 # to a revision: (41 * rev) is the byte offset.
2338 # A record of 40 0s denotes an empty revision.
2339 # And yes, it's still pretty fast (faster than Tie::File).
2341 sub rev_db_set {
2342 my ($self, $rev, $commit) = @_;
2343 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2344 open my $fh, '+<', $self->{db_path} or croak $!;
2345 my $offset = $rev * 41;
2346 # assume that append is the common case:
2347 seek $fh, 0, 2 or croak $!;
2348 my $pos = tell $fh;
2349 if ($pos < $offset) {
2350 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
2351 or croak $!;
2352 }
2353 seek $fh, $offset, 0 or croak $!;
2354 print $fh $commit,"\n" or croak $!;
2355 close $fh or croak $!;
2356 }
2358 sub rev_db_get {
2359 my ($self, $rev) = @_;
2360 my $ret;
2361 my $offset = $rev * 41;
2362 open my $fh, '<', $self->{db_path} or croak $!;
2363 if (seek $fh, $offset, 0) {
2364 $ret = readline $fh;
2365 if (defined $ret) {
2366 chomp $ret;
2367 $ret = undef if ($ret =~ /^0{40}$/);
2368 }
2369 }
2370 close $fh or croak $!;
2371 $ret;
2372 }
2374 sub _new {
2375 my ($class, $id) = @_;
2376 $id ||= $Git::SVN::default;
2377 my $dir = "$ENV{GIT_DIR}/svn/$id";
2378 bless { id => $id, dir => $dir, index => "$dir/index",
2379 db_path => "$dir/.rev_db" }, $class;
2380 }
2383 package Git::SVN::Prompt;
2384 use strict;
2385 use warnings;
2386 require SVN::Core;
2387 use vars qw/$_no_auth_cache $_username/;
2389 sub simple {
2390 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2391 $may_save = undef if $_no_auth_cache;
2392 $default_username = $_username if defined $_username;
2393 if (defined $default_username && length $default_username) {
2394 if (defined $realm && length $realm) {
2395 print STDERR "Authentication realm: $realm\n";
2396 STDERR->flush;
2397 }
2398 $cred->username($default_username);
2399 } else {
2400 username($cred, $realm, $may_save, $pool);
2401 }
2402 $cred->password(_read_password("Password for '" .
2403 $cred->username . "': ", $realm));
2404 $cred->may_save($may_save);
2405 $SVN::_Core::SVN_NO_ERROR;
2406 }
2408 sub ssl_server_trust {
2409 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2410 $may_save = undef if $_no_auth_cache;
2411 print STDERR "Error validating server certificate for '$realm':\n";
2412 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2413 print STDERR " - The certificate is not issued by a trusted ",
2414 "authority. Use the\n",
2415 " fingerprint to validate the certificate manually!\n";
2416 }
2417 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2418 print STDERR " - The certificate hostname does not match.\n";
2419 }
2420 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2421 print STDERR " - The certificate is not yet valid.\n";
2422 }
2423 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2424 print STDERR " - The certificate has expired.\n";
2425 }
2426 if ($failures & $SVN::Auth::SSL::OTHER) {
2427 print STDERR " - The certificate has an unknown error.\n";
2428 }
2429 printf STDERR
2430 "Certificate information:\n".
2431 " - Hostname: %s\n".
2432 " - Valid: from %s until %s\n".
2433 " - Issuer: %s\n".
2434 " - Fingerprint: %s\n",
2435 map $cert_info->$_, qw(hostname valid_from valid_until
2436 issuer_dname fingerprint);
2437 my $choice;
2438 prompt:
2439 print STDERR $may_save ?
2440 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2441 "(R)eject or accept (t)emporarily? ";
2442 STDERR->flush;
2443 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2444 if ($choice =~ /^t$/i) {
2445 $cred->may_save(undef);
2446 } elsif ($choice =~ /^r$/i) {
2447 return -1;
2448 } elsif ($may_save && $choice =~ /^p$/i) {
2449 $cred->may_save($may_save);
2450 } else {
2451 goto prompt;
2452 }
2453 $cred->accepted_failures($failures);
2454 $SVN::_Core::SVN_NO_ERROR;
2455 }
2457 sub ssl_client_cert {
2458 my ($cred, $realm, $may_save, $pool) = @_;
2459 $may_save = undef if $_no_auth_cache;
2460 print STDERR "Client certificate filename: ";
2461 STDERR->flush;
2462 chomp(my $filename = <STDIN>);
2463 $cred->cert_file($filename);
2464 $cred->may_save($may_save);
2465 $SVN::_Core::SVN_NO_ERROR;
2466 }
2468 sub ssl_client_cert_pw {
2469 my ($cred, $realm, $may_save, $pool) = @_;
2470 $may_save = undef if $_no_auth_cache;
2471 $cred->password(_read_password("Password: ", $realm));
2472 $cred->may_save($may_save);
2473 $SVN::_Core::SVN_NO_ERROR;
2474 }
2476 sub username {
2477 my ($cred, $realm, $may_save, $pool) = @_;
2478 $may_save = undef if $_no_auth_cache;
2479 if (defined $realm && length $realm) {
2480 print STDERR "Authentication realm: $realm\n";
2481 }
2482 my $username;
2483 if (defined $_username) {
2484 $username = $_username;
2485 } else {
2486 print STDERR "Username: ";
2487 STDERR->flush;
2488 chomp($username = <STDIN>);
2489 }
2490 $cred->username($username);
2491 $cred->may_save($may_save);
2492 $SVN::_Core::SVN_NO_ERROR;
2493 }
2495 sub _read_password {
2496 my ($prompt, $realm) = @_;
2497 print STDERR $prompt;
2498 STDERR->flush;
2499 require Term::ReadKey;
2500 Term::ReadKey::ReadMode('noecho');
2501 my $password = '';
2502 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2503 last if $key =~ /[\012\015]/; # \n\r
2504 $password .= $key;
2505 }
2506 Term::ReadKey::ReadMode('restore');
2507 print STDERR "\n";
2508 STDERR->flush;
2509 $password;
2510 }
2512 package main;
2514 sub uri_encode {
2515 my ($f) = @_;
2516 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2517 $f
2518 }
2520 sub uri_decode {
2521 my ($f) = @_;
2522 $f =~ tr/+/ /;
2523 $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2524 $f
2525 }
2527 sub libsvn_log_entry {
2528 my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2529 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2530 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2531 or die "Unable to parse date: $date\n";
2532 if (defined $author && length $author > 0 &&
2533 defined $_authors && ! defined $users{$author}) {
2534 die "Author: $author not defined in $_authors file\n";
2535 }
2536 $msg = '' if ($rev == 0 && !defined $msg);
2538 open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2539 my $h;
2540 print $un "r$rev\n" or croak $!;
2541 $h = $untracked->{empty};
2542 foreach (sort keys %$h) {
2543 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2544 print $un " $act: ", uri_encode($_), "\n" or croak $!;
2545 warn "W: $act: $_\n";
2546 }
2547 foreach my $t (qw/dir_prop file_prop/) {
2548 $h = $untracked->{$t} or next;
2549 foreach my $path (sort keys %$h) {
2550 my $ppath = $path eq '' ? '.' : $path;
2551 foreach my $prop (sort keys %{$h->{$path}}) {
2552 next if $SKIP{$prop};
2553 my $v = $h->{$path}->{$prop};
2554 if (defined $v) {
2555 print $un " +$t: ",
2556 uri_encode($ppath), ' ',
2557 uri_encode($prop), ' ',
2558 uri_encode($v), "\n"
2559 or croak $!;
2560 } else {
2561 print $un " -$t: ",
2562 uri_encode($ppath), ' ',
2563 uri_encode($prop), "\n"
2564 or croak $!;
2565 }
2566 }
2567 }
2568 }
2569 foreach my $t (qw/absent_file absent_directory/) {
2570 $h = $untracked->{$t} or next;
2571 foreach my $parent (sort keys %$h) {
2572 foreach my $path (sort @{$h->{$parent}}) {
2573 print $un " $t: ",
2574 uri_encode("$parent/$path"), "\n"
2575 or croak $!;
2576 warn "W: $t: $parent/$path ",
2577 "Insufficient permissions?\n";
2578 }
2579 }
2580 }
2582 # revprops (make this optional? it's an extra network trip...)
2583 my $rp = $SVN->rev_proplist($rev);
2584 foreach (sort keys %$rp) {
2585 next if /^svn:(?:author|date|log)$/;
2586 print $un " rev_prop: ", uri_encode($_), ' ',
2587 uri_encode($rp->{$_}), "\n";
2588 }
2589 close $un or croak $!;
2591 { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2592 author => $author, msg => $msg."\n", parents => $parents || [],
2593 revprops => $rp }
2594 }
2596 sub libsvn_fetch {
2597 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2598 my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2599 my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2600 unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2601 die "SVN connection failed somewhere...\n";
2602 }
2603 libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2604 }
2606 sub svn_grab_base_rev {
2607 my $c = eval { command_oneline([qw/rev-parse --verify/,
2608 "refs/remotes/$GIT_SVN^0"],
2609 { STDERR => 0 }) };
2610 if (defined $c && length $c) {
2611 my ($url, $rev, $uuid) = cmt_metadata($c);
2612 return ($rev, $c) if defined $rev;
2613 }
2614 if ($_no_metadata) {
2615 my $offset = -41; # from tail
2616 my $rl;
2617 open my $fh, '<', $REVDB or
2618 die "--no-metadata specified and $REVDB not readable\n";
2619 seek $fh, $offset, 2;
2620 $rl = readline $fh;
2621 defined $rl or return (undef, undef);
2622 chomp $rl;
2623 while ($c ne $rl && tell $fh != 0) {
2624 $offset -= 41;
2625 seek $fh, $offset, 2;
2626 $rl = readline $fh;
2627 defined $rl or return (undef, undef);
2628 chomp $rl;
2629 }
2630 my $rev = tell $fh;
2631 croak $! if ($rev < -1);
2632 $rev = ($rev - 41) / 41;
2633 close $fh or croak $!;
2634 return ($rev, $c);
2635 }
2636 return (undef, undef);
2637 }
2639 sub libsvn_parse_revision {
2640 my $base = shift;
2641 my $head = $SVN->get_latest_revnum();
2642 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2643 return ($base + 1, $head) if (defined $base);
2644 return (0, $head);
2645 }
2646 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2647 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2648 if ($_revision =~ /^BASE:(\d+)$/) {
2649 return ($base + 1, $1) if (defined $base);
2650 return (0, $head);
2651 }
2652 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2653 die "revision argument: $_revision not understood by git-svn\n",
2654 "Try using the command-line svn client instead\n";
2655 }
2657 sub libsvn_traverse_ignore {
2658 my ($fh, $path, $r) = @_;
2659 $path =~ s#^/+##g;
2660 my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2661 my $p = $path;
2662 $p =~ s#^\Q$SVN->{svn_path}\E/##;
2663 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2664 if (my $s = $props->{'svn:ignore'}) {
2665 $s =~ s/[\r\n]+/\n/g;
2666 chomp $s;
2667 if (length $p == 0) {
2668 $s =~ s#\n#\n/$p#g;
2669 print $fh "/$s\n";
2670 } else {
2671 $s =~ s#\n#\n/$p/#g;
2672 print $fh "/$p/$s\n";
2673 }
2674 }
2675 foreach (sort keys %$dirent) {
2676 next if $dirent->{$_}->kind != $SVN::Node::dir;
2677 libsvn_traverse_ignore($fh, "$path/$_", $r);
2678 }
2679 }
2681 sub revisions_eq {
2682 my ($path, $r0, $r1) = @_;
2683 return 1 if $r0 == $r1;
2684 my $nr = 0;
2685 # should be OK to use Pool here (r1 - r0) should be small
2686 $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2687 return 0 if ($nr > 1);
2688 return 1;
2689 }
2691 sub libsvn_find_parent_branch {
2692 my ($paths, $rev, $author, $date, $msg) = @_;
2693 my $svn_path = '/'.$SVN->{svn_path};
2695 # look for a parent from another branch:
2696 my $i = $paths->{$svn_path} or return;
2697 my $branch_from = $i->copyfrom_path or return;
2698 my $r = $i->copyfrom_rev;
2699 print STDERR "Found possible branch point: ",
2700 "$branch_from => $svn_path, $r\n";
2701 $branch_from =~ s#^/##;
2702 my $l_map = {};
2703 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2704 my $url = $SVN->{repos_root};
2705 defined $l_map->{$url} or return;
2706 my $id = $l_map->{$url}->{$branch_from};
2707 if (!defined $id && $_follow_parent) {
2708 print STDERR "Following parent: $branch_from\@$r\n";
2709 # auto create a new branch and follow it
2710 $id = basename($branch_from);
2711 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2712 while (-r "$GIT_DIR/svn/$id") {
2713 # just grow a tail if we're not unique enough :x
2714 $id .= '-';
2715 }
2716 }
2717 return unless defined $id;
2719 my ($r0, $parent) = find_rev_before($r,$id,1);
2720 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2721 defined(my $pid = fork) or croak $!;
2722 if (!$pid) {
2723 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2724 init_vars();
2725 $SVN_URL = "$url/$branch_from";
2726 $SVN = undef;
2727 setup_git_svn();
2728 # we can't assume SVN_URL exists at r+1:
2729 $_revision = "0:$r";
2730 fetch_lib();
2731 exit 0;
2732 }
2733 waitpid $pid, 0;
2734 croak $? if $?;
2735 ($r0, $parent) = find_rev_before($r,$id,1);
2736 }
2737 return unless (defined $r0 && defined $parent);
2738 if (revisions_eq($branch_from, $r0, $r)) {
2739 unlink $GIT_SVN_INDEX;
2740 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2741 command_noisy('read-tree', $parent);
2742 unless ($SVN->can_do_switch) {
2743 return _libsvn_new_tree($paths, $rev, $author, $date,
2744 $msg, [$parent]);
2745 }
2746 # do_switch works with svn/trunk >= r22312, but that is not
2747 # included with SVN 1.4.2 (the latest version at the moment),
2748 # so we can't rely on it.
2749 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2750 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2751 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2752 die "SVN connection failed somewhere...\n";
2753 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2754 }
2755 print STDERR "Nope, branch point not imported or unknown\n";
2756 return undef;
2757 }
2759 sub libsvn_new_tree {
2760 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2761 return $log_entry;
2762 }
2763 my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2764 _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2765 }
2767 sub _libsvn_new_tree {
2768 my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2769 my $ed = SVN::Git::Fetcher->new({q => $_q});
2770 unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2771 die "SVN connection failed somewhere...\n";
2772 }
2773 libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2774 }
2776 sub find_graft_path_commit {
2777 my ($tree_paths, $p1, $r1) = @_;
2778 foreach my $x (keys %$tree_paths) {
2779 next unless ($p1 =~ /^\Q$x\E/);
2780 my $i = $tree_paths->{$x};
2781 my ($r0, $parent) = find_rev_before($r1,$i,1);
2782 return $parent if (defined $r0 && $r0 == $r1);
2783 print STDERR "r$r1 of $i not imported\n";
2784 next;
2785 }
2786 return undef;
2787 }
2789 sub find_graft_path_parents {
2790 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2791 foreach my $x (keys %$tree_paths) {
2792 next unless ($p0 =~ /^\Q$x\E/);
2793 my $i = $tree_paths->{$x};
2794 my ($r, $parent) = find_rev_before($r0, $i, 1);
2795 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2796 my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2797 my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2798 next if ($url_a && $url_b && $url_a eq $url_b &&
2799 $uuid_b eq $uuid_a);
2800 $grafts->{$c}->{$parent} = 1;
2801 }
2802 }
2803 }
2805 sub libsvn_graft_file_copies {
2806 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2807 foreach (keys %$paths) {
2808 my $i = $paths->{$_};
2809 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2810 $i->copyfrom_rev);
2811 next unless (defined $p0 && defined $r0);
2813 my $p1 = $_;
2814 $p1 =~ s#^/##;
2815 $p0 =~ s#^/##;
2816 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2817 next unless $c;
2818 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2819 }
2820 }
2822 sub set_index {
2823 my $old = $ENV{GIT_INDEX_FILE};
2824 $ENV{GIT_INDEX_FILE} = shift;
2825 return $old;
2826 }
2828 sub restore_index {
2829 my ($old) = @_;
2830 if (defined $old) {
2831 $ENV{GIT_INDEX_FILE} = $old;
2832 } else {
2833 delete $ENV{GIT_INDEX_FILE};
2834 }
2835 }
2837 sub libsvn_commit_cb {
2838 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2839 if ($_optimize_commits && $rev == ($r_last + 1)) {
2840 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2841 $log->{tree} = get_tree_from_treeish($c);
2842 my $cmt = git_commit($log, $cmt_last, $c);
2843 my @diff = command('diff-tree', $cmt, $c);
2844 if (@diff) {
2845 print STDERR "Trees differ: $cmt $c\n",
2846 join('',@diff),"\n";
2847 exit 1;
2848 }
2849 } else {
2850 fetch("$rev=$c");
2851 }
2852 }
2854 sub libsvn_ls_fullurl {
2855 my $fullurl = shift;
2856 my $ra = Git::SVN::Ra->new($fullurl);
2857 my @ret;
2858 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
2859 my ($dirent, undef, undef) = $ra->get_dir('', $r);
2860 foreach my $d (sort keys %$dirent) {
2861 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2862 push @ret, "$d/"; # add '/' for compat with cli svn
2863 }
2864 }
2865 return @ret;
2866 }
2868 sub libsvn_skip_unknown_revs {
2869 my $err = shift;
2870 my $errno = $err->apr_err();
2871 # Maybe the branch we're tracking didn't
2872 # exist when the repo started, so it's
2873 # not an error if it doesn't, just continue
2874 #
2875 # Wonderfully consistent library, eh?
2876 # 160013 - svn:// and file://
2877 # 175002 - http(s)://
2878 # 175007 - http(s):// (this repo required authorization, too...)
2879 # More codes may be discovered later...
2880 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2881 return;
2882 }
2883 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2884 };
2886 # Tie::File seems to be prone to offset errors if revisions get sparse,
2887 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2888 # one of my favorite modules is out :< Next up would be one of the DBM
2889 # modules, but I'm not sure which is most portable... So I'll just
2890 # go with something that's plain-text, but still capable of
2891 # being randomly accessed. So here's my ultra-simple fixed-width
2892 # database. All records are 40 characters + "\n", so it's easy to seek
2893 # to a revision: (41 * rev) is the byte offset.
2894 # A record of 40 0s denotes an empty revision.
2895 # And yes, it's still pretty fast (faster than Tie::File).
2896 sub revdb_set {
2897 my ($file, $rev, $commit) = @_;
2898 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2899 open my $fh, '+<', $file or croak $!;
2900 my $offset = $rev * 41;
2901 # assume that append is the common case:
2902 seek $fh, 0, 2 or croak $!;
2903 my $pos = tell $fh;
2904 if ($pos < $offset) {
2905 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2906 }
2907 seek $fh, $offset, 0 or croak $!;
2908 print $fh $commit,"\n";
2909 close $fh or croak $!;
2910 }
2912 sub revdb_get {
2913 my ($file, $rev) = @_;
2914 my $ret;
2915 my $offset = $rev * 41;
2916 open my $fh, '<', $file or croak $!;
2917 seek $fh, $offset, 0;
2918 if (tell $fh == $offset) {
2919 $ret = readline $fh;
2920 if (defined $ret) {
2921 chomp $ret;
2922 $ret = undef if ($ret =~ /^0{40}$/);
2923 }
2924 }
2925 close $fh or croak $!;
2926 return $ret;
2927 }
2929 sub copy_remote_ref {
2930 my $origin = $_cp_remote ? $_cp_remote : 'origin';
2931 my $ref = "refs/remotes/$GIT_SVN";
2932 if (command('ls-remote', $origin, $ref)) {
2933 command_noisy('fetch', $origin, "$ref:$ref");
2934 } elsif ($_cp_remote && !$_upgrade) {
2935 die "Unable to find remote reference: ",
2936 "refs/remotes/$GIT_SVN on $origin\n";
2937 }
2938 }
2940 {
2941 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2942 $SVN::Node::dir.$SVN::Node::unknown.
2943 $SVN::Node::none.$SVN::Node::file.
2944 $SVN::Node::dir.$SVN::Node::unknown.
2945 $SVN::Auth::SSL::CNMISMATCH.
2946 $SVN::Auth::SSL::NOTYETVALID.
2947 $SVN::Auth::SSL::EXPIRED.
2948 $SVN::Auth::SSL::UNKNOWNCA.
2949 $SVN::Auth::SSL::OTHER;
2950 }
2952 package SVN::Git::Fetcher;
2953 use vars qw/@ISA/;
2954 use strict;
2955 use warnings;
2956 use Carp qw/croak/;
2957 use IO::File qw//;
2959 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2960 sub new {
2961 my ($class, $git_svn) = @_;
2962 my $self = SVN::Delta::Editor->new;
2963 bless $self, $class;
2964 $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2965 $self->{q} = $git_svn->{q};
2966 $self->{empty} = {};
2967 $self->{dir_prop} = {};
2968 $self->{file_prop} = {};
2969 $self->{absent_dir} = {};
2970 $self->{absent_file} = {};
2971 ($self->{gui}, $self->{ctx}) = command_input_pipe(
2972 qw/update-index -z --index-info/);
2973 require Digest::MD5;
2974 $self;
2975 }
2977 sub open_root {
2978 { path => '' };
2979 }
2981 sub open_directory {
2982 my ($self, $path, $pb, $rev) = @_;
2983 { path => $path };
2984 }
2986 sub delete_entry {
2987 my ($self, $path, $rev, $pb) = @_;
2988 my $gui = $self->{gui};
2990 # remove entire directories.
2991 if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2992 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2993 -r --name-only -z/,
2994 $self->{c}, '--', $path);
2995 local $/ = "\0";
2996 while (<$ls>) {
2997 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2998 print "\tD\t$_\n" unless $self->{q};
2999 }
3000 print "\tD\t$path/\n" unless $self->{q};
3001 command_close_pipe($ls, $ctx);
3002 $self->{empty}->{$path} = 0
3003 } else {
3004 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
3005 print "\tD\t$path\n" unless $self->{q};
3006 }
3007 undef;
3008 }
3010 sub open_file {
3011 my ($self, $path, $pb, $rev) = @_;
3012 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
3013 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3014 unless (defined $mode && defined $blob) {
3015 die "$path was not found in commit $self->{c} (r$rev)\n";
3016 }
3017 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3018 pool => SVN::Pool->new, action => 'M' };
3019 }
3021 sub add_file {
3022 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3023 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3024 delete $self->{empty}->{$dir};
3025 { path => $path, mode_a => 100644, mode_b => 100644,
3026 pool => SVN::Pool->new, action => 'A' };
3027 }
3029 sub add_directory {
3030 my ($self, $path, $cp_path, $cp_rev) = @_;
3031 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3032 delete $self->{empty}->{$dir};
3033 $self->{empty}->{$path} = 1;
3034 { path => $path };
3035 }
3037 sub change_dir_prop {
3038 my ($self, $db, $prop, $value) = @_;
3039 $self->{dir_prop}->{$db->{path}} ||= {};
3040 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3041 undef;
3042 }
3044 sub absent_directory {
3045 my ($self, $path, $pb) = @_;
3046 $self->{absent_dir}->{$pb->{path}} ||= [];
3047 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3048 undef;
3049 }
3051 sub absent_file {
3052 my ($self, $path, $pb) = @_;
3053 $self->{absent_file}->{$pb->{path}} ||= [];
3054 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3055 undef;
3056 }
3058 sub change_file_prop {
3059 my ($self, $fb, $prop, $value) = @_;
3060 if ($prop eq 'svn:executable') {
3061 if ($fb->{mode_b} != 120000) {
3062 $fb->{mode_b} = defined $value ? 100755 : 100644;
3063 }
3064 } elsif ($prop eq 'svn:special') {
3065 $fb->{mode_b} = defined $value ? 120000 : 100644;
3066 } else {
3067 $self->{file_prop}->{$fb->{path}} ||= {};
3068 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3069 }
3070 undef;
3071 }
3073 sub apply_textdelta {
3074 my ($self, $fb, $exp) = @_;
3075 my $fh = IO::File->new_tmpfile;
3076 $fh->autoflush(1);
3077 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3078 # (but $base does not,) so dup() it for reading in close_file
3079 open my $dup, '<&', $fh or croak $!;
3080 my $base = IO::File->new_tmpfile;
3081 $base->autoflush(1);
3082 if ($fb->{blob}) {
3083 defined (my $pid = fork) or croak $!;
3084 if (!$pid) {
3085 open STDOUT, '>&', $base or croak $!;
3086 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
3087 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
3088 }
3089 waitpid $pid, 0;
3090 croak $? if $?;
3092 if (defined $exp) {
3093 seek $base, 0, 0 or croak $!;
3094 my $md5 = Digest::MD5->new;
3095 $md5->addfile($base);
3096 my $got = $md5->hexdigest;
3097 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3098 "expected: $exp\n",
3099 " got: $got\n" if ($got ne $exp);
3100 }
3101 }
3102 seek $base, 0, 0 or croak $!;
3103 $fb->{fh} = $dup;
3104 $fb->{base} = $base;
3105 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3106 }
3108 sub close_file {
3109 my ($self, $fb, $exp) = @_;
3110 my $hash;
3111 my $path = $fb->{path};
3112 if (my $fh = $fb->{fh}) {
3113 seek($fh, 0, 0) or croak $!;
3114 my $md5 = Digest::MD5->new;
3115 $md5->addfile($fh);
3116 my $got = $md5->hexdigest;
3117 die "Checksum mismatch: $path\n",
3118 "expected: $exp\n got: $got\n" if ($got ne $exp);
3119 seek($fh, 0, 0) or croak $!;
3120 if ($fb->{mode_b} == 120000) {
3121 read($fh, my $buf, 5) == 5 or croak $!;
3122 $buf eq 'link ' or die "$path has mode 120000",
3123 "but is not a link\n";
3124 }
3125 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3126 if (!$pid) {
3127 open STDIN, '<&', $fh or croak $!;
3128 exec qw/git-hash-object -w --stdin/ or croak $!;
3129 }
3130 chomp($hash = do { local $/; <$out> });
3131 close $out or croak $!;
3132 close $fh or croak $!;
3133 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3134 close $fb->{base} or croak $!;
3135 } else {
3136 $hash = $fb->{blob} or die "no blob information\n";
3137 }
3138 $fb->{pool}->clear;
3139 my $gui = $self->{gui};
3140 print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
3141 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
3142 undef;
3143 }
3145 sub abort_edit {
3146 my $self = shift;
3147 eval { command_close_pipe($self->{gui}, $self->{ctx}) };
3148 $self->SUPER::abort_edit(@_);
3149 }
3151 sub close_edit {
3152 my $self = shift;
3153 command_close_pipe($self->{gui}, $self->{ctx});
3154 $self->{git_commit_ok} = 1;
3155 $self->SUPER::close_edit(@_);
3156 }
3158 package SVN::Git::Editor;
3159 use vars qw/@ISA/;
3160 use strict;
3161 use warnings;
3162 use Carp qw/croak/;
3163 use IO::File;
3165 sub new {
3166 my $class = shift;
3167 my $git_svn = shift;
3168 my $self = SVN::Delta::Editor->new(@_);
3169 bless $self, $class;
3170 foreach (qw/svn_path c r ra /) {
3171 die "$_ required!\n" unless (defined $git_svn->{$_});
3172 $self->{$_} = $git_svn->{$_};
3173 }
3174 $self->{pool} = SVN::Pool->new;
3175 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3176 $self->{rm} = { };
3177 require Digest::MD5;
3178 return $self;
3179 }
3181 sub split_path {
3182 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3183 }
3185 sub repo_path {
3186 (defined $_[1] && length $_[1]) ? $_[1] : ''
3187 }
3189 sub url_path {
3190 my ($self, $path) = @_;
3191 $self->{ra}->{url} . '/' . $self->repo_path($path);
3192 }
3194 sub rmdirs {
3195 my ($self, $q) = @_;
3196 my $rm = $self->{rm};
3197 delete $rm->{''}; # we never delete the url we're tracking
3198 return unless %$rm;
3200 foreach (keys %$rm) {
3201 my @d = split m#/#, $_;
3202 my $c = shift @d;
3203 $rm->{$c} = 1;
3204 while (@d) {
3205 $c .= '/' . shift @d;
3206 $rm->{$c} = 1;
3207 }
3208 }
3209 delete $rm->{$self->{svn_path}};
3210 delete $rm->{''}; # we never delete the url we're tracking
3211 return unless %$rm;
3213 my ($fh, $ctx) = command_output_pipe(
3214 qw/ls-tree --name-only -r -z/, $self->{c});
3215 local $/ = "\0";
3216 while (<$fh>) {
3217 chomp;
3218 my @dn = split m#/#, $_;
3219 while (pop @dn) {
3220 delete $rm->{join '/', @dn};
3221 }
3222 unless (%$rm) {
3223 close $fh;
3224 return;
3225 }
3226 }
3227 command_close_pipe($fh, $ctx);
3229 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3230 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3231 $self->close_directory($bat->{$d}, $p);
3232 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3233 print "\tD+\t$d/\n" unless $q;
3234 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3235 delete $bat->{$d};
3236 }
3237 }
3239 sub open_or_add_dir {
3240 my ($self, $full_path, $baton) = @_;
3241 my $t = $self->{ra}->check_path($full_path, $self->{r});
3242 if ($t == $SVN::Node::none) {
3243 return $self->add_directory($full_path, $baton,
3244 undef, -1, $self->{pool});
3245 } elsif ($t == $SVN::Node::dir) {
3246 return $self->open_directory($full_path, $baton,
3247 $self->{r}, $self->{pool});
3248 }
3249 print STDERR "$full_path already exists in repository at ",
3250 "r$self->{r} and it is not a directory (",
3251 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3252 exit 1;
3253 }
3255 sub ensure_path {
3256 my ($self, $path) = @_;
3257 my $bat = $self->{bat};
3258 $path = $self->repo_path($path);
3259 return $bat->{''} unless (length $path);
3260 my @p = split m#/+#, $path;
3261 my $c = shift @p;
3262 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3263 while (@p) {
3264 my $c0 = $c;
3265 $c .= '/' . shift @p;
3266 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3267 }
3268 return $bat->{$c};
3269 }
3271 sub A {
3272 my ($self, $m, $q) = @_;
3273 my ($dir, $file) = split_path($m->{file_b});
3274 my $pbat = $self->ensure_path($dir);
3275 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3276 undef, -1);
3277 print "\tA\t$m->{file_b}\n" unless $q;
3278 $self->chg_file($fbat, $m);
3279 $self->close_file($fbat,undef,$self->{pool});
3280 }
3282 sub C {
3283 my ($self, $m, $q) = @_;
3284 my ($dir, $file) = split_path($m->{file_b});
3285 my $pbat = $self->ensure_path($dir);
3286 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3287 $self->url_path($m->{file_a}), $self->{r});
3288 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3289 $self->chg_file($fbat, $m);
3290 $self->close_file($fbat,undef,$self->{pool});
3291 }
3293 sub delete_entry {
3294 my ($self, $path, $pbat) = @_;
3295 my $rpath = $self->repo_path($path);
3296 my ($dir, $file) = split_path($rpath);
3297 $self->{rm}->{$dir} = 1;
3298 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3299 }
3301 sub R {
3302 my ($self, $m, $q) = @_;
3303 my ($dir, $file) = split_path($m->{file_b});
3304 my $pbat = $self->ensure_path($dir);
3305 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3306 $self->url_path($m->{file_a}), $self->{r});
3307 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3308 $self->chg_file($fbat, $m);
3309 $self->close_file($fbat,undef,$self->{pool});
3311 ($dir, $file) = split_path($m->{file_a});
3312 $pbat = $self->ensure_path($dir);
3313 $self->delete_entry($m->{file_a}, $pbat);
3314 }
3316 sub M {
3317 my ($self, $m, $q) = @_;
3318 my ($dir, $file) = split_path($m->{file_b});
3319 my $pbat = $self->ensure_path($dir);
3320 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3321 $pbat,$self->{r},$self->{pool});
3322 print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3323 $self->chg_file($fbat, $m);
3324 $self->close_file($fbat,undef,$self->{pool});
3325 }
3327 sub T { shift->M(@_) }
3329 sub change_file_prop {
3330 my ($self, $fbat, $pname, $pval) = @_;
3331 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3332 }
3334 sub chg_file {
3335 my ($self, $fbat, $m) = @_;
3336 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3337 $self->change_file_prop($fbat,'svn:executable','*');
3338 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3339 $self->change_file_prop($fbat,'svn:executable',undef);
3340 }
3341 my $fh = IO::File->new_tmpfile or croak $!;
3342 if ($m->{mode_b} =~ /^120/) {
3343 print $fh 'link ' or croak $!;
3344 $self->change_file_prop($fbat,'svn:special','*');
3345 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3346 $self->change_file_prop($fbat,'svn:special',undef);
3347 }
3348 defined(my $pid = fork) or croak $!;
3349 if (!$pid) {
3350 open STDOUT, '>&', $fh or croak $!;
3351 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3352 }
3353 waitpid $pid, 0;
3354 croak $? if $?;
3355 $fh->flush == 0 or croak $!;
3356 seek $fh, 0, 0 or croak $!;
3358 my $md5 = Digest::MD5->new;
3359 $md5->addfile($fh) or croak $!;
3360 seek $fh, 0, 0 or croak $!;
3362 my $exp = $md5->hexdigest;
3363 my $pool = SVN::Pool->new;
3364 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3365 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3366 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3367 $pool->clear;
3369 close $fh or croak $!;
3370 }
3372 sub D {
3373 my ($self, $m, $q) = @_;
3374 my ($dir, $file) = split_path($m->{file_b});
3375 my $pbat = $self->ensure_path($dir);
3376 print "\tD\t$m->{file_b}\n" unless $q;
3377 $self->delete_entry($m->{file_b}, $pbat);
3378 }
3380 sub close_edit {
3381 my ($self) = @_;
3382 my ($p,$bat) = ($self->{pool}, $self->{bat});
3383 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3384 $self->close_directory($bat->{$_}, $p);
3385 }
3386 $self->SUPER::close_edit($p);
3387 $p->clear;
3388 }
3390 sub abort_edit {
3391 my ($self) = @_;
3392 $self->SUPER::abort_edit($self->{pool});
3393 $self->{pool}->clear;
3394 }
3396 package Git::SVN::Ra;
3397 use vars qw/@ISA $config_dir/;
3398 use strict;
3399 use warnings;
3400 my ($can_do_switch);
3402 BEGIN {
3403 # enforce temporary pool usage for some simple functions
3404 my $e;
3405 foreach (qw/get_latest_revnum rev_proplist get_file
3406 check_path get_dir get_uuid get_repos_root/) {
3407 $e .= "sub $_ {
3408 my \$self = shift;
3409 my \$pool = SVN::Pool->new;
3410 my \@ret = \$self->SUPER::$_(\@_,\$pool);
3411 \$pool->clear;
3412 wantarray ? \@ret : \$ret[0]; }\n";
3413 }
3414 eval $e;
3415 }
3417 sub new {
3418 my ($class, $url) = @_;
3419 SVN::_Core::svn_config_ensure($config_dir, undef);
3420 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3421 SVN::Client::get_simple_provider(),
3422 SVN::Client::get_ssl_server_trust_file_provider(),
3423 SVN::Client::get_simple_prompt_provider(
3424 \&Git::SVN::Prompt::simple, 2),
3425 SVN::Client::get_ssl_client_cert_prompt_provider(
3426 \&Git::SVN::Prompt::ssl_client_cert, 2),
3427 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3428 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3429 SVN::Client::get_username_provider(),
3430 SVN::Client::get_ssl_server_trust_prompt_provider(
3431 \&Git::SVN::Prompt::ssl_server_trust),
3432 SVN::Client::get_username_prompt_provider(
3433 \&Git::SVN::Prompt::username, 2),
3434 ]);
3435 my $config = SVN::Core::config_get_config($config_dir);
3436 my $self = SVN::Ra->new(url => $url, auth => $baton,
3437 config => $config,
3438 pool => SVN::Pool->new,
3439 auth_provider_callbacks => $callbacks);
3440 $self->{svn_path} = $url;
3441 $self->{repos_root} = $self->get_repos_root;
3442 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
3443 bless $self, $class;
3444 }
3446 sub DESTROY {
3447 my $self = shift;
3448 $self->{pool}->clear if $self->{pool};
3449 $self->SUPER::DESTROY(@_);
3450 }
3452 sub dup {
3453 my ($self) = @_;
3454 my $dup = SVN::Ra->new(pool => SVN::Pool->new,
3455 map { $_ => $self->{$_} } qw/config url
3456 auth auth_provider_callbacks repos_root svn_path/);
3457 bless $dup, ref $self;
3458 }
3460 sub get_log {
3461 my ($self, @args) = @_;
3462 my $pool = SVN::Pool->new;
3463 $args[4]-- if $args[4] && ! $::_follow_parent;
3464 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3465 my $ret = $self->SUPER::get_log(@args, $pool);
3466 $pool->clear;
3467 $ret;
3468 }
3470 sub get_commit_editor {
3471 my ($self, $msg, $cb, $pool) = @_;
3472 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3473 $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3474 }
3476 sub uuid {
3477 my ($self) = @_;
3478 $self->{uuid} ||= $self->get_uuid;
3479 }
3481 sub gs_do_update {
3482 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3483 my $pool = SVN::Pool->new;
3484 my $reporter = $self->do_update($rev_b, $path, $recurse,
3485 $editor, $pool);
3486 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3487 my $new = ($rev_a == $rev_b);
3488 $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3489 $reporter->finish_report($pool);
3490 $pool->clear;
3491 $editor->{git_commit_ok};
3492 }
3494 sub gs_do_switch {
3495 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3496 my $pool = SVN::Pool->new;
3497 my $reporter = $self->do_switch($rev_b, $path, $recurse,
3498 $url_b, $editor, $pool);
3499 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3500 $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3501 $reporter->finish_report($pool);
3502 $pool->clear;
3503 $editor->{git_commit_ok};
3504 }
3506 sub can_do_switch {
3507 my $self = shift;
3508 unless (defined $can_do_switch) {
3509 my $pool = SVN::Pool->new;
3510 my $rep = eval {
3511 $self->do_switch(1, '', 0, $self->{url},
3512 SVN::Delta::Editor->new, $pool);
3513 };
3514 if ($@) {
3515 $can_do_switch = 0;
3516 } else {
3517 $rep->abort_report($pool);
3518 $can_do_switch = 1;
3519 }
3520 $pool->clear;
3521 }
3522 $can_do_switch;
3523 }
3525 __END__
3527 Data structures:
3529 $log_msg hashref as returned by libsvn_log_entry()
3530 {
3531 msg => 'whitespace-formatted log entry
3532 ', # trailing newline is preserved
3533 revision => '8', # integer
3534 date => '2004-02-24T17:01:44.108345Z', # commit date
3535 author => 'committer name'
3536 };
3538 @mods = array of diff-index line hashes, each element represents one line
3539 of diff-index output
3541 diff-index line ($m hash)
3542 {
3543 mode_a => first column of diff-index output, no leading ':',
3544 mode_b => second column of diff-index output,
3545 sha1_b => sha1sum of the final blob,
3546 chg => change type [MCRADT],
3547 file_a => original file name of a file (iff chg is 'C' or 'R')
3548 file_b => new/current file name of a file (any chg)
3549 }
3550 ;
3552 # retval of read_url_paths{,_all}();
3553 $l_map = {
3554 # repository root url
3555 'https://svn.musicpd.org' => {
3556 # repository path # GIT_SVN_ID
3557 'mpd/trunk' => 'trunk',
3558 'mpd/tags/0.11.5' => 'tags/0.11.5',
3559 },
3560 }
3562 Notes:
3563 I don't trust the each() function on unless I created %hash myself
3564 because the internal iterator may not have started at base.