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