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