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