1#!/usr/bin/env perl
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11$VERSION = '@@GIT_VERSION@@';
12
13use Cwd qw/abs_path/;
14$GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15$ENV{GIT_DIR} = $GIT_DIR;
16
17my $LC_ALL = $ENV{LC_ALL};
18my $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
23
24# If SVN:: library support is added, please make the dependencies
25# optional and preserve the capability to use the command-line client.
26# use eval { require SVN::... } to make it lazy load
27# We don't use any modules not in the standard Perl distribution:
28use Carp qw/croak/;
29use IO::File qw//;
30use File::Basename qw/dirname basename/;
31use File::Path qw/mkpath/;
32use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
33use File::Spec qw//;
34use File::Copy qw/copy/;
35use POSIX qw/strftime/;
36use IPC::Open3;
37use Memoize;
38memoize('revisions_eq');
39memoize('cmt_metadata');
40memoize('get_commit_time');
41
42my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
43
44sub nag_lib {
45 print STDERR <<EOF;
46! Please consider installing the SVN Perl libraries (version 1.1.0 or
47! newer). You will generally get better performance and fewer bugs,
48! especially if you:
49! 1) have a case-insensitive filesystem
50! 2) replace symlinks with files (and vice-versa) in commits
51
52EOF
53}
54
55$_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
56libsvn_load();
57nag_lib() unless $_use_lib;
58
59my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
60my $sha1 = qr/[a-f\d]{40}/;
61my $sha1_short = qr/[a-f\d]{4,40}/;
62my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
63 $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
64 $_repack, $_repack_nr, $_repack_flags, $_q,
65 $_message, $_file, $_follow_parent, $_no_metadata,
66 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
67 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
68 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
69 $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive);
70my (@_branch_from, %tree_map, %users, %rusers, %equiv);
71my ($_svn_co_url_revs, $_svn_pg_peg_revs);
72my @repo_path_split_cache;
73
74my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
75 'branch|b=s' => \@_branch_from,
76 'follow-parent|follow' => \$_follow_parent,
77 'branch-all-refs|B' => \$_branch_all_refs,
78 'authors-file|A=s' => \$_authors,
79 'repack:i' => \$_repack,
80 'no-metadata' => \$_no_metadata,
81 'quiet|q' => \$_q,
82 'ignore-nodate' => \$_ignore_nodate,
83 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
84
85my ($_trunk, $_tags, $_branches);
86my %multi_opts = ( 'trunk|T=s' => \$_trunk,
87 'tags|t=s' => \$_tags,
88 'branches|b=s' => \$_branches );
89my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
90my %cmt_opts = ( 'edit|e' => \$_edit,
91 'rmdir' => \$_rmdir,
92 'find-copies-harder' => \$_find_copies_harder,
93 'l=i' => \$_l,
94 'copy-similarity|C=i'=> \$_cp_similarity
95);
96
97my %cmd = (
98 fetch => [ \&fetch, "Download new revisions from SVN",
99 { 'revision|r=s' => \$_revision, %fc_opts } ],
100 init => [ \&init, "Initialize a repo for tracking" .
101 " (requires URL argument)",
102 \%init_opts ],
103 commit => [ \&commit, "Commit git revisions to SVN",
104 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
105 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
106 { 'revision|r=i' => \$_revision } ],
107 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
108 { 'no-ignore-externals' => \$_no_ignore_ext,
109 'copy-remote|remote=s' => \$_cp_remote,
110 'upgrade' => \$_upgrade } ],
111 'graft-branches' => [ \&graft_branches,
112 'Detect merges/branches from already imported history',
113 { 'merge-rx|m' => \@_opt_m,
114 'branch|b=s' => \@_branch_from,
115 'branch-all-refs|B' => \$_branch_all_refs,
116 'no-default-regex' => \$_no_default_regex,
117 'no-graft-copy' => \$_no_graft_copy } ],
118 'multi-init' => [ \&multi_init,
119 'Initialize multiple trees (like git-svnimport)',
120 { %multi_opts, %fc_opts } ],
121 'multi-fetch' => [ \&multi_fetch,
122 'Fetch multiple trees (like git-svnimport)',
123 \%fc_opts ],
124 'log' => [ \&show_log, 'Show commit logs',
125 { 'limit=i' => \$_limit,
126 'revision|r=s' => \$_revision,
127 'verbose|v' => \$_verbose,
128 'incremental' => \$_incremental,
129 'oneline' => \$_oneline,
130 'show-commit' => \$_show_commit,
131 'non-recursive' => \$_non_recursive,
132 'authors-file|A=s' => \$_authors,
133 } ],
134 'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
135 { 'message|m=s' => \$_message,
136 'file|F=s' => \$_file,
137 %cmt_opts } ],
138 dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
139 { 'merge|m|M' => \$_merge,
140 'strategy|s=s' => \$_strategy,
141 'dry-run|n' => \$_dry_run,
142 %cmt_opts } ],
143);
144
145my $cmd;
146for (my $i = 0; $i < @ARGV; $i++) {
147 if (defined $cmd{$ARGV[$i]}) {
148 $cmd = $ARGV[$i];
149 splice @ARGV, $i, 1;
150 last;
151 }
152};
153
154my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
155
156read_repo_config(\%opts);
157my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
158 'version|V' => \$_version,
159 'id|i=s' => \$GIT_SVN);
160exit 1 if (!$rv && $cmd ne 'log');
161
162set_default_vals();
163usage(0) if $_help;
164version() if $_version;
165usage(1) unless defined $cmd;
166init_vars();
167load_authors() if $_authors;
168load_all_refs() if $_branch_all_refs;
169svn_compat_check() unless $_use_lib;
170migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
171$cmd{$cmd}->[0]->(@ARGV);
172exit 0;
173
174####################### primary functions ######################
175sub usage {
176 my $exit = shift || 0;
177 my $fd = $exit ? \*STDERR : \*STDOUT;
178 print $fd <<"";
179git-svn - bidirectional operations between a single Subversion tree and git
180Usage: $0 <command> [options] [arguments]\n
181
182 print $fd "Available commands:\n" unless $cmd;
183
184 foreach (sort keys %cmd) {
185 next if $cmd && $cmd ne $_;
186 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
187 foreach (keys %{$cmd{$_}->[2]}) {
188 # prints out arguments as they should be passed:
189 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
190 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
191 "--$_" : "-$_" }
192 split /\|/,$_)," $x\n";
193 }
194 }
195 print $fd <<"";
196\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
197arbitrary identifier if you're tracking multiple SVN branches/repositories in
198one git repository and want to keep them separate. See git-svn(1) for more
199information.
200
201 exit $exit;
202}
203
204sub version {
205 print "git-svn version $VERSION\n";
206 exit 0;
207}
208
209sub rebuild {
210 if (quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0")) {
211 copy_remote_ref();
212 }
213 $SVN_URL = shift or undef;
214 my $newest_rev = 0;
215 if ($_upgrade) {
216 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
217 } else {
218 check_upgrade_needed();
219 }
220
221 my $pid = open(my $rev_list,'-|');
222 defined $pid or croak $!;
223 if ($pid == 0) {
224 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
225 }
226 my $latest;
227 while (<$rev_list>) {
228 chomp;
229 my $c = $_;
230 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
231 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
232 next if (!@commit); # skip merges
233 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
234 if (!$rev || !$uuid) {
235 croak "Unable to extract revision or UUID from ",
236 "$c, $commit[$#commit]\n";
237 }
238
239 # if we merged or otherwise started elsewhere, this is
240 # how we break out of it
241 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
242 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
243
244 unless (defined $latest) {
245 if (!$SVN_URL && !$url) {
246 croak "SVN repository location required: $url\n";
247 }
248 $SVN_URL ||= $url;
249 $SVN_UUID ||= $uuid;
250 setup_git_svn();
251 $latest = $rev;
252 }
253 revdb_set($REVDB, $rev, $c);
254 print "r$rev = $c\n";
255 $newest_rev = $rev if ($rev > $newest_rev);
256 }
257 close $rev_list or croak $?;
258
259 goto out if $_use_lib;
260 if (!chdir $SVN_WC) {
261 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
262 chdir $SVN_WC or croak $!;
263 }
264
265 $pid = fork;
266 defined $pid or croak $!;
267 if ($pid == 0) {
268 my @svn_up = qw(svn up);
269 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
270 sys(@svn_up,"-r$newest_rev");
271 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
272 index_changes();
273 exec('git-write-tree') or croak $!;
274 }
275 waitpid $pid, 0;
276 croak $? if $?;
277out:
278 if ($_upgrade) {
279 print STDERR <<"";
280Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
281when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
282
283 }
284}
285
286sub init {
287 my $url = shift or die "SVN repository location required " .
288 "as a command-line argument\n";
289 $url =~ s!/+$!!; # strip trailing slash
290
291 if (my $repo_path = shift) {
292 unless (-d $repo_path) {
293 mkpath([$repo_path]);
294 }
295 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
296 init_vars();
297 }
298
299 $SVN_URL = $url;
300 unless (-d $GIT_DIR) {
301 my @init_db = ('git-init-db');
302 push @init_db, "--template=$_template" if defined $_template;
303 push @init_db, "--shared" if defined $_shared;
304 sys(@init_db);
305 }
306 setup_git_svn();
307}
308
309sub fetch {
310 check_upgrade_needed();
311 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
312 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
313 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
314 refs/heads/master^0))) {
315 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
316 }
317 return $ret;
318}
319
320sub fetch_cmd {
321 my (@parents) = @_;
322 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
323 unless ($_revision) {
324 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
325 }
326 push @log_args, "-r$_revision";
327 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
328
329 my $svn_log = svn_log_raw(@log_args);
330
331 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
332 # don't need last_revision from grab_base_rev() because
333 # user could've specified a different revision to skip (they
334 # didn't want to import certain revisions into git for whatever
335 # reason, so trust $base->{revision} instead.
336 my (undef, $last_commit) = svn_grab_base_rev();
337 unless (-d $SVN_WC) {
338 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
339 chdir $SVN_WC or croak $!;
340 read_uuid();
341 $last_commit = git_commit($base, @parents);
342 assert_tree($last_commit);
343 } else {
344 chdir $SVN_WC or croak $!;
345 read_uuid();
346 # looks like a user manually cp'd and svn switch'ed
347 unless ($last_commit) {
348 sys(qw/svn revert -R ./);
349 assert_svn_wc_clean($base->{revision});
350 $last_commit = git_commit($base, @parents);
351 assert_tree($last_commit);
352 }
353 }
354 my @svn_up = qw(svn up);
355 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
356 my $last = $base;
357 while (my $log_msg = next_log_entry($svn_log)) {
358 if ($last->{revision} >= $log_msg->{revision}) {
359 croak "Out of order: last >= current: ",
360 "$last->{revision} >= $log_msg->{revision}\n";
361 }
362 # Revert is needed for cases like:
363 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
364 # I can't seem to reproduce something like that on a test...
365 sys(qw/svn revert -R ./);
366 assert_svn_wc_clean($last->{revision});
367 sys(@svn_up,"-r$log_msg->{revision}");
368 $last_commit = git_commit($log_msg, $last_commit, @parents);
369 $last = $log_msg;
370 }
371 close $svn_log->{fh};
372 $last->{commit} = $last_commit;
373 return $last;
374}
375
376sub fetch_lib {
377 my (@parents) = @_;
378 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
379 my $repo;
380 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
381 $SVN_LOG ||= libsvn_connect($repo);
382 $SVN ||= libsvn_connect($repo);
383 my ($last_rev, $last_commit) = svn_grab_base_rev();
384 my ($base, $head) = libsvn_parse_revision($last_rev);
385 if ($base > $head) {
386 return { revision => $last_rev, commit => $last_commit }
387 }
388 my $index = set_index($GIT_SVN_INDEX);
389
390 # limit ourselves and also fork() since get_log won't release memory
391 # after processing a revision and SVN stuff seems to leak
392 my $inc = 1000;
393 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
394 read_uuid();
395 if (defined $last_commit) {
396 unless (-e $GIT_SVN_INDEX) {
397 sys(qw/git-read-tree/, $last_commit);
398 }
399 chomp (my $x = `git-write-tree`);
400 my ($y) = (`git-cat-file commit $last_commit`
401 =~ /^tree ($sha1)/m);
402 if ($y ne $x) {
403 unlink $GIT_SVN_INDEX or croak $!;
404 sys(qw/git-read-tree/, $last_commit);
405 }
406 chomp ($x = `git-write-tree`);
407 if ($y ne $x) {
408 print STDERR "trees ($last_commit) $y != $x\n",
409 "Something is seriously wrong...\n";
410 }
411 }
412 while (1) {
413 # fork, because using SVN::Pool with get_log() still doesn't
414 # seem to help enough to keep memory usage down.
415 defined(my $pid = fork) or croak $!;
416 if (!$pid) {
417 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
418
419 # Yes I'm perfectly aware that the fourth argument
420 # below is the limit revisions number. Unfortunately
421 # performance sucks with it enabled, so it's much
422 # faster to fetch revision ranges instead of relying
423 # on the limiter.
424 libsvn_get_log($SVN_LOG, '/'.$SVN_PATH,
425 $min, $max, 0, 1, 1,
426 sub {
427 my $log_msg;
428 if ($last_commit) {
429 $log_msg = libsvn_fetch(
430 $last_commit, @_);
431 $last_commit = git_commit(
432 $log_msg,
433 $last_commit,
434 @parents);
435 } else {
436 $log_msg = libsvn_new_tree(@_);
437 $last_commit = git_commit(
438 $log_msg, @parents);
439 }
440 });
441 exit 0;
442 }
443 waitpid $pid, 0;
444 croak $? if $?;
445 ($last_rev, $last_commit) = svn_grab_base_rev();
446 last if ($max >= $head);
447 $min = $max + 1;
448 $max += $inc;
449 $max = $head if ($max > $head);
450 }
451 restore_index($index);
452 return { revision => $last_rev, commit => $last_commit };
453}
454
455sub commit {
456 my (@commits) = @_;
457 check_upgrade_needed();
458 if ($_stdin || !@commits) {
459 print "Reading from stdin...\n";
460 @commits = ();
461 while (<STDIN>) {
462 if (/\b($sha1_short)\b/o) {
463 unshift @commits, $1;
464 }
465 }
466 }
467 my @revs;
468 foreach my $c (@commits) {
469 chomp(my @tmp = safe_qx('git-rev-parse',$c));
470 if (scalar @tmp == 1) {
471 push @revs, $tmp[0];
472 } elsif (scalar @tmp > 1) {
473 push @revs, reverse (safe_qx('git-rev-list',@tmp));
474 } else {
475 die "Failed to rev-parse $c\n";
476 }
477 }
478 chomp @revs;
479 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
480 print "Done committing ",scalar @revs," revisions to SVN\n";
481}
482
483sub commit_cmd {
484 my (@revs) = @_;
485
486 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
487 my $info = svn_info('.');
488 my $fetched = fetch();
489 if ($info->{Revision} != $fetched->{revision}) {
490 print STDERR "There are new revisions that were fetched ",
491 "and need to be merged (or acknowledged) ",
492 "before committing.\n";
493 exit 1;
494 }
495 $info = svn_info('.');
496 read_uuid($info);
497 my $last = $fetched;
498 foreach my $c (@revs) {
499 my $mods = svn_checkout_tree($last, $c);
500 if (scalar @$mods == 0) {
501 print "Skipping, no changes detected\n";
502 next;
503 }
504 $last = svn_commit_tree($last, $c);
505 }
506}
507
508sub commit_lib {
509 my (@revs) = @_;
510 my ($r_last, $cmt_last) = svn_grab_base_rev();
511 defined $r_last or die "Must have an existing revision to commit\n";
512 my $fetched = fetch();
513 if ($r_last != $fetched->{revision}) {
514 print STDERR "There are new revisions that were fetched ",
515 "and need to be merged (or acknowledged) ",
516 "before committing.\n",
517 "last rev: $r_last\n",
518 " current: $fetched->{revision}\n";
519 exit 1;
520 }
521 read_uuid();
522 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
523 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
524
525 my $repo;
526 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
527 set_svn_commit_env();
528 foreach my $c (@revs) {
529 my $log_msg = get_commit_message($c, $commit_msg);
530
531 # fork for each commit because there's a memory leak I
532 # can't track down... (it's probably in the SVN code)
533 defined(my $pid = open my $fh, '-|') or croak $!;
534 if (!$pid) {
535 $SVN_LOG = libsvn_connect($repo);
536 $SVN = libsvn_connect($repo);
537 my $ed = SVN::Git::Editor->new(
538 { r => $r_last,
539 ra => $SVN_LOG,
540 c => $c,
541 svn_path => $SVN_PATH
542 },
543 $SVN->get_commit_editor(
544 $log_msg->{msg},
545 sub {
546 libsvn_commit_cb(
547 @_, $c,
548 $log_msg->{msg},
549 $r_last,
550 $cmt_last)
551 },
552 @lock)
553 );
554 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
555 if (@$mods == 0) {
556 print "No changes\nr$r_last = $cmt_last\n";
557 $ed->abort_edit;
558 } else {
559 $ed->close_edit;
560 }
561 exit 0;
562 }
563 my ($r_new, $cmt_new, $no);
564 while (<$fh>) {
565 print $_;
566 chomp;
567 if (/^r(\d+) = ($sha1)$/o) {
568 ($r_new, $cmt_new) = ($1, $2);
569 } elsif ($_ eq 'No changes') {
570 $no = 1;
571 }
572 }
573 close $fh or croak $?;
574 if (! defined $r_new && ! defined $cmt_new) {
575 unless ($no) {
576 die "Failed to parse revision information\n";
577 }
578 } else {
579 ($r_last, $cmt_last) = ($r_new, $cmt_new);
580 }
581 }
582 $ENV{LC_ALL} = 'C';
583 unlink $commit_msg;
584}
585
586sub dcommit {
587 my $gs = "refs/remotes/$GIT_SVN";
588 chomp(my @refs = safe_qx(qw/git-rev-list --no-merges/, "$gs..HEAD"));
589 foreach my $d (reverse @refs) {
590 if ($_dry_run) {
591 print "diff-tree $d~1 $d\n";
592 } else {
593 commit_diff("$d~1", $d);
594 }
595 }
596 return if $_dry_run;
597 fetch();
598 my @diff = safe_qx(qw/git-diff-tree HEAD/, $gs);
599 my @finish;
600 if (@diff) {
601 @finish = qw/rebase/;
602 push @finish, qw/--merge/ if $_merge;
603 push @finish, "--strategy=$_strategy" if $_strategy;
604 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
605 } else {
606 print "No changes between current HEAD and $gs\n",
607 "Hard resetting to the latest $gs\n";
608 @finish = qw/reset --hard/;
609 }
610 sys('git', @finish, $gs);
611}
612
613sub show_ignore {
614 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
615 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
616}
617
618sub show_ignore_cmd {
619 require File::Find or die $!;
620 if (defined $_revision) {
621 die "-r/--revision option doesn't work unless the Perl SVN ",
622 "libraries are used\n";
623 }
624 chdir $SVN_WC or croak $!;
625 my %ign;
626 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
627 s#^\./##;
628 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
629 }}, no_chdir=>1},'.');
630
631 print "\n# /\n";
632 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
633 delete $ign{'.'};
634 foreach my $i (sort keys %ign) {
635 print "\n# ",$i,"\n";
636 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
637 }
638}
639
640sub show_ignore_lib {
641 my $repo;
642 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
643 $SVN ||= libsvn_connect($repo);
644 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
645 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
646}
647
648sub graft_branches {
649 my $gr_file = "$GIT_DIR/info/grafts";
650 my ($grafts, $comments) = read_grafts($gr_file);
651 my $gr_sha1;
652
653 if (%$grafts) {
654 # temporarily disable our grafts file to make this idempotent
655 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
656 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
657 }
658
659 my $l_map = read_url_paths();
660 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
661 unless ($_no_default_regex) {
662 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
663 qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
664 qr/\b(?:from|of)\s+([\w\.\-]+)/i );
665 }
666 foreach my $u (keys %$l_map) {
667 if (@re) {
668 foreach my $p (keys %{$l_map->{$u}}) {
669 graft_merge_msg($grafts,$l_map,$u,$p,@re);
670 }
671 }
672 unless ($_no_graft_copy) {
673 if ($_use_lib) {
674 graft_file_copy_lib($grafts,$l_map,$u);
675 } else {
676 graft_file_copy_cmd($grafts,$l_map,$u);
677 }
678 }
679 }
680 graft_tree_joins($grafts);
681
682 write_grafts($grafts, $comments, $gr_file);
683 unlink "$gr_file~$gr_sha1" if $gr_sha1;
684}
685
686sub multi_init {
687 my $url = shift;
688 $_trunk ||= 'trunk';
689 $_trunk =~ s#/+$##;
690 $url =~ s#/+$## if $url;
691 if ($_trunk !~ m#^[a-z\+]+://#) {
692 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
693 unless ($url) {
694 print STDERR "E: '$_trunk' is not a complete URL ",
695 "and a separate URL is not specified\n";
696 exit 1;
697 }
698 $_trunk = $url . $_trunk;
699 }
700 my $ch_id;
701 if ($GIT_SVN eq 'git-svn') {
702 $ch_id = 1;
703 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
704 }
705 init_vars();
706 unless (-d $GIT_SVN_DIR) {
707 print "GIT_SVN_ID set to 'trunk' for $_trunk\n" if $ch_id;
708 init($_trunk);
709 sys('git-repo-config', 'svn.trunk', $_trunk);
710 }
711 complete_url_ls_init($url, $_branches, '--branches/-b', '');
712 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
713}
714
715sub multi_fetch {
716 # try to do trunk first, since branches/tags
717 # may be descended from it.
718 if (-e "$GIT_DIR/svn/trunk/info/url") {
719 fetch_child_id('trunk', @_);
720 }
721 rec_fetch('', "$GIT_DIR/svn", @_);
722}
723
724sub show_log {
725 my (@args) = @_;
726 my ($r_min, $r_max);
727 my $r_last = -1; # prevent dupes
728 rload_authors() if $_authors;
729 if (defined $TZ) {
730 $ENV{TZ} = $TZ;
731 } else {
732 delete $ENV{TZ};
733 }
734 if (defined $_revision) {
735 if ($_revision =~ /^(\d+):(\d+)$/) {
736 ($r_min, $r_max) = ($1, $2);
737 } elsif ($_revision =~ /^\d+$/) {
738 $r_min = $r_max = $_revision;
739 } else {
740 print STDERR "-r$_revision is not supported, use ",
741 "standard \'git log\' arguments instead\n";
742 exit 1;
743 }
744 }
745
746 my $pid = open(my $log,'-|');
747 defined $pid or croak $!;
748 if (!$pid) {
749 exec(git_svn_log_cmd($r_min,$r_max), @args) or croak $!;
750 }
751 setup_pager();
752 my (@k, $c, $d);
753
754 while (<$log>) {
755 if (/^commit ($sha1_short)/o) {
756 my $cmt = $1;
757 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
758 $r_last = $c->{r};
759 process_commit($c, $r_min, $r_max, \@k) or
760 goto out;
761 }
762 $d = undef;
763 $c = { c => $cmt };
764 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
765 get_author_info($c, $1, $2, $3);
766 } elsif (/^(?:tree|parent|committer) /) {
767 # ignore
768 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
769 push @{$c->{raw}}, $_;
770 } elsif (/^[ACRMDT]\t/) {
771 # we could add $SVN_PATH here, but that requires
772 # remote access at the moment (repo_path_split)...
773 s#^([ACRMDT])\t# $1 #;
774 push @{$c->{changed}}, $_;
775 } elsif (/^diff /) {
776 $d = 1;
777 push @{$c->{diff}}, $_;
778 } elsif ($d) {
779 push @{$c->{diff}}, $_;
780 } elsif (/^ (git-svn-id:.+)$/) {
781 ($c->{url}, $c->{r}, undef) = extract_metadata($1);
782 } elsif (s/^ //) {
783 push @{$c->{l}}, $_;
784 }
785 }
786 if ($c && defined $c->{r} && $c->{r} != $r_last) {
787 $r_last = $c->{r};
788 process_commit($c, $r_min, $r_max, \@k);
789 }
790 if (@k) {
791 my $swap = $r_max;
792 $r_max = $r_min;
793 $r_min = $swap;
794 process_commit($_, $r_min, $r_max) foreach reverse @k;
795 }
796out:
797 close $log;
798 print '-' x72,"\n" unless $_incremental || $_oneline;
799}
800
801sub commit_diff_usage {
802 print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
803 exit 1
804}
805
806sub commit_diff {
807 if (!$_use_lib) {
808 print STDERR "commit-diff must be used with SVN libraries\n";
809 exit 1;
810 }
811 my $ta = shift or commit_diff_usage();
812 my $tb = shift or commit_diff_usage();
813 if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
814 print STDERR "Needed URL or usable git-svn id command-line\n";
815 commit_diff_usage();
816 }
817 if (defined $_message && defined $_file) {
818 print STDERR "Both --message/-m and --file/-F specified ",
819 "for the commit message.\n",
820 "I have no idea what you mean\n";
821 exit 1;
822 }
823 if (defined $_file) {
824 $_message = file_to_s($_file);
825 } else {
826 $_message ||= get_commit_message($tb,
827 "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
828 }
829 my $repo;
830 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
831 $SVN_LOG ||= libsvn_connect($repo);
832 $SVN ||= libsvn_connect($repo);
833 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
834 my $ed = SVN::Git::Editor->new({ r => $SVN->get_latest_revnum,
835 ra => $SVN_LOG, c => $tb,
836 svn_path => $SVN_PATH
837 },
838 $SVN->get_commit_editor($_message,
839 sub {print "Committed $_[0]\n"},@lock)
840 );
841 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
842 if (@$mods == 0) {
843 print "No changes\n$ta == $tb\n";
844 $ed->abort_edit;
845 } else {
846 $ed->close_edit;
847 }
848 $_message = $_file = undef;
849}
850
851########################### utility functions #########################
852
853sub cmt_showable {
854 my ($c) = @_;
855 return 1 if defined $c->{r};
856 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
857 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
858 my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
859 shift @msg while ($msg[0] ne "\n");
860 shift @msg;
861 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
862
863 (undef, $c->{r}, undef) = extract_metadata(
864 (grep(/^git-svn-id: /, @msg))[-1]);
865 }
866 return defined $c->{r};
867}
868
869sub git_svn_log_cmd {
870 my ($r_min, $r_max) = @_;
871 my @cmd = (qw/git-log --abbrev-commit --pretty=raw
872 --default/, "refs/remotes/$GIT_SVN");
873 push @cmd, '-r' unless $_non_recursive;
874 push @cmd, qw/--raw --name-status/ if $_verbose;
875 return @cmd unless defined $r_max;
876 if ($r_max == $r_min) {
877 push @cmd, '--max-count=1';
878 if (my $c = revdb_get($REVDB, $r_max)) {
879 push @cmd, $c;
880 }
881 } else {
882 my ($c_min, $c_max);
883 $c_max = revdb_get($REVDB, $r_max);
884 $c_min = revdb_get($REVDB, $r_min);
885 if (defined $c_min && defined $c_max) {
886 if ($r_max > $r_max) {
887 push @cmd, "$c_min..$c_max";
888 } else {
889 push @cmd, "$c_max..$c_min";
890 }
891 } elsif ($r_max > $r_min) {
892 push @cmd, $c_max;
893 } else {
894 push @cmd, $c_min;
895 }
896 }
897 return @cmd;
898}
899
900sub fetch_child_id {
901 my $id = shift;
902 print "Fetching $id\n";
903 my $ref = "$GIT_DIR/refs/remotes/$id";
904 defined(my $pid = open my $fh, '-|') or croak $!;
905 if (!$pid) {
906 $_repack = undef;
907 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
908 init_vars();
909 fetch(@_);
910 exit 0;
911 }
912 while (<$fh>) {
913 print $_;
914 check_repack() if (/^r\d+ = $sha1/);
915 }
916 close $fh or croak $?;
917}
918
919sub rec_fetch {
920 my ($pfx, $p, @args) = @_;
921 my @dir;
922 foreach (sort <$p/*>) {
923 if (-r "$_/info/url") {
924 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
925 my $id = $pfx . basename $_;
926 next if $id eq 'trunk';
927 fetch_child_id($id, @args);
928 } elsif (-d $_) {
929 push @dir, $_;
930 }
931 }
932 foreach (@dir) {
933 my $x = $_;
934 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
935 rec_fetch($x, $_);
936 }
937}
938
939sub complete_url_ls_init {
940 my ($url, $var, $switch, $pfx) = @_;
941 unless ($var) {
942 print STDERR "W: $switch not specified\n";
943 return;
944 }
945 $var =~ s#/+$##;
946 if ($var !~ m#^[a-z\+]+://#) {
947 $var = '/' . $var if ($var !~ m#^/#);
948 unless ($url) {
949 print STDERR "E: '$var' is not a complete URL ",
950 "and a separate URL is not specified\n";
951 exit 1;
952 }
953 $var = $url . $var;
954 }
955 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
956 : safe_qx(qw/svn ls --non-interactive/, $var));
957 my $old = $GIT_SVN;
958 defined(my $pid = fork) or croak $!;
959 if (!$pid) {
960 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
961 $u =~ s#/+$##;
962 if ($u !~ m!\Q$var\E/(.+)$!) {
963 print STDERR "W: Unrecognized URL: $u\n";
964 die "This should never happen\n";
965 }
966 # don't try to init already existing refs
967 my $id = $pfx.$1;
968 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
969 init_vars();
970 unless (-d $GIT_SVN_DIR) {
971 print "init $u => $id\n";
972 init($u);
973 }
974 }
975 exit 0;
976 }
977 waitpid $pid, 0;
978 croak $? if $?;
979 my ($n) = ($switch =~ /^--(\w+)/);
980 sys('git-repo-config', "svn.$n", $var);
981}
982
983sub common_prefix {
984 my $paths = shift;
985 my %common;
986 foreach (@$paths) {
987 my @tmp = split m#/#, $_;
988 my $p = '';
989 while (my $x = shift @tmp) {
990 $p .= "/$x";
991 $common{$p} ||= 0;
992 $common{$p}++;
993 }
994 }
995 foreach (sort {length $b <=> length $a} keys %common) {
996 if ($common{$_} == @$paths) {
997 return $_;
998 }
999 }
1000 return '';
1001}
1002
1003# grafts set here are 'stronger' in that they're based on actual tree
1004# matches, and won't be deleted from merge-base checking in write_grafts()
1005sub graft_tree_joins {
1006 my $grafts = shift;
1007 map_tree_joins() if (@_branch_from && !%tree_map);
1008 return unless %tree_map;
1009
1010 git_svn_each(sub {
1011 my $i = shift;
1012 defined(my $pid = open my $fh, '-|') or croak $!;
1013 if (!$pid) {
1014 exec qw/git-rev-list --pretty=raw/,
1015 "refs/remotes/$i" or croak $!;
1016 }
1017 while (<$fh>) {
1018 next unless /^commit ($sha1)$/o;
1019 my $c = $1;
1020 my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
1021 next unless $tree_map{$t};
1022
1023 my $l;
1024 do {
1025 $l = readline $fh;
1026 } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
1027
1028 my ($s, $tz) = ($1, $2);
1029 if ($tz =~ s/^\+//) {
1030 $s += tz_to_s_offset($tz);
1031 } elsif ($tz =~ s/^\-//) {
1032 $s -= tz_to_s_offset($tz);
1033 }
1034
1035 my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
1036
1037 foreach my $p (@{$tree_map{$t}}) {
1038 next if $p eq $c;
1039 my $mb = eval {
1040 safe_qx('git-merge-base', $c, $p)
1041 };
1042 next unless ($@ || $?);
1043 if (defined $r_a) {
1044 # see if SVN says it's a relative
1045 my ($url_b, $r_b, $uuid_b) =
1046 cmt_metadata($p);
1047 next if (defined $url_b &&
1048 defined $url_a &&
1049 ($url_a eq $url_b) &&
1050 ($uuid_a eq $uuid_b));
1051 if ($uuid_a eq $uuid_b) {
1052 if ($r_b < $r_a) {
1053 $grafts->{$c}->{$p} = 2;
1054 next;
1055 } elsif ($r_b > $r_a) {
1056 $grafts->{$p}->{$c} = 2;
1057 next;
1058 }
1059 }
1060 }
1061 my $ct = get_commit_time($p);
1062 if ($ct < $s) {
1063 $grafts->{$c}->{$p} = 2;
1064 } elsif ($ct > $s) {
1065 $grafts->{$p}->{$c} = 2;
1066 }
1067 # what should we do when $ct == $s ?
1068 }
1069 }
1070 close $fh or croak $?;
1071 });
1072}
1073
1074# this isn't funky-filename safe, but good enough for now...
1075sub graft_file_copy_cmd {
1076 my ($grafts, $l_map, $u) = @_;
1077 my $paths = $l_map->{$u};
1078 my $pfx = common_prefix([keys %$paths]);
1079 $SVN_URL ||= $u.$pfx;
1080 my $pid = open my $fh, '-|';
1081 defined $pid or croak $!;
1082 unless ($pid) {
1083 my @exec = qw/svn log -v/;
1084 push @exec, "-r$_revision" if defined $_revision;
1085 exec @exec, $u.$pfx or croak $!;
1086 }
1087 my ($r, $mp) = (undef, undef);
1088 while (<$fh>) {
1089 chomp;
1090 if (/^\-{72}$/) {
1091 $mp = $r = undef;
1092 } elsif (/^r(\d+) \| /) {
1093 $r = $1 unless defined $r;
1094 } elsif (/^Changed paths:/) {
1095 $mp = 1;
1096 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
1097 my ($p1, $p0, $r0) = ($1, $2, $3);
1098 my $c = find_graft_path_commit($paths, $p1, $r);
1099 next unless $c;
1100 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
1101 }
1102 }
1103}
1104
1105sub graft_file_copy_lib {
1106 my ($grafts, $l_map, $u) = @_;
1107 my $tree_paths = $l_map->{$u};
1108 my $pfx = common_prefix([keys %$tree_paths]);
1109 my ($repo, $path) = repo_path_split($u.$pfx);
1110 $SVN_LOG ||= libsvn_connect($repo);
1111 $SVN ||= libsvn_connect($repo);
1112
1113 my ($base, $head) = libsvn_parse_revision();
1114 my $inc = 1000;
1115 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1116 my $eh = $SVN::Error::handler;
1117 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1118 while (1) {
1119 my $pool = SVN::Pool->new;
1120 libsvn_get_log($SVN_LOG, "/$path", $min, $max, 0, 1, 1,
1121 sub {
1122 libsvn_graft_file_copies($grafts, $tree_paths,
1123 $path, @_);
1124 }, $pool);
1125 $pool->clear;
1126 last if ($max >= $head);
1127 $min = $max + 1;
1128 $max += $inc;
1129 $max = $head if ($max > $head);
1130 }
1131 $SVN::Error::handler = $eh;
1132}
1133
1134sub process_merge_msg_matches {
1135 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1136 my (@strong, @weak);
1137 foreach (@matches) {
1138 # merging with ourselves is not interesting
1139 next if $_ eq $p;
1140 if ($l_map->{$u}->{$_}) {
1141 push @strong, $_;
1142 } else {
1143 push @weak, $_;
1144 }
1145 }
1146 foreach my $w (@weak) {
1147 last if @strong;
1148 # no exact match, use branch name as regexp.
1149 my $re = qr/\Q$w\E/i;
1150 foreach (keys %{$l_map->{$u}}) {
1151 if (/$re/) {
1152 push @strong, $l_map->{$u}->{$_};
1153 last;
1154 }
1155 }
1156 last if @strong;
1157 $w = basename($w);
1158 $re = qr/\Q$w\E/i;
1159 foreach (keys %{$l_map->{$u}}) {
1160 if (/$re/) {
1161 push @strong, $l_map->{$u}->{$_};
1162 last;
1163 }
1164 }
1165 }
1166 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1167 \s(?:[a-f\d\-]+)$/xsm);
1168 unless (defined $rev) {
1169 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1170 \@(?:[a-f\d\-]+)/xsm);
1171 return unless defined $rev;
1172 }
1173 foreach my $m (@strong) {
1174 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1175 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1176 }
1177}
1178
1179sub graft_merge_msg {
1180 my ($grafts, $l_map, $u, $p, @re) = @_;
1181
1182 my $x = $l_map->{$u}->{$p};
1183 my $rl = rev_list_raw($x);
1184 while (my $c = next_rev_list_entry($rl)) {
1185 foreach my $re (@re) {
1186 my (@br) = ($c->{m} =~ /$re/g);
1187 next unless @br;
1188 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1189 }
1190 }
1191}
1192
1193sub read_uuid {
1194 return if $SVN_UUID;
1195 if ($_use_lib) {
1196 my $pool = SVN::Pool->new;
1197 $SVN_UUID = $SVN->get_uuid($pool);
1198 $pool->clear;
1199 } else {
1200 my $info = shift || svn_info('.');
1201 $SVN_UUID = $info->{'Repository UUID'} or
1202 croak "Repository UUID unreadable\n";
1203 }
1204}
1205
1206sub quiet_run {
1207 my $pid = fork;
1208 defined $pid or croak $!;
1209 if (!$pid) {
1210 open my $null, '>', '/dev/null' or croak $!;
1211 open STDERR, '>&', $null or croak $!;
1212 open STDOUT, '>&', $null or croak $!;
1213 exec @_ or croak $!;
1214 }
1215 waitpid $pid, 0;
1216 return $?;
1217}
1218
1219sub repo_path_split {
1220 my $full_url = shift;
1221 $full_url =~ s#/+$##;
1222
1223 foreach (@repo_path_split_cache) {
1224 if ($full_url =~ s#$_##) {
1225 my $u = $1;
1226 $full_url =~ s#^/+##;
1227 return ($u, $full_url);
1228 }
1229 }
1230
1231 if ($_use_lib) {
1232 my $tmp = libsvn_connect($full_url);
1233 my $url = $tmp->get_repos_root;
1234 $full_url =~ s#^\Q$url\E/*##;
1235 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1236 return ($url, $full_url);
1237 } else {
1238 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1239 $path =~ s#^/+##;
1240 my @paths = split(m#/+#, $path);
1241 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1242 my $n = shift @paths || last;
1243 $url .= "/$n";
1244 }
1245 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1246 $path = join('/',@paths);
1247 return ($url, $path);
1248 }
1249}
1250
1251sub setup_git_svn {
1252 defined $SVN_URL or croak "SVN repository location required\n";
1253 unless (-d $GIT_DIR) {
1254 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1255 }
1256 mkpath([$GIT_SVN_DIR]);
1257 mkpath(["$GIT_SVN_DIR/info"]);
1258 open my $fh, '>>',$REVDB or croak $!;
1259 close $fh;
1260 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1261
1262}
1263
1264sub assert_svn_wc_clean {
1265 return if $_use_lib;
1266 my ($svn_rev) = @_;
1267 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1268 my $lcr = svn_info('.')->{'Last Changed Rev'};
1269 if ($svn_rev != $lcr) {
1270 print STDERR "Checking for copy-tree ... ";
1271 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1272 "-r$lcr:$svn_rev")));
1273 if (@diff) {
1274 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1275 } else {
1276 print STDERR "OK!\n";
1277 }
1278 }
1279 my @status = grep(!/^Performing status on external/,(`svn status`));
1280 @status = grep(!/^\s*$/,@status);
1281 @status = grep(!/^X/,@status) if $_no_ignore_ext;
1282 if (scalar @status) {
1283 print STDERR "Tree ($SVN_WC) is not clean:\n";
1284 print STDERR $_ foreach @status;
1285 croak;
1286 }
1287}
1288
1289sub get_tree_from_treeish {
1290 my ($treeish) = @_;
1291 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1292 chomp(my $type = `git-cat-file -t $treeish`);
1293 my $expected;
1294 while ($type eq 'tag') {
1295 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1296 }
1297 if ($type eq 'commit') {
1298 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1299 ($expected) = ($expected =~ /^tree ($sha1)$/);
1300 die "Unable to get tree from $treeish\n" unless $expected;
1301 } elsif ($type eq 'tree') {
1302 $expected = $treeish;
1303 } else {
1304 die "$treeish is a $type, expected tree, tag or commit\n";
1305 }
1306 return $expected;
1307}
1308
1309sub assert_tree {
1310 return if $_use_lib;
1311 my ($treeish) = @_;
1312 my $expected = get_tree_from_treeish($treeish);
1313
1314 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1315 if (-e $tmpindex) {
1316 unlink $tmpindex or croak $!;
1317 }
1318 my $old_index = set_index($tmpindex);
1319 index_changes(1);
1320 chomp(my $tree = `git-write-tree`);
1321 restore_index($old_index);
1322 if ($tree ne $expected) {
1323 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1324 }
1325 unlink $tmpindex;
1326}
1327
1328sub parse_diff_tree {
1329 my $diff_fh = shift;
1330 local $/ = "\0";
1331 my $state = 'meta';
1332 my @mods;
1333 while (<$diff_fh>) {
1334 chomp $_; # this gets rid of the trailing "\0"
1335 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1336 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1337 push @mods, { mode_a => $1, mode_b => $2,
1338 sha1_b => $3, chg => $4 };
1339 if ($4 =~ /^(?:C|R)$/) {
1340 $state = 'file_a';
1341 } else {
1342 $state = 'file_b';
1343 }
1344 } elsif ($state eq 'file_a') {
1345 my $x = $mods[$#mods] or croak "Empty array\n";
1346 if ($x->{chg} !~ /^(?:C|R)$/) {
1347 croak "Error parsing $_, $x->{chg}\n";
1348 }
1349 $x->{file_a} = $_;
1350 $state = 'file_b';
1351 } elsif ($state eq 'file_b') {
1352 my $x = $mods[$#mods] or croak "Empty array\n";
1353 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1354 croak "Error parsing $_, $x->{chg}\n";
1355 }
1356 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1357 croak "Error parsing $_, $x->{chg}\n";
1358 }
1359 $x->{file_b} = $_;
1360 $state = 'meta';
1361 } else {
1362 croak "Error parsing $_\n";
1363 }
1364 }
1365 close $diff_fh or croak $?;
1366
1367 return \@mods;
1368}
1369
1370sub svn_check_prop_executable {
1371 my $m = shift;
1372 return if -l $m->{file_b};
1373 if ($m->{mode_b} =~ /755$/) {
1374 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1375 if ($m->{mode_a} !~ /755$/) {
1376 sys(qw(svn propset svn:executable 1), $m->{file_b});
1377 }
1378 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1379 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1380 sys(qw(svn propdel svn:executable), $m->{file_b});
1381 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1382 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1383 }
1384}
1385
1386sub svn_ensure_parent_path {
1387 my $dir_b = dirname(shift);
1388 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1389 mkpath([$dir_b]) unless (-d $dir_b);
1390 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1391}
1392
1393sub precommit_check {
1394 my $mods = shift;
1395 my (%rm_file, %rmdir_check, %added_check);
1396
1397 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1398 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1399 if ($m->{chg} eq 'R') {
1400 if (-d $m->{file_b}) {
1401 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1402 }
1403 # dir/$file => dir/file/$file
1404 my $dirname = dirname($m->{file_b});
1405 while ($dirname ne File::Spec->curdir) {
1406 if ($dirname ne $m->{file_a}) {
1407 $dirname = dirname($dirname);
1408 next;
1409 }
1410 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1411 }
1412 # baz/zzz => baz (baz is a file)
1413 $dirname = dirname($m->{file_a});
1414 while ($dirname ne File::Spec->curdir) {
1415 if ($dirname ne $m->{file_b}) {
1416 $dirname = dirname($dirname);
1417 next;
1418 }
1419 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1420 }
1421 }
1422 if ($m->{chg} =~ /^(D|R)$/) {
1423 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1424 $rm_file{ $m->{$t} } = 1;
1425 my $dirname = dirname( $m->{$t} );
1426 my $basename = basename( $m->{$t} );
1427 $rmdir_check{$dirname}->{$basename} = 1;
1428 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1429 if (-d $m->{file_b}) {
1430 err_dir_to_file($m->{file_b});
1431 }
1432 my $dirname = dirname( $m->{file_b} );
1433 my $basename = basename( $m->{file_b} );
1434 $added_check{$dirname}->{$basename} = 1;
1435 while ($dirname ne File::Spec->curdir) {
1436 if ($rm_file{$dirname}) {
1437 err_file_to_dir($m->{file_b});
1438 }
1439 $dirname = dirname $dirname;
1440 }
1441 }
1442 }
1443 return (\%rmdir_check, \%added_check);
1444
1445 sub err_dir_to_file {
1446 my $file = shift;
1447 print STDERR "Node change from directory to file ",
1448 "is not supported by Subversion: ",$file,"\n";
1449 exit 1;
1450 }
1451 sub err_file_to_dir {
1452 my $file = shift;
1453 print STDERR "Node change from file to directory ",
1454 "is not supported by Subversion: ",$file,"\n";
1455 exit 1;
1456 }
1457}
1458
1459
1460sub get_diff {
1461 my ($from, $treeish) = @_;
1462 assert_tree($from);
1463 print "diff-tree $from $treeish\n";
1464 my $pid = open my $diff_fh, '-|';
1465 defined $pid or croak $!;
1466 if ($pid == 0) {
1467 my @diff_tree = qw(git-diff-tree -z -r);
1468 if ($_cp_similarity) {
1469 push @diff_tree, "-C$_cp_similarity";
1470 } else {
1471 push @diff_tree, '-C';
1472 }
1473 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1474 push @diff_tree, "-l$_l" if defined $_l;
1475 exec(@diff_tree, $from, $treeish) or croak $!;
1476 }
1477 return parse_diff_tree($diff_fh);
1478}
1479
1480sub svn_checkout_tree {
1481 my ($from, $treeish) = @_;
1482 my $mods = get_diff($from->{commit}, $treeish);
1483 return $mods unless (scalar @$mods);
1484 my ($rm, $add) = precommit_check($mods);
1485
1486 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1487 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1488 if ($m->{chg} eq 'C') {
1489 svn_ensure_parent_path( $m->{file_b} );
1490 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1491 apply_mod_line_blob($m);
1492 svn_check_prop_executable($m);
1493 } elsif ($m->{chg} eq 'D') {
1494 sys(qw(svn rm --force), $m->{file_b});
1495 } elsif ($m->{chg} eq 'R') {
1496 svn_ensure_parent_path( $m->{file_b} );
1497 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1498 apply_mod_line_blob($m);
1499 svn_check_prop_executable($m);
1500 } elsif ($m->{chg} eq 'M') {
1501 apply_mod_line_blob($m);
1502 svn_check_prop_executable($m);
1503 } elsif ($m->{chg} eq 'T') {
1504 sys(qw(svn rm --force),$m->{file_b});
1505 apply_mod_line_blob($m);
1506 sys(qw(svn add), $m->{file_b});
1507 svn_check_prop_executable($m);
1508 } elsif ($m->{chg} eq 'A') {
1509 svn_ensure_parent_path( $m->{file_b} );
1510 apply_mod_line_blob($m);
1511 sys(qw(svn add), $m->{file_b});
1512 svn_check_prop_executable($m);
1513 } else {
1514 croak "Invalid chg: $m->{chg}\n";
1515 }
1516 }
1517
1518 assert_tree($treeish);
1519 if ($_rmdir) { # remove empty directories
1520 handle_rmdir($rm, $add);
1521 }
1522 assert_tree($treeish);
1523 return $mods;
1524}
1525
1526sub libsvn_checkout_tree {
1527 my ($from, $treeish, $ed) = @_;
1528 my $mods = get_diff($from, $treeish);
1529 return $mods unless (scalar @$mods);
1530 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1531 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1532 my $f = $m->{chg};
1533 if (defined $o{$f}) {
1534 $ed->$f($m, $_q);
1535 } else {
1536 croak "Invalid change type: $f\n";
1537 }
1538 }
1539 $ed->rmdirs($_q) if $_rmdir;
1540 return $mods;
1541}
1542
1543# svn ls doesn't work with respect to the current working tree, but what's
1544# in the repository. There's not even an option for it... *sigh*
1545# (added files don't show up and removed files remain in the ls listing)
1546sub svn_ls_current {
1547 my ($dir, $rm, $add) = @_;
1548 chomp(my @ls = safe_qx('svn','ls',$dir));
1549 my @ret = ();
1550 foreach (@ls) {
1551 s#/$##; # trailing slashes are evil
1552 push @ret, $_ unless $rm->{$dir}->{$_};
1553 }
1554 if (exists $add->{$dir}) {
1555 push @ret, keys %{$add->{$dir}};
1556 }
1557 return \@ret;
1558}
1559
1560sub handle_rmdir {
1561 my ($rm, $add) = @_;
1562
1563 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1564 my $ls = svn_ls_current($dir, $rm, $add);
1565 next if (scalar @$ls);
1566 sys(qw(svn rm --force),$dir);
1567
1568 my $dn = dirname $dir;
1569 $rm->{ $dn }->{ basename $dir } = 1;
1570 $ls = svn_ls_current($dn, $rm, $add);
1571 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1572 sys(qw(svn rm --force),$dn);
1573 $dir = basename $dn;
1574 $dn = dirname $dn;
1575 $rm->{ $dn }->{ $dir } = 1;
1576 $ls = svn_ls_current($dn, $rm, $add);
1577 }
1578 }
1579}
1580
1581sub get_commit_message {
1582 my ($commit, $commit_msg) = (@_);
1583 my %log_msg = ( msg => '' );
1584 open my $msg, '>', $commit_msg or croak $!;
1585
1586 chomp(my $type = `git-cat-file -t $commit`);
1587 if ($type eq 'commit' || $type eq 'tag') {
1588 my $pid = open my $msg_fh, '-|';
1589 defined $pid or croak $!;
1590
1591 if ($pid == 0) {
1592 exec('git-cat-file', $type, $commit) or croak $!;
1593 }
1594 my $in_msg = 0;
1595 while (<$msg_fh>) {
1596 if (!$in_msg) {
1597 $in_msg = 1 if (/^\s*$/);
1598 } elsif (/^git-svn-id: /) {
1599 # skip this, we regenerate the correct one
1600 # on re-fetch anyways
1601 } else {
1602 print $msg $_ or croak $!;
1603 }
1604 }
1605 close $msg_fh or croak $?;
1606 }
1607 close $msg or croak $!;
1608
1609 if ($_edit || ($type eq 'tree')) {
1610 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1611 system($editor, $commit_msg);
1612 }
1613
1614 # file_to_s removes all trailing newlines, so just use chomp() here:
1615 open $msg, '<', $commit_msg or croak $!;
1616 { local $/; chomp($log_msg{msg} = <$msg>); }
1617 close $msg or croak $!;
1618
1619 return \%log_msg;
1620}
1621
1622sub set_svn_commit_env {
1623 if (defined $LC_ALL) {
1624 $ENV{LC_ALL} = $LC_ALL;
1625 } else {
1626 delete $ENV{LC_ALL};
1627 }
1628}
1629
1630sub svn_commit_tree {
1631 my ($last, $commit) = @_;
1632 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1633 my $log_msg = get_commit_message($commit, $commit_msg);
1634 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1635 print "Committing $commit: $oneline\n";
1636
1637 set_svn_commit_env();
1638 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1639 $ENV{LC_ALL} = 'C';
1640 unlink $commit_msg;
1641 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1642 if (!defined $committed) {
1643 my $out = join("\n",@ci_output);
1644 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1645 $out, "\n\nAssuming English locale...";
1646 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1647 defined $committed or die " FAILED!\n",
1648 "Commit output failed to parse committed revision!\n",
1649 print STDERR " OK\n";
1650 }
1651
1652 my @svn_up = qw(svn up);
1653 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1654 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1655 push @svn_up, "-r$committed";
1656 sys(@svn_up);
1657 my $info = svn_info('.');
1658 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1659 if ($info->{'Last Changed Rev'} != $committed) {
1660 croak "$info->{'Last Changed Rev'} != $committed\n"
1661 }
1662 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1663 /(\d{4})\-(\d\d)\-(\d\d)\s
1664 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1665 or croak "Failed to parse date: $date\n";
1666 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1667 $log_msg->{author} = $info->{'Last Changed Author'};
1668 $log_msg->{revision} = $committed;
1669 $log_msg->{msg} .= "\n";
1670 $log_msg->{parents} = [ $last->{commit} ];
1671 $log_msg->{commit} = git_commit($log_msg, $commit);
1672 return $log_msg;
1673 }
1674 # resync immediately
1675 push @svn_up, "-r$last->{revision}";
1676 sys(@svn_up);
1677 return fetch("$committed=$commit");
1678}
1679
1680sub rev_list_raw {
1681 my (@args) = @_;
1682 my $pid = open my $fh, '-|';
1683 defined $pid or croak $!;
1684 if (!$pid) {
1685 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1686 }
1687 return { fh => $fh, t => { } };
1688}
1689
1690sub next_rev_list_entry {
1691 my $rl = shift;
1692 my $fh = $rl->{fh};
1693 my $x = $rl->{t};
1694 while (<$fh>) {
1695 if (/^commit ($sha1)$/o) {
1696 if ($x->{c}) {
1697 $rl->{t} = { c => $1 };
1698 return $x;
1699 } else {
1700 $x->{c} = $1;
1701 }
1702 } elsif (/^parent ($sha1)$/o) {
1703 $x->{p}->{$1} = 1;
1704 } elsif (s/^ //) {
1705 $x->{m} ||= '';
1706 $x->{m} .= $_;
1707 }
1708 }
1709 return ($x != $rl->{t}) ? $x : undef;
1710}
1711
1712# read the entire log into a temporary file (which is removed ASAP)
1713# and store the file handle + parser state
1714sub svn_log_raw {
1715 my (@log_args) = @_;
1716 my $log_fh = IO::File->new_tmpfile or croak $!;
1717 my $pid = fork;
1718 defined $pid or croak $!;
1719 if (!$pid) {
1720 open STDOUT, '>&', $log_fh or croak $!;
1721 exec (qw(svn log), @log_args) or croak $!
1722 }
1723 waitpid $pid, 0;
1724 croak $? if $?;
1725 seek $log_fh, 0, 0 or croak $!;
1726 return { state => 'sep', fh => $log_fh };
1727}
1728
1729sub next_log_entry {
1730 my $log = shift; # retval of svn_log_raw()
1731 my $ret = undef;
1732 my $fh = $log->{fh};
1733
1734 while (<$fh>) {
1735 chomp;
1736 if (/^\-{72}$/) {
1737 if ($log->{state} eq 'msg') {
1738 if ($ret->{lines}) {
1739 $ret->{msg} .= $_."\n";
1740 unless(--$ret->{lines}) {
1741 $log->{state} = 'sep';
1742 }
1743 } else {
1744 croak "Log parse error at: $_\n",
1745 $ret->{revision},
1746 "\n";
1747 }
1748 next;
1749 }
1750 if ($log->{state} ne 'sep') {
1751 croak "Log parse error at: $_\n",
1752 "state: $log->{state}\n",
1753 $ret->{revision},
1754 "\n";
1755 }
1756 $log->{state} = 'rev';
1757
1758 # if we have an empty log message, put something there:
1759 if ($ret) {
1760 $ret->{msg} ||= "\n";
1761 delete $ret->{lines};
1762 return $ret;
1763 }
1764 next;
1765 }
1766 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1767 my $rev = $1;
1768 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1769 ($lines) = ($lines =~ /(\d+)/);
1770 $date = '1970-01-01 00:00:00 +0000'
1771 if ($_ignore_nodate && $date eq '(no date)');
1772 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1773 /(\d{4})\-(\d\d)\-(\d\d)\s
1774 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1775 or croak "Failed to parse date: $date\n";
1776 $ret = { revision => $rev,
1777 date => "$tz $Y-$m-$d $H:$M:$S",
1778 author => $author,
1779 lines => $lines,
1780 msg => '' };
1781 if (defined $_authors && ! defined $users{$author}) {
1782 die "Author: $author not defined in ",
1783 "$_authors file\n";
1784 }
1785 $log->{state} = 'msg_start';
1786 next;
1787 }
1788 # skip the first blank line of the message:
1789 if ($log->{state} eq 'msg_start' && /^$/) {
1790 $log->{state} = 'msg';
1791 } elsif ($log->{state} eq 'msg') {
1792 if ($ret->{lines}) {
1793 $ret->{msg} .= $_."\n";
1794 unless (--$ret->{lines}) {
1795 $log->{state} = 'sep';
1796 }
1797 } else {
1798 croak "Log parse error at: $_\n",
1799 $ret->{revision},"\n";
1800 }
1801 }
1802 }
1803 return $ret;
1804}
1805
1806sub svn_info {
1807 my $url = shift || $SVN_URL;
1808
1809 my $pid = open my $info_fh, '-|';
1810 defined $pid or croak $!;
1811
1812 if ($pid == 0) {
1813 exec(qw(svn info),$url) or croak $!;
1814 }
1815
1816 my $ret = {};
1817 # only single-lines seem to exist in svn info output
1818 while (<$info_fh>) {
1819 chomp $_;
1820 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1821 $ret->{$1} = $2;
1822 push @{$ret->{-order}}, $1;
1823 }
1824 }
1825 close $info_fh or croak $?;
1826 return $ret;
1827}
1828
1829sub sys { system(@_) == 0 or croak $? }
1830
1831sub do_update_index {
1832 my ($z_cmd, $cmd, $no_text_base) = @_;
1833
1834 my $z = open my $p, '-|';
1835 defined $z or croak $!;
1836 unless ($z) { exec @$z_cmd or croak $! }
1837
1838 my $pid = open my $ui, '|-';
1839 defined $pid or croak $!;
1840 unless ($pid) {
1841 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1842 }
1843 local $/ = "\0";
1844 while (my $x = <$p>) {
1845 chomp $x;
1846 if (!$no_text_base && lstat $x && ! -l _ &&
1847 svn_propget_base('svn:keywords', $x)) {
1848 my $mode = -x _ ? 0755 : 0644;
1849 my ($v,$d,$f) = File::Spec->splitpath($x);
1850 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1851 'text-base',"$f.svn-base");
1852 $tb =~ s#^/##;
1853 unless (-f $tb) {
1854 $tb = File::Spec->catfile($d, '.svn',
1855 'text-base',"$f.svn-base");
1856 $tb =~ s#^/##;
1857 }
1858 my @s = stat($x);
1859 unlink $x or croak $!;
1860 copy($tb, $x);
1861 chmod(($mode &~ umask), $x) or croak $!;
1862 utime $s[8], $s[9], $x;
1863 }
1864 print $ui $x,"\0";
1865 }
1866 close $ui or croak $?;
1867}
1868
1869sub index_changes {
1870 return if $_use_lib;
1871
1872 if (!-f "$GIT_SVN_DIR/info/exclude") {
1873 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1874 print $fd '.svn',"\n";
1875 close $fd or croak $!;
1876 }
1877 my $no_text_base = shift;
1878 do_update_index([qw/git-diff-files --name-only -z/],
1879 'remove',
1880 $no_text_base);
1881 do_update_index([qw/git-ls-files -z --others/,
1882 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1883 'add',
1884 $no_text_base);
1885}
1886
1887sub s_to_file {
1888 my ($str, $file, $mode) = @_;
1889 open my $fd,'>',$file or croak $!;
1890 print $fd $str,"\n" or croak $!;
1891 close $fd or croak $!;
1892 chmod ($mode &~ umask, $file) if (defined $mode);
1893}
1894
1895sub file_to_s {
1896 my $file = shift;
1897 open my $fd,'<',$file or croak "$!: file: $file\n";
1898 local $/;
1899 my $ret = <$fd>;
1900 close $fd or croak $!;
1901 $ret =~ s/\s*$//s;
1902 return $ret;
1903}
1904
1905sub assert_revision_unknown {
1906 my $r = shift;
1907 if (my $c = revdb_get($REVDB, $r)) {
1908 croak "$r = $c already exists! Why are we refetching it?";
1909 }
1910}
1911
1912sub trees_eq {
1913 my ($x, $y) = @_;
1914 my @x = safe_qx('git-cat-file','commit',$x);
1915 my @y = safe_qx('git-cat-file','commit',$y);
1916 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1917 || $y[0] !~ /^tree $sha1\n$/) {
1918 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1919 return 0
1920 }
1921 return 1;
1922}
1923
1924sub git_commit {
1925 my ($log_msg, @parents) = @_;
1926 assert_revision_unknown($log_msg->{revision});
1927 map_tree_joins() if (@_branch_from && !%tree_map);
1928
1929 my (@tmp_parents, @exec_parents, %seen_parent);
1930 if (my $lparents = $log_msg->{parents}) {
1931 @tmp_parents = @$lparents
1932 }
1933 # commit parents can be conditionally bound to a particular
1934 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1935 foreach my $p (@parents) {
1936 next unless defined $p;
1937 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1938 if ($1 == $log_msg->{revision}) {
1939 push @tmp_parents, $2;
1940 }
1941 } else {
1942 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1943 }
1944 }
1945 my $tree = $log_msg->{tree};
1946 if (!defined $tree) {
1947 my $index = set_index($GIT_SVN_INDEX);
1948 index_changes();
1949 chomp($tree = `git-write-tree`);
1950 croak $? if $?;
1951 restore_index($index);
1952 }
1953
1954 # just in case we clobber the existing ref, we still want that ref
1955 # as our parent:
1956 if (my $cur = eval { file_to_s("$GIT_DIR/refs/remotes/$GIT_SVN") }) {
1957 push @tmp_parents, $cur;
1958 }
1959
1960 if (exists $tree_map{$tree}) {
1961 foreach my $p (@{$tree_map{$tree}}) {
1962 my $skip;
1963 foreach (@tmp_parents) {
1964 # see if a common parent is found
1965 my $mb = eval {
1966 safe_qx('git-merge-base', $_, $p)
1967 };
1968 next if ($@ || $?);
1969 $skip = 1;
1970 last;
1971 }
1972 next if $skip;
1973 my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1974 next if (($SVN_UUID eq $uuid_p) &&
1975 ($log_msg->{revision} > $r_p));
1976 next if (defined $url_p && defined $SVN_URL &&
1977 ($SVN_UUID eq $uuid_p) &&
1978 ($url_p eq $SVN_URL));
1979 push @tmp_parents, $p;
1980 }
1981 }
1982 foreach (@tmp_parents) {
1983 next if $seen_parent{$_};
1984 $seen_parent{$_} = 1;
1985 push @exec_parents, $_;
1986 # MAXPARENT is defined to 16 in commit-tree.c:
1987 last if @exec_parents > 16;
1988 }
1989
1990 set_commit_env($log_msg);
1991 my @exec = ('git-commit-tree', $tree);
1992 push @exec, '-p', $_ foreach @exec_parents;
1993 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1994 or croak $!;
1995 print $msg_fh $log_msg->{msg} or croak $!;
1996 unless ($_no_metadata) {
1997 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision}",
1998 " $SVN_UUID\n" or croak $!;
1999 }
2000 $msg_fh->flush == 0 or croak $!;
2001 close $msg_fh or croak $!;
2002 chomp(my $commit = do { local $/; <$out_fh> });
2003 close $out_fh or croak $!;
2004 waitpid $pid, 0;
2005 croak $? if $?;
2006 if ($commit !~ /^$sha1$/o) {
2007 die "Failed to commit, invalid sha1: $commit\n";
2008 }
2009 sys('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
2010 revdb_set($REVDB, $log_msg->{revision}, $commit);
2011
2012 # this output is read via pipe, do not change:
2013 print "r$log_msg->{revision} = $commit\n";
2014 check_repack();
2015 return $commit;
2016}
2017
2018sub check_repack {
2019 if ($_repack && (--$_repack_nr == 0)) {
2020 $_repack_nr = $_repack;
2021 sys("git repack $_repack_flags");
2022 }
2023}
2024
2025sub set_commit_env {
2026 my ($log_msg) = @_;
2027 my $author = $log_msg->{author};
2028 if (!defined $author || length $author == 0) {
2029 $author = '(no author)';
2030 }
2031 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
2032 : ($author,"$author\@$SVN_UUID");
2033 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2034 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2035 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2036}
2037
2038sub apply_mod_line_blob {
2039 my $m = shift;
2040 if ($m->{mode_b} =~ /^120/) {
2041 blob_to_symlink($m->{sha1_b}, $m->{file_b});
2042 } else {
2043 blob_to_file($m->{sha1_b}, $m->{file_b});
2044 }
2045}
2046
2047sub blob_to_symlink {
2048 my ($blob, $link) = @_;
2049 defined $link or croak "\$link not defined!\n";
2050 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
2051 if (-l $link || -f _) {
2052 unlink $link or croak $!;
2053 }
2054
2055 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
2056 symlink $dest, $link or croak $!;
2057}
2058
2059sub blob_to_file {
2060 my ($blob, $file) = @_;
2061 defined $file or croak "\$file not defined!\n";
2062 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
2063 if (-l $file || -f _) {
2064 unlink $file or croak $!;
2065 }
2066
2067 open my $blob_fh, '>', $file or croak "$!: $file\n";
2068 my $pid = fork;
2069 defined $pid or croak $!;
2070
2071 if ($pid == 0) {
2072 open STDOUT, '>&', $blob_fh or croak $!;
2073 exec('git-cat-file','blob',$blob) or croak $!;
2074 }
2075 waitpid $pid, 0;
2076 croak $? if $?;
2077
2078 close $blob_fh or croak $!;
2079}
2080
2081sub safe_qx {
2082 my $pid = open my $child, '-|';
2083 defined $pid or croak $!;
2084 if ($pid == 0) {
2085 exec(@_) or croak $!;
2086 }
2087 my @ret = (<$child>);
2088 close $child or croak $?;
2089 die $? if $?; # just in case close didn't error out
2090 return wantarray ? @ret : join('',@ret);
2091}
2092
2093sub svn_compat_check {
2094 if ($_follow_parent) {
2095 print STDERR 'E: --follow-parent functionality is only ',
2096 "available when SVN libraries are used\n";
2097 exit 1;
2098 }
2099 my @co_help = safe_qx(qw(svn co -h));
2100 unless (grep /ignore-externals/,@co_help) {
2101 print STDERR "W: Installed svn version does not support ",
2102 "--ignore-externals\n";
2103 $_no_ignore_ext = 1;
2104 }
2105 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
2106 $_svn_co_url_revs = 1;
2107 }
2108 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
2109 $_svn_pg_peg_revs = 1;
2110 }
2111
2112 # I really, really hope nobody hits this...
2113 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
2114 print STDERR <<'';
2115W: The installed svn version does not support the --stop-on-copy flag in
2116 the log command.
2117 Lets hope the directory you're tracking is not a branch or tag
2118 and was never moved within the repository...
2119
2120 $_no_stop_copy = 1;
2121 }
2122}
2123
2124# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
2125# (and they won't honor URL@<rev> without -r<rev>, too!)
2126sub svn_cmd_checkout {
2127 my ($url, $rev, $dir) = @_;
2128 my @cmd = ('svn','co', "-r$rev");
2129 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
2130 $url .= "\@$rev" if $_svn_co_url_revs;
2131 sys(@cmd, $url, $dir);
2132}
2133
2134sub check_upgrade_needed {
2135 if (!-r $REVDB) {
2136 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2137 open my $fh, '>>',$REVDB or croak $!;
2138 close $fh;
2139 }
2140 my $old = eval {
2141 my $pid = open my $child, '-|';
2142 defined $pid or croak $!;
2143 if ($pid == 0) {
2144 close STDERR;
2145 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
2146 }
2147 my @ret = (<$child>);
2148 close $child or croak $?;
2149 die $? if $?; # just in case close didn't error out
2150 return wantarray ? @ret : join('',@ret);
2151 };
2152 return unless $old;
2153 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
2154 if ($@ || !$head) {
2155 print STDERR "Please run: $0 rebuild --upgrade\n";
2156 exit 1;
2157 }
2158}
2159
2160# fills %tree_map with a reverse mapping of trees to commits. Useful
2161# for finding parents to commit on.
2162sub map_tree_joins {
2163 my %seen;
2164 foreach my $br (@_branch_from) {
2165 my $pid = open my $pipe, '-|';
2166 defined $pid or croak $!;
2167 if ($pid == 0) {
2168 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
2169 or croak $!;
2170 }
2171 while (<$pipe>) {
2172 if (/^commit ($sha1)$/o) {
2173 my $commit = $1;
2174
2175 # if we've seen a commit,
2176 # we've seen its parents
2177 last if $seen{$commit};
2178 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
2179 unless (defined $tree) {
2180 die "Failed to parse commit $commit\n";
2181 }
2182 push @{$tree_map{$tree}}, $commit;
2183 $seen{$commit} = 1;
2184 }
2185 }
2186 close $pipe; # we could be breaking the pipe early
2187 }
2188}
2189
2190sub load_all_refs {
2191 if (@_branch_from) {
2192 print STDERR '--branch|-b parameters are ignored when ',
2193 "--branch-all-refs|-B is passed\n";
2194 }
2195
2196 # don't worry about rev-list on non-commit objects/tags,
2197 # it shouldn't blow up if a ref is a blob or tree...
2198 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2199}
2200
2201# '<svn username> = real-name <email address>' mapping based on git-svnimport:
2202sub load_authors {
2203 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2204 while (<$authors>) {
2205 chomp;
2206 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
2207 my ($user, $name, $email) = ($1, $2, $3);
2208 $users{$user} = [$name, $email];
2209 }
2210 close $authors or croak $!;
2211}
2212
2213sub rload_authors {
2214 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2215 while (<$authors>) {
2216 chomp;
2217 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2218 my ($user, $name, $email) = ($1, $2, $3);
2219 $rusers{"$name <$email>"} = $user;
2220 }
2221 close $authors or croak $!;
2222}
2223
2224sub svn_propget_base {
2225 my ($p, $f) = @_;
2226 $f .= '@BASE' if $_svn_pg_peg_revs;
2227 return safe_qx(qw/svn propget/, $p, $f);
2228}
2229
2230sub git_svn_each {
2231 my $sub = shift;
2232 foreach (`git-rev-parse --symbolic --all`) {
2233 next unless s#^refs/remotes/##;
2234 chomp $_;
2235 next unless -f "$GIT_DIR/svn/$_/info/url";
2236 &$sub($_);
2237 }
2238}
2239
2240sub migrate_revdb {
2241 git_svn_each(sub {
2242 my $id = shift;
2243 defined(my $pid = fork) or croak $!;
2244 if (!$pid) {
2245 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2246 init_vars();
2247 exit 0 if -r $REVDB;
2248 print "Upgrading svn => git mapping...\n";
2249 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2250 open my $fh, '>>',$REVDB or croak $!;
2251 close $fh;
2252 rebuild();
2253 print "Done upgrading. You may now delete the ",
2254 "deprecated $GIT_SVN_DIR/revs directory\n";
2255 exit 0;
2256 }
2257 waitpid $pid, 0;
2258 croak $? if $?;
2259 });
2260}
2261
2262sub migration_check {
2263 migrate_revdb() unless (-e $REVDB);
2264 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2265 print "Upgrading repository...\n";
2266 unless (-d "$GIT_DIR/svn") {
2267 mkdir "$GIT_DIR/svn" or croak $!;
2268 }
2269 print "Data from a previous version of git-svn exists, but\n\t",
2270 "$GIT_SVN_DIR\n\t(required for this version ",
2271 "($VERSION) of git-svn) does not.\n";
2272
2273 foreach my $x (`git-rev-parse --symbolic --all`) {
2274 next unless $x =~ s#^refs/remotes/##;
2275 chomp $x;
2276 next unless -f "$GIT_DIR/$x/info/url";
2277 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2278 next unless $u;
2279 my $dn = dirname("$GIT_DIR/svn/$x");
2280 mkpath([$dn]) unless -d $dn;
2281 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2282 }
2283 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2284 print "Done upgrading.\n";
2285}
2286
2287sub find_rev_before {
2288 my ($r, $id, $eq_ok) = @_;
2289 my $f = "$GIT_DIR/svn/$id/.rev_db";
2290 return (undef,undef) unless -r $f;
2291 --$r unless $eq_ok;
2292 while ($r > 0) {
2293 if (my $c = revdb_get($f, $r)) {
2294 return ($r, $c);
2295 }
2296 --$r;
2297 }
2298 return (undef, undef);
2299}
2300
2301sub init_vars {
2302 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2303 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2304 $REVDB = "$GIT_SVN_DIR/.rev_db";
2305 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2306 $SVN_URL = undef;
2307 $SVN_WC = "$GIT_SVN_DIR/tree";
2308 %tree_map = ();
2309}
2310
2311# convert GetOpt::Long specs for use by git-repo-config
2312sub read_repo_config {
2313 return unless -d $GIT_DIR;
2314 my $opts = shift;
2315 foreach my $o (keys %$opts) {
2316 my $v = $opts->{$o};
2317 my ($key) = ($o =~ /^([a-z\-]+)/);
2318 $key =~ s/-//g;
2319 my $arg = 'git-repo-config';
2320 $arg .= ' --int' if ($o =~ /[:=]i$/);
2321 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2322 if (ref $v eq 'ARRAY') {
2323 chomp(my @tmp = `$arg --get-all svn.$key`);
2324 @$v = @tmp if @tmp;
2325 } else {
2326 chomp(my $tmp = `$arg --get svn.$key`);
2327 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2328 $$v = $tmp;
2329 }
2330 }
2331 }
2332}
2333
2334sub set_default_vals {
2335 if (defined $_repack) {
2336 $_repack = 1000 if ($_repack <= 0);
2337 $_repack_nr = $_repack;
2338 $_repack_flags ||= '-d';
2339 }
2340}
2341
2342sub read_grafts {
2343 my $gr_file = shift;
2344 my ($grafts, $comments) = ({}, {});
2345 if (open my $fh, '<', $gr_file) {
2346 my @tmp;
2347 while (<$fh>) {
2348 if (/^($sha1)\s+/) {
2349 my $c = $1;
2350 if (@tmp) {
2351 @{$comments->{$c}} = @tmp;
2352 @tmp = ();
2353 }
2354 foreach my $p (split /\s+/, $_) {
2355 $grafts->{$c}->{$p} = 1;
2356 }
2357 } else {
2358 push @tmp, $_;
2359 }
2360 }
2361 close $fh or croak $!;
2362 @{$comments->{'END'}} = @tmp if @tmp;
2363 }
2364 return ($grafts, $comments);
2365}
2366
2367sub write_grafts {
2368 my ($grafts, $comments, $gr_file) = @_;
2369
2370 open my $fh, '>', $gr_file or croak $!;
2371 foreach my $c (sort keys %$grafts) {
2372 if ($comments->{$c}) {
2373 print $fh $_ foreach @{$comments->{$c}};
2374 }
2375 my $p = $grafts->{$c};
2376 my %x; # real parents
2377 delete $p->{$c}; # commits are not self-reproducing...
2378 my $pid = open my $ch, '-|';
2379 defined $pid or croak $!;
2380 if (!$pid) {
2381 exec(qw/git-cat-file commit/, $c) or croak $!;
2382 }
2383 while (<$ch>) {
2384 if (/^parent ($sha1)/) {
2385 $x{$1} = $p->{$1} = 1;
2386 } else {
2387 last unless /^\S/;
2388 }
2389 }
2390 close $ch; # breaking the pipe
2391
2392 # if real parents are the only ones in the grafts, drop it
2393 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2394
2395 my (@ip, @jp, $mb);
2396 my %del = %x;
2397 @ip = @jp = keys %$p;
2398 foreach my $i (@ip) {
2399 next if $del{$i} || $p->{$i} == 2;
2400 foreach my $j (@jp) {
2401 next if $i eq $j || $del{$j} || $p->{$j} == 2;
2402 $mb = eval { safe_qx('git-merge-base',$i,$j) };
2403 next unless $mb;
2404 chomp $mb;
2405 next if $x{$mb};
2406 if ($mb eq $j) {
2407 delete $p->{$i};
2408 $del{$i} = 1;
2409 } elsif ($mb eq $i) {
2410 delete $p->{$j};
2411 $del{$j} = 1;
2412 }
2413 }
2414 }
2415
2416 # if real parents are the only ones in the grafts, drop it
2417 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2418
2419 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2420 }
2421 if ($comments->{'END'}) {
2422 print $fh $_ foreach @{$comments->{'END'}};
2423 }
2424 close $fh or croak $!;
2425}
2426
2427sub read_url_paths_all {
2428 my ($l_map, $pfx, $p) = @_;
2429 my @dir;
2430 foreach (<$p/*>) {
2431 if (-r "$_/info/url") {
2432 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2433 my $id = $pfx . basename $_;
2434 my $url = file_to_s("$_/info/url");
2435 my ($u, $p) = repo_path_split($url);
2436 $l_map->{$u}->{$p} = $id;
2437 } elsif (-d $_) {
2438 push @dir, $_;
2439 }
2440 }
2441 foreach (@dir) {
2442 my $x = $_;
2443 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
2444 read_url_paths_all($l_map, $x, $_);
2445 }
2446}
2447
2448# this one only gets ids that have been imported, not new ones
2449sub read_url_paths {
2450 my $l_map = {};
2451 git_svn_each(sub { my $x = shift;
2452 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2453 my ($u, $p) = repo_path_split($url);
2454 $l_map->{$u}->{$p} = $x;
2455 });
2456 return $l_map;
2457}
2458
2459sub extract_metadata {
2460 my $id = shift or return (undef, undef, undef);
2461 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2462 \s([a-f\d\-]+)$/x);
2463 if (!$rev || !$uuid || !$url) {
2464 # some of the original repositories I made had
2465 # identifiers like this:
2466 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2467 }
2468 return ($url, $rev, $uuid);
2469}
2470
2471sub cmt_metadata {
2472 return extract_metadata((grep(/^git-svn-id: /,
2473 safe_qx(qw/git-cat-file commit/, shift)))[-1]);
2474}
2475
2476sub get_commit_time {
2477 my $cmt = shift;
2478 defined(my $pid = open my $fh, '-|') or croak $!;
2479 if (!$pid) {
2480 exec qw/git-rev-list --pretty=raw -n1/, $cmt or croak $!;
2481 }
2482 while (<$fh>) {
2483 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
2484 my ($s, $tz) = ($1, $2);
2485 if ($tz =~ s/^\+//) {
2486 $s += tz_to_s_offset($tz);
2487 } elsif ($tz =~ s/^\-//) {
2488 $s -= tz_to_s_offset($tz);
2489 }
2490 close $fh;
2491 return $s;
2492 }
2493 die "Can't get commit time for commit: $cmt\n";
2494}
2495
2496sub tz_to_s_offset {
2497 my ($tz) = @_;
2498 $tz =~ s/(\d\d)$//;
2499 return ($1 * 60) + ($tz * 3600);
2500}
2501
2502sub setup_pager { # translated to Perl from pager.c
2503 return unless (-t *STDOUT);
2504 my $pager = $ENV{PAGER};
2505 if (!defined $pager) {
2506 $pager = 'less';
2507 } elsif (length $pager == 0 || $pager eq 'cat') {
2508 return;
2509 }
2510 pipe my $rfd, my $wfd or return;
2511 defined(my $pid = fork) or croak $!;
2512 if (!$pid) {
2513 open STDOUT, '>&', $wfd or croak $!;
2514 return;
2515 }
2516 open STDIN, '<&', $rfd or croak $!;
2517 $ENV{LESS} ||= '-S';
2518 exec $pager or croak "Can't run pager: $!\n";;
2519}
2520
2521sub get_author_info {
2522 my ($dest, $author, $t, $tz) = @_;
2523 $author =~ s/(?:^\s*|\s*$)//g;
2524 $dest->{a_raw} = $author;
2525 my $_a;
2526 if ($_authors) {
2527 $_a = $rusers{$author} || undef;
2528 }
2529 if (!$_a) {
2530 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2531 }
2532 $dest->{t} = $t;
2533 $dest->{tz} = $tz;
2534 $dest->{a} = $_a;
2535 # Date::Parse isn't in the standard Perl distro :(
2536 if ($tz =~ s/^\+//) {
2537 $t += tz_to_s_offset($tz);
2538 } elsif ($tz =~ s/^\-//) {
2539 $t -= tz_to_s_offset($tz);
2540 }
2541 $dest->{t_utc} = $t;
2542}
2543
2544sub process_commit {
2545 my ($c, $r_min, $r_max, $defer) = @_;
2546 if (defined $r_min && defined $r_max) {
2547 if ($r_min == $c->{r} && $r_min == $r_max) {
2548 show_commit($c);
2549 return 0;
2550 }
2551 return 1 if $r_min == $r_max;
2552 if ($r_min < $r_max) {
2553 # we need to reverse the print order
2554 return 0 if (defined $_limit && --$_limit < 0);
2555 push @$defer, $c;
2556 return 1;
2557 }
2558 if ($r_min != $r_max) {
2559 return 1 if ($r_min < $c->{r});
2560 return 1 if ($r_max > $c->{r});
2561 }
2562 }
2563 return 0 if (defined $_limit && --$_limit < 0);
2564 show_commit($c);
2565 return 1;
2566}
2567
2568sub show_commit {
2569 my $c = shift;
2570 if ($_oneline) {
2571 my $x = "\n";
2572 if (my $l = $c->{l}) {
2573 while ($l->[0] =~ /^\s*$/) { shift @$l }
2574 $x = $l->[0];
2575 }
2576 $_l_fmt ||= 'A' . length($c->{r});
2577 print 'r',pack($_l_fmt, $c->{r}),' | ';
2578 print "$c->{c} | " if $_show_commit;
2579 print $x;
2580 } else {
2581 show_commit_normal($c);
2582 }
2583}
2584
2585sub show_commit_changed_paths {
2586 my ($c) = @_;
2587 return unless $c->{changed};
2588 print "Changed paths:\n", @{$c->{changed}};
2589}
2590
2591sub show_commit_normal {
2592 my ($c) = @_;
2593 print '-' x72, "\nr$c->{r} | ";
2594 print "$c->{c} | " if $_show_commit;
2595 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2596 localtime($c->{t_utc})), ' | ';
2597 my $nr_line = 0;
2598
2599 if (my $l = $c->{l}) {
2600 while ($l->[$#$l] eq "\n" && $#$l > 0
2601 && $l->[($#$l - 1)] eq "\n") {
2602 pop @$l;
2603 }
2604 $nr_line = scalar @$l;
2605 if (!$nr_line) {
2606 print "1 line\n\n\n";
2607 } else {
2608 if ($nr_line == 1) {
2609 $nr_line = '1 line';
2610 } else {
2611 $nr_line .= ' lines';
2612 }
2613 print $nr_line, "\n";
2614 show_commit_changed_paths($c);
2615 print "\n";
2616 print $_ foreach @$l;
2617 }
2618 } else {
2619 print "1 line\n";
2620 show_commit_changed_paths($c);
2621 print "\n";
2622
2623 }
2624 foreach my $x (qw/raw diff/) {
2625 if ($c->{$x}) {
2626 print "\n";
2627 print $_ foreach @{$c->{$x}}
2628 }
2629 }
2630}
2631
2632sub libsvn_load {
2633 return unless $_use_lib;
2634 $_use_lib = eval {
2635 require SVN::Core;
2636 if ($SVN::Core::VERSION lt '1.1.0') {
2637 die "Need SVN::Core 1.1.0 or better ",
2638 "(got $SVN::Core::VERSION) ",
2639 "Falling back to command-line svn\n";
2640 }
2641 require SVN::Ra;
2642 require SVN::Delta;
2643 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2644 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2645 $SVN::Node::dir.$SVN::Node::unknown.
2646 $SVN::Node::none.$SVN::Node::file.
2647 $SVN::Node::dir.$SVN::Node::unknown;
2648 1;
2649 };
2650}
2651
2652sub libsvn_connect {
2653 my ($url) = @_;
2654 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2655 SVN::Client::get_ssl_server_trust_file_provider(),
2656 SVN::Client::get_username_provider()]);
2657 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2658 return $s;
2659}
2660
2661sub libsvn_get_file {
2662 my ($gui, $f, $rev) = @_;
2663 my $p = $f;
2664 if (length $SVN_PATH > 0) {
2665 return unless ($p =~ s#^\Q$SVN_PATH\E/##);
2666 }
2667
2668 my ($hash, $pid, $in, $out);
2669 my $pool = SVN::Pool->new;
2670 defined($pid = open3($in, $out, '>&STDERR',
2671 qw/git-hash-object -w --stdin/)) or croak $!;
2672 # redirect STDOUT for SVN 1.1.x compatibility
2673 open my $stdout, '>&', \*STDOUT or croak $!;
2674 open STDOUT, '>&', $in or croak $!;
2675 my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
2676 $in->flush == 0 or croak $!;
2677 open STDOUT, '>&', $stdout or croak $!;
2678 close $in or croak $!;
2679 close $stdout or croak $!;
2680 $pool->clear;
2681 chomp($hash = do { local $/; <$out> });
2682 close $out or croak $!;
2683 waitpid $pid, 0;
2684 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2685
2686 my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2687 if (exists $props->{'svn:special'}) {
2688 $mode = '120000';
2689 my $link = `git-cat-file blob $hash`;
2690 $link =~ s/^link // or die "svn:special file with contents: <",
2691 $link, "> is not understood\n";
2692 defined($pid = open3($in, $out, '>&STDERR',
2693 qw/git-hash-object -w --stdin/)) or croak $!;
2694 print $in $link;
2695 $in->flush == 0 or croak $!;
2696 close $in or croak $!;
2697 chomp($hash = do { local $/; <$out> });
2698 close $out or croak $!;
2699 waitpid $pid, 0;
2700 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2701 }
2702 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2703}
2704
2705sub libsvn_log_entry {
2706 my ($rev, $author, $date, $msg, $parents) = @_;
2707 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2708 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2709 or die "Unable to parse date: $date\n";
2710 if (defined $_authors && ! defined $users{$author}) {
2711 die "Author: $author not defined in $_authors file\n";
2712 }
2713 $msg = '' if ($rev == 0 && !defined $msg);
2714 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2715 author => $author, msg => $msg."\n", parents => $parents || [] }
2716}
2717
2718sub process_rm {
2719 my ($gui, $last_commit, $f) = @_;
2720 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2721 # remove entire directories.
2722 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2723 defined(my $pid = open my $ls, '-|') or croak $!;
2724 if (!$pid) {
2725 exec(qw/git-ls-tree -r --name-only -z/,
2726 $last_commit,'--',$f) or croak $!;
2727 }
2728 local $/ = "\0";
2729 while (<$ls>) {
2730 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2731 }
2732 close $ls or croak $?;
2733 } else {
2734 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2735 }
2736}
2737
2738sub libsvn_fetch {
2739 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2740 open my $gui, '| git-update-index -z --index-info' or croak $!;
2741 my @amr;
2742 foreach my $f (keys %$paths) {
2743 my $m = $paths->{$f}->action();
2744 $f =~ s#^/+##;
2745 if ($m =~ /^[DR]$/) {
2746 print "\t$m\t$f\n" unless $_q;
2747 process_rm($gui, $last_commit, $f);
2748 next if $m eq 'D';
2749 # 'R' can be file replacements, too, right?
2750 }
2751 my $pool = SVN::Pool->new;
2752 my $t = $SVN->check_path($f, $rev, $pool);
2753 if ($t == $SVN::Node::file) {
2754 if ($m =~ /^[AMR]$/) {
2755 push @amr, [ $m, $f ];
2756 } else {
2757 die "Unrecognized action: $m, ($f r$rev)\n";
2758 }
2759 } elsif ($t == $SVN::Node::dir && $m =~ /^[AR]$/) {
2760 my @traversed = ();
2761 libsvn_traverse($gui, '', $f, $rev, \@traversed);
2762 foreach (@traversed) {
2763 push @amr, [ $m, $_ ]
2764 }
2765 }
2766 $pool->clear;
2767 }
2768 foreach (@amr) {
2769 print "\t$_->[0]\t$_->[1]\n" unless $_q;
2770 libsvn_get_file($gui, $_->[1], $rev)
2771 }
2772 close $gui or croak $?;
2773 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2774}
2775
2776sub svn_grab_base_rev {
2777 defined(my $pid = open my $fh, '-|') or croak $!;
2778 if (!$pid) {
2779 open my $null, '>', '/dev/null' or croak $!;
2780 open STDERR, '>&', $null or croak $!;
2781 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2782 or croak $!;
2783 }
2784 chomp(my $c = do { local $/; <$fh> });
2785 close $fh;
2786 if (defined $c && length $c) {
2787 my ($url, $rev, $uuid) = cmt_metadata($c);
2788 return ($rev, $c) if defined $rev;
2789 }
2790 if ($_no_metadata) {
2791 my $offset = -41; # from tail
2792 my $rl;
2793 open my $fh, '<', $REVDB or
2794 die "--no-metadata specified and $REVDB not readable\n";
2795 seek $fh, $offset, 2;
2796 $rl = readline $fh;
2797 defined $rl or return (undef, undef);
2798 chomp $rl;
2799 while ($c ne $rl && tell $fh != 0) {
2800 $offset -= 41;
2801 seek $fh, $offset, 2;
2802 $rl = readline $fh;
2803 defined $rl or return (undef, undef);
2804 chomp $rl;
2805 }
2806 my $rev = tell $fh;
2807 croak $! if ($rev < -1);
2808 $rev = ($rev - 41) / 41;
2809 close $fh or croak $!;
2810 return ($rev, $c);
2811 }
2812 return (undef, undef);
2813}
2814
2815sub libsvn_parse_revision {
2816 my $base = shift;
2817 my $head = $SVN->get_latest_revnum();
2818 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2819 return ($base + 1, $head) if (defined $base);
2820 return (0, $head);
2821 }
2822 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2823 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2824 if ($_revision =~ /^BASE:(\d+)$/) {
2825 return ($base + 1, $1) if (defined $base);
2826 return (0, $head);
2827 }
2828 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2829 die "revision argument: $_revision not understood by git-svn\n",
2830 "Try using the command-line svn client instead\n";
2831}
2832
2833sub libsvn_traverse {
2834 my ($gui, $pfx, $path, $rev, $files) = @_;
2835 my $cwd = "$pfx/$path";
2836 my $pool = SVN::Pool->new;
2837 $cwd =~ s#^/+##g;
2838 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2839 foreach my $d (keys %$dirent) {
2840 my $t = $dirent->{$d}->kind;
2841 if ($t == $SVN::Node::dir) {
2842 libsvn_traverse($gui, $cwd, $d, $rev, $files);
2843 } elsif ($t == $SVN::Node::file) {
2844 my $file = "$cwd/$d";
2845 if (defined $files) {
2846 push @$files, $file;
2847 } else {
2848 print "\tA\t$file\n" unless $_q;
2849 libsvn_get_file($gui, $file, $rev);
2850 }
2851 }
2852 }
2853 $pool->clear;
2854}
2855
2856sub libsvn_traverse_ignore {
2857 my ($fh, $path, $r) = @_;
2858 $path =~ s#^/+##g;
2859 my $pool = SVN::Pool->new;
2860 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2861 my $p = $path;
2862 $p =~ s#^\Q$SVN_PATH\E/?##;
2863 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2864 if (my $s = $props->{'svn:ignore'}) {
2865 $s =~ s/[\r\n]+/\n/g;
2866 chomp $s;
2867 if (length $p == 0) {
2868 $s =~ s#\n#\n/$p#g;
2869 print $fh "/$s\n";
2870 } else {
2871 $s =~ s#\n#\n/$p/#g;
2872 print $fh "/$p/$s\n";
2873 }
2874 }
2875 foreach (sort keys %$dirent) {
2876 next if $dirent->{$_}->kind != $SVN::Node::dir;
2877 libsvn_traverse_ignore($fh, "$path/$_", $r);
2878 }
2879 $pool->clear;
2880}
2881
2882sub revisions_eq {
2883 my ($path, $r0, $r1) = @_;
2884 return 1 if $r0 == $r1;
2885 my $nr = 0;
2886 if ($_use_lib) {
2887 # should be OK to use Pool here (r1 - r0) should be small
2888 my $pool = SVN::Pool->new;
2889 libsvn_get_log($SVN, "/$path", $r0, $r1,
2890 0, 1, 1, sub {$nr++}, $pool);
2891 $pool->clear;
2892 } else {
2893 my ($url, undef) = repo_path_split($SVN_URL);
2894 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2895 while (next_log_entry($svn_log)) { $nr++ }
2896 close $svn_log->{fh};
2897 }
2898 return 0 if ($nr > 1);
2899 return 1;
2900}
2901
2902sub libsvn_find_parent_branch {
2903 my ($paths, $rev, $author, $date, $msg) = @_;
2904 my $svn_path = '/'.$SVN_PATH;
2905
2906 # look for a parent from another branch:
2907 my $i = $paths->{$svn_path} or return;
2908 my $branch_from = $i->copyfrom_path or return;
2909 my $r = $i->copyfrom_rev;
2910 print STDERR "Found possible branch point: ",
2911 "$branch_from => $svn_path, $r\n";
2912 $branch_from =~ s#^/##;
2913 my $l_map = {};
2914 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2915 my $url = $SVN->{url};
2916 defined $l_map->{$url} or return;
2917 my $id = $l_map->{$url}->{$branch_from};
2918 if (!defined $id && $_follow_parent) {
2919 print STDERR "Following parent: $branch_from\@$r\n";
2920 # auto create a new branch and follow it
2921 $id = basename($branch_from);
2922 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2923 while (-r "$GIT_DIR/svn/$id") {
2924 # just grow a tail if we're not unique enough :x
2925 $id .= '-';
2926 }
2927 }
2928 return unless defined $id;
2929
2930 my ($r0, $parent) = find_rev_before($r,$id,1);
2931 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2932 defined(my $pid = fork) or croak $!;
2933 if (!$pid) {
2934 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2935 init_vars();
2936 $SVN_URL = "$url/$branch_from";
2937 $SVN_LOG = $SVN = undef;
2938 setup_git_svn();
2939 # we can't assume SVN_URL exists at r+1:
2940 $_revision = "0:$r";
2941 fetch_lib();
2942 exit 0;
2943 }
2944 waitpid $pid, 0;
2945 croak $? if $?;
2946 ($r0, $parent) = find_rev_before($r,$id,1);
2947 }
2948 return unless (defined $r0 && defined $parent);
2949 if (revisions_eq($branch_from, $r0, $r)) {
2950 unlink $GIT_SVN_INDEX;
2951 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2952 sys(qw/git-read-tree/, $parent);
2953 return libsvn_fetch($parent, $paths, $rev,
2954 $author, $date, $msg);
2955 }
2956 print STDERR "Nope, branch point not imported or unknown\n";
2957 return undef;
2958}
2959
2960sub libsvn_get_log {
2961 my ($ra, @args) = @_;
2962 if ($SVN::Core::VERSION le '1.2.0') {
2963 splice(@args, 3, 1);
2964 }
2965 $ra->get_log(@args);
2966}
2967
2968sub libsvn_new_tree {
2969 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2970 return $log_entry;
2971 }
2972 my ($paths, $rev, $author, $date, $msg) = @_;
2973 open my $gui, '| git-update-index -z --index-info' or croak $!;
2974 libsvn_traverse($gui, '', $SVN_PATH, $rev);
2975 close $gui or croak $?;
2976 return libsvn_log_entry($rev, $author, $date, $msg);
2977}
2978
2979sub find_graft_path_commit {
2980 my ($tree_paths, $p1, $r1) = @_;
2981 foreach my $x (keys %$tree_paths) {
2982 next unless ($p1 =~ /^\Q$x\E/);
2983 my $i = $tree_paths->{$x};
2984 my ($r0, $parent) = find_rev_before($r1,$i,1);
2985 return $parent if (defined $r0 && $r0 == $r1);
2986 print STDERR "r$r1 of $i not imported\n";
2987 next;
2988 }
2989 return undef;
2990}
2991
2992sub find_graft_path_parents {
2993 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2994 foreach my $x (keys %$tree_paths) {
2995 next unless ($p0 =~ /^\Q$x\E/);
2996 my $i = $tree_paths->{$x};
2997 my ($r, $parent) = find_rev_before($r0, $i, 1);
2998 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2999 my ($url_b, undef, $uuid_b) = cmt_metadata($c);
3000 my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
3001 next if ($url_a && $url_b && $url_a eq $url_b &&
3002 $uuid_b eq $uuid_a);
3003 $grafts->{$c}->{$parent} = 1;
3004 }
3005 }
3006}
3007
3008sub libsvn_graft_file_copies {
3009 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
3010 foreach (keys %$paths) {
3011 my $i = $paths->{$_};
3012 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
3013 $i->copyfrom_rev);
3014 next unless (defined $p0 && defined $r0);
3015
3016 my $p1 = $_;
3017 $p1 =~ s#^/##;
3018 $p0 =~ s#^/##;
3019 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
3020 next unless $c;
3021 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
3022 }
3023}
3024
3025sub set_index {
3026 my $old = $ENV{GIT_INDEX_FILE};
3027 $ENV{GIT_INDEX_FILE} = shift;
3028 return $old;
3029}
3030
3031sub restore_index {
3032 my ($old) = @_;
3033 if (defined $old) {
3034 $ENV{GIT_INDEX_FILE} = $old;
3035 } else {
3036 delete $ENV{GIT_INDEX_FILE};
3037 }
3038}
3039
3040sub libsvn_commit_cb {
3041 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
3042 if ($_optimize_commits && $rev == ($r_last + 1)) {
3043 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
3044 $log->{tree} = get_tree_from_treeish($c);
3045 my $cmt = git_commit($log, $cmt_last, $c);
3046 my @diff = safe_qx('git-diff-tree', $cmt, $c);
3047 if (@diff) {
3048 print STDERR "Trees differ: $cmt $c\n",
3049 join('',@diff),"\n";
3050 exit 1;
3051 }
3052 } else {
3053 fetch("$rev=$c");
3054 }
3055}
3056
3057sub libsvn_ls_fullurl {
3058 my $fullurl = shift;
3059 my ($repo, $path) = repo_path_split($fullurl);
3060 $SVN ||= libsvn_connect($repo);
3061 my @ret;
3062 my $pool = SVN::Pool->new;
3063 my ($dirent, undef, undef) = $SVN->get_dir($path,
3064 $SVN->get_latest_revnum, $pool);
3065 foreach my $d (keys %$dirent) {
3066 if ($dirent->{$d}->kind == $SVN::Node::dir) {
3067 push @ret, "$d/"; # add '/' for compat with cli svn
3068 }
3069 }
3070 $pool->clear;
3071 return @ret;
3072}
3073
3074
3075sub libsvn_skip_unknown_revs {
3076 my $err = shift;
3077 my $errno = $err->apr_err();
3078 # Maybe the branch we're tracking didn't
3079 # exist when the repo started, so it's
3080 # not an error if it doesn't, just continue
3081 #
3082 # Wonderfully consistent library, eh?
3083 # 160013 - svn:// and file://
3084 # 175002 - http(s)://
3085 # More codes may be discovered later...
3086 if ($errno == 175002 || $errno == 160013) {
3087 return;
3088 }
3089 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3090};
3091
3092# Tie::File seems to be prone to offset errors if revisions get sparse,
3093# it's not that fast, either. Tie::File is also not in Perl 5.6. So
3094# one of my favorite modules is out :< Next up would be one of the DBM
3095# modules, but I'm not sure which is most portable... So I'll just
3096# go with something that's plain-text, but still capable of
3097# being randomly accessed. So here's my ultra-simple fixed-width
3098# database. All records are 40 characters + "\n", so it's easy to seek
3099# to a revision: (41 * rev) is the byte offset.
3100# A record of 40 0s denotes an empty revision.
3101# And yes, it's still pretty fast (faster than Tie::File).
3102sub revdb_set {
3103 my ($file, $rev, $commit) = @_;
3104 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
3105 open my $fh, '+<', $file or croak $!;
3106 my $offset = $rev * 41;
3107 # assume that append is the common case:
3108 seek $fh, 0, 2 or croak $!;
3109 my $pos = tell $fh;
3110 if ($pos < $offset) {
3111 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
3112 }
3113 seek $fh, $offset, 0 or croak $!;
3114 print $fh $commit,"\n";
3115 close $fh or croak $!;
3116}
3117
3118sub revdb_get {
3119 my ($file, $rev) = @_;
3120 my $ret;
3121 my $offset = $rev * 41;
3122 open my $fh, '<', $file or croak $!;
3123 seek $fh, $offset, 0;
3124 if (tell $fh == $offset) {
3125 $ret = readline $fh;
3126 if (defined $ret) {
3127 chomp $ret;
3128 $ret = undef if ($ret =~ /^0{40}$/);
3129 }
3130 }
3131 close $fh or croak $!;
3132 return $ret;
3133}
3134
3135sub copy_remote_ref {
3136 my $origin = $_cp_remote ? $_cp_remote : 'origin';
3137 my $ref = "refs/remotes/$GIT_SVN";
3138 if (safe_qx('git-ls-remote', $origin, $ref)) {
3139 sys(qw/git fetch/, $origin, "$ref:$ref");
3140 } else {
3141 die "Unable to find remote reference: ",
3142 "refs/remotes/$GIT_SVN on $origin\n";
3143 }
3144}
3145
3146package SVN::Git::Editor;
3147use vars qw/@ISA/;
3148use strict;
3149use warnings;
3150use Carp qw/croak/;
3151use IO::File;
3152
3153sub new {
3154 my $class = shift;
3155 my $git_svn = shift;
3156 my $self = SVN::Delta::Editor->new(@_);
3157 bless $self, $class;
3158 foreach (qw/svn_path c r ra /) {
3159 die "$_ required!\n" unless (defined $git_svn->{$_});
3160 $self->{$_} = $git_svn->{$_};
3161 }
3162 $self->{pool} = SVN::Pool->new;
3163 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3164 $self->{rm} = { };
3165 require Digest::MD5;
3166 return $self;
3167}
3168
3169sub split_path {
3170 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3171}
3172
3173sub repo_path {
3174 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
3175 : $_[0]->{svn_path}
3176}
3177
3178sub url_path {
3179 my ($self, $path) = @_;
3180 $self->{ra}->{url} . '/' . $self->repo_path($path);
3181}
3182
3183sub rmdirs {
3184 my ($self, $q) = @_;
3185 my $rm = $self->{rm};
3186 delete $rm->{''}; # we never delete the url we're tracking
3187 return unless %$rm;
3188
3189 foreach (keys %$rm) {
3190 my @d = split m#/#, $_;
3191 my $c = shift @d;
3192 $rm->{$c} = 1;
3193 while (@d) {
3194 $c .= '/' . shift @d;
3195 $rm->{$c} = 1;
3196 }
3197 }
3198 delete $rm->{$self->{svn_path}};
3199 delete $rm->{''}; # we never delete the url we're tracking
3200 return unless %$rm;
3201
3202 defined(my $pid = open my $fh,'-|') or croak $!;
3203 if (!$pid) {
3204 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
3205 }
3206 local $/ = "\0";
3207 my @svn_path = split m#/#, $self->{svn_path};
3208 while (<$fh>) {
3209 chomp;
3210 my @dn = (@svn_path, (split m#/#, $_));
3211 while (pop @dn) {
3212 delete $rm->{join '/', @dn};
3213 }
3214 unless (%$rm) {
3215 close $fh;
3216 return;
3217 }
3218 }
3219 close $fh;
3220
3221 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3222 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3223 $self->close_directory($bat->{$d}, $p);
3224 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3225 print "\tD+\t/$d/\n" unless $q;
3226 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3227 delete $bat->{$d};
3228 }
3229}
3230
3231sub open_or_add_dir {
3232 my ($self, $full_path, $baton) = @_;
3233 my $p = SVN::Pool->new;
3234 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
3235 $p->clear;
3236 if ($t == $SVN::Node::none) {
3237 return $self->add_directory($full_path, $baton,
3238 undef, -1, $self->{pool});
3239 } elsif ($t == $SVN::Node::dir) {
3240 return $self->open_directory($full_path, $baton,
3241 $self->{r}, $self->{pool});
3242 }
3243 print STDERR "$full_path already exists in repository at ",
3244 "r$self->{r} and it is not a directory (",
3245 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3246 exit 1;
3247}
3248
3249sub ensure_path {
3250 my ($self, $path) = @_;
3251 my $bat = $self->{bat};
3252 $path = $self->repo_path($path);
3253 return $bat->{''} unless (length $path);
3254 my @p = split m#/+#, $path;
3255 my $c = shift @p;
3256 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3257 while (@p) {
3258 my $c0 = $c;
3259 $c .= '/' . shift @p;
3260 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3261 }
3262 return $bat->{$c};
3263}
3264
3265sub A {
3266 my ($self, $m, $q) = @_;
3267 my ($dir, $file) = split_path($m->{file_b});
3268 my $pbat = $self->ensure_path($dir);
3269 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3270 undef, -1);
3271 print "\tA\t$m->{file_b}\n" unless $q;
3272 $self->chg_file($fbat, $m);
3273 $self->close_file($fbat,undef,$self->{pool});
3274}
3275
3276sub C {
3277 my ($self, $m, $q) = @_;
3278 my ($dir, $file) = split_path($m->{file_b});
3279 my $pbat = $self->ensure_path($dir);
3280 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3281 $self->url_path($m->{file_a}), $self->{r});
3282 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3283 $self->chg_file($fbat, $m);
3284 $self->close_file($fbat,undef,$self->{pool});
3285}
3286
3287sub delete_entry {
3288 my ($self, $path, $pbat) = @_;
3289 my $rpath = $self->repo_path($path);
3290 my ($dir, $file) = split_path($rpath);
3291 $self->{rm}->{$dir} = 1;
3292 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3293}
3294
3295sub R {
3296 my ($self, $m, $q) = @_;
3297 my ($dir, $file) = split_path($m->{file_b});
3298 my $pbat = $self->ensure_path($dir);
3299 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3300 $self->url_path($m->{file_a}), $self->{r});
3301 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3302 $self->chg_file($fbat, $m);
3303 $self->close_file($fbat,undef,$self->{pool});
3304
3305 ($dir, $file) = split_path($m->{file_a});
3306 $pbat = $self->ensure_path($dir);
3307 $self->delete_entry($m->{file_a}, $pbat);
3308}
3309
3310sub M {
3311 my ($self, $m, $q) = @_;
3312 my ($dir, $file) = split_path($m->{file_b});
3313 my $pbat = $self->ensure_path($dir);
3314 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3315 $pbat,$self->{r},$self->{pool});
3316 print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3317 $self->chg_file($fbat, $m);
3318 $self->close_file($fbat,undef,$self->{pool});
3319}
3320
3321sub T { shift->M(@_) }
3322
3323sub change_file_prop {
3324 my ($self, $fbat, $pname, $pval) = @_;
3325 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3326}
3327
3328sub chg_file {
3329 my ($self, $fbat, $m) = @_;
3330 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3331 $self->change_file_prop($fbat,'svn:executable','*');
3332 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3333 $self->change_file_prop($fbat,'svn:executable',undef);
3334 }
3335 my $fh = IO::File->new_tmpfile or croak $!;
3336 if ($m->{mode_b} =~ /^120/) {
3337 print $fh 'link ' or croak $!;
3338 $self->change_file_prop($fbat,'svn:special','*');
3339 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3340 $self->change_file_prop($fbat,'svn:special',undef);
3341 }
3342 defined(my $pid = fork) or croak $!;
3343 if (!$pid) {
3344 open STDOUT, '>&', $fh or croak $!;
3345 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3346 }
3347 waitpid $pid, 0;
3348 croak $? if $?;
3349 $fh->flush == 0 or croak $!;
3350 seek $fh, 0, 0 or croak $!;
3351
3352 my $md5 = Digest::MD5->new;
3353 $md5->addfile($fh) or croak $!;
3354 seek $fh, 0, 0 or croak $!;
3355
3356 my $exp = $md5->hexdigest;
3357 my $pool = SVN::Pool->new;
3358 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3359 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3360 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3361 $pool->clear;
3362
3363 close $fh or croak $!;
3364}
3365
3366sub D {
3367 my ($self, $m, $q) = @_;
3368 my ($dir, $file) = split_path($m->{file_b});
3369 my $pbat = $self->ensure_path($dir);
3370 print "\tD\t$m->{file_b}\n" unless $q;
3371 $self->delete_entry($m->{file_b}, $pbat);
3372}
3373
3374sub close_edit {
3375 my ($self) = @_;
3376 my ($p,$bat) = ($self->{pool}, $self->{bat});
3377 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3378 $self->close_directory($bat->{$_}, $p);
3379 }
3380 $self->SUPER::close_edit($p);
3381 $p->clear;
3382}
3383
3384sub abort_edit {
3385 my ($self) = @_;
3386 $self->SUPER::abort_edit($self->{pool});
3387 $self->{pool}->clear;
3388}
3389
3390__END__
3391
3392Data structures:
3393
3394$svn_log hashref (as returned by svn_log_raw)
3395{
3396 fh => file handle of the log file,
3397 state => state of the log file parser (sep/msg/rev/msg_start...)
3398}
3399
3400$log_msg hashref as returned by next_log_entry($svn_log)
3401{
3402 msg => 'whitespace-formatted log entry
3403', # trailing newline is preserved
3404 revision => '8', # integer
3405 date => '2004-02-24T17:01:44.108345Z', # commit date
3406 author => 'committer name'
3407};
3408
3409
3410@mods = array of diff-index line hashes, each element represents one line
3411 of diff-index output
3412
3413diff-index line ($m hash)
3414{
3415 mode_a => first column of diff-index output, no leading ':',
3416 mode_b => second column of diff-index output,
3417 sha1_b => sha1sum of the final blob,
3418 chg => change type [MCRADT],
3419 file_a => original file name of a file (iff chg is 'C' or 'R')
3420 file_b => new/current file name of a file (any chg)
3421}
3422;
3423
3424# retval of read_url_paths{,_all}();
3425$l_map = {
3426 # repository root url
3427 'https://svn.musicpd.org' => {
3428 # repository path # GIT_SVN_ID
3429 'mpd/trunk' => 'trunk',
3430 'mpd/tags/0.11.5' => 'tags/0.11.5',
3431 },
3432}
3433
3434Notes:
3435 I don't trust the each() function on unless I created %hash myself
3436 because the internal iterator may not have started at base.