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