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