git-svn: avoid creating some small files
[git/debian.git] / contrib / git-svn / git-svn.perl
blob88af9c570473697bc6970d76aab87628528b52fa
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '1.1.1-broken';
13 use Cwd qw/abs_path/;
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
17 my $LC_ALL = $ENV{LC_ALL};
18 my $TZ = $ENV{TZ};
19 # make sure the svn binary gives consistent output between locales and TZs:
20 $ENV{TZ} = 'UTC';
21 $ENV{LC_ALL} = 'C';
23 # If SVN:: library support is added, please make the dependencies
24 # optional and preserve the capability to use the command-line client.
25 # use eval { require SVN::... } to make it lazy load
26 # We don't use any modules not in the standard Perl distribution:
27 use Carp qw/croak/;
28 use IO::File qw//;
29 use File::Basename qw/dirname basename/;
30 use File::Path qw/mkpath/;
31 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
32 use File::Spec qw//;
33 use POSIX qw/strftime/;
34 use Memoize;
35 memoize('revisions_eq');
37 my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
38 $_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
39 libsvn_load();
40 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
41 my $sha1 = qr/[a-f\d]{40}/;
42 my $sha1_short = qr/[a-f\d]{4,40}/;
43 my ($_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);
49 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
50 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
51 my @repo_path_split_cache;
53 my %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);
60 my ($_trunk, $_tags, $_branches);
61 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
62 'tags|t=s' => \$_tags,
63 'branches|b=s' => \$_branches );
64 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
66 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
67 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
69 my %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 } ],
111 my $cmd;
112 for (my $i = 0; $i < @ARGV; $i++) {
113 if (defined $cmd{$ARGV[$i]}) {
114 $cmd = $ARGV[$i];
115 splice @ARGV, $i, 1;
116 last;
120 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
122 read_repo_config(\%opts);
123 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
124 'version|V' => \$_version,
125 'id|i=s' => \$GIT_SVN);
126 exit 1 if (!$rv && $cmd ne 'log');
128 set_default_vals();
129 usage(0) if $_help;
130 version() if $_version;
131 usage(1) unless defined $cmd;
132 init_vars();
133 load_authors() if $_authors;
134 load_all_refs() if $_branch_all_refs;
135 svn_compat_check();
136 migration_check() unless $cmd =~ /^(?:init|multi-init)$/;
137 $cmd{$cmd}->[0]->(@ARGV);
138 exit 0;
140 ####################### primary functions ######################
141 sub usage {
142 my $exit = shift || 0;
143 my $fd = $exit ? \*STDERR : \*STDOUT;
144 print $fd <<"";
145 git-svn - bidirectional operations between a single Subversion tree and git
146 Usage: $0 <command> [options] [arguments]\n
148 print $fd "Available commands:\n" unless $cmd;
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";
161 print $fd <<"";
162 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
163 arbitrary identifier if you're tracking multiple SVN branches/repositories in
164 one git repository and want to keep them separate. See git-svn(1) for more
165 information.
167 exit $exit;
170 sub version {
171 print "git-svn version $VERSION\n";
172 exit 0;
175 sub 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();
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 $!;
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";
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));
207 unless (defined $latest) {
208 if (!$SVN_URL && !$url) {
209 croak "SVN repository location required: $url\n";
211 $SVN_URL ||= $url;
212 $SVN_UUID ||= $uuid;
213 setup_git_svn();
214 $latest = $rev;
216 revdb_set($REVDB, $rev, $c);
217 print "r$rev = $c\n";
218 $newest_rev = $rev if ($rev > $newest_rev);
220 close $rev_list or croak $?;
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 $!;
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 $!;
238 waitpid $pid, 0;
239 croak $? if $?;
240 out:
241 if ($_upgrade) {
242 print STDERR <<"";
243 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
244 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
249 sub 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);
259 setup_git_svn();
262 sub 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});
270 return $ret;
273 sub 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';
279 push @log_args, "-r$_revision";
280 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
282 my $svn_log = svn_log_raw(@log_args);
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);
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";
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;
324 close $svn_log->{fh};
325 $last->{commit} = $last_commit;
326 return $last;
329 sub 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 }
341 my $index = set_index($GIT_SVN_INDEX);
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);
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);
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";
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 print "Fetching revisions $min .. $max\n";
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);
394 $SVN::Error::handler = sub { 'quiet warnings' };
395 exit 0;
397 waitpid $pid, 0;
398 croak $? if $?;
399 ($last_rev, $last_commit) = svn_grab_base_rev();
400 last if ($max >= $head);
401 $min = $max + 1;
402 $max += $inc;
403 $max = $head if ($max > $head);
405 restore_index($index);
406 return { revision => $last_rev, commit => $last_commit };
409 sub commit {
410 my (@commits) = @_;
411 check_upgrade_needed();
412 if ($_stdin || !@commits) {
413 print "Reading from stdin...\n";
414 @commits = ();
415 while (<STDIN>) {
416 if (/\b($sha1_short)\b/o) {
417 unshift @commits, $1;
421 my @revs;
422 foreach my $c (@commits) {
423 chomp(my @tmp = safe_qx('git-rev-parse',$c));
424 if (scalar @tmp == 1) {
425 push @revs, $tmp[0];
426 } elsif (scalar @tmp > 1) {
427 push @revs, reverse (safe_qx('git-rev-list',@tmp));
428 } else {
429 die "Failed to rev-parse $c\n";
432 chomp @revs;
433 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
434 print "Done committing ",scalar @revs," revisions to SVN\n";
437 sub commit_cmd {
438 my (@revs) = @_;
440 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
441 my $info = svn_info('.');
442 my $fetched = fetch();
443 if ($info->{Revision} != $fetched->{revision}) {
444 print STDERR "There are new revisions that were fetched ",
445 "and need to be merged (or acknowledged) ",
446 "before committing.\n";
447 exit 1;
449 $info = svn_info('.');
450 read_uuid($info);
451 my $last = $fetched;
452 foreach my $c (@revs) {
453 my $mods = svn_checkout_tree($last, $c);
454 if (scalar @$mods == 0) {
455 print "Skipping, no changes detected\n";
456 next;
458 $last = svn_commit_tree($last, $c);
462 sub commit_lib {
463 my (@revs) = @_;
464 my ($r_last, $cmt_last) = svn_grab_base_rev();
465 defined $r_last or die "Must have an existing revision to commit\n";
466 my $fetched = fetch_lib();
467 if ($r_last != $fetched->{revision}) {
468 print STDERR "There are new revisions that were fetched ",
469 "and need to be merged (or acknowledged) ",
470 "before committing.\n",
471 "last rev: $r_last\n",
472 " current: $fetched->{revision}\n";
473 exit 1;
475 read_uuid();
476 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
477 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
479 foreach my $c (@revs) {
480 # fork for each commit because there's a memory leak I
481 # can't track down... (it's probably in the SVN code)
482 defined(my $pid = open my $fh, '-|') or croak $!;
483 if (!$pid) {
484 if (defined $LC_ALL) {
485 $ENV{LC_ALL} = $LC_ALL;
486 } else {
487 delete $ENV{LC_ALL};
489 my $log_msg = get_commit_message($c, $commit_msg);
490 my $ed = SVN::Git::Editor->new(
491 { r => $r_last,
492 ra => $SVN,
493 c => $c,
494 svn_path => $SVN_PATH
496 $SVN->get_commit_editor(
497 $log_msg->{msg},
498 sub {
499 libsvn_commit_cb(
500 @_, $c,
501 $log_msg->{msg},
502 $r_last,
503 $cmt_last)
505 @lock)
507 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
508 if (@$mods == 0) {
509 print "No changes\nr$r_last = $cmt_last\n";
510 $ed->abort_edit;
511 } else {
512 $ed->close_edit;
514 exit 0;
516 my ($r_new, $cmt_new, $no);
517 while (<$fh>) {
518 print $_;
519 chomp;
520 if (/^r(\d+) = ($sha1)$/o) {
521 ($r_new, $cmt_new) = ($1, $2);
522 } elsif ($_ eq 'No changes') {
523 $no = 1;
526 close $fh or croak $!;
527 if (! defined $r_new && ! defined $cmt_new) {
528 unless ($no) {
529 die "Failed to parse revision information\n";
531 } else {
532 ($r_last, $cmt_last) = ($r_new, $cmt_new);
535 unlink $commit_msg;
538 sub show_ignore {
539 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
540 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
543 sub show_ignore_cmd {
544 require File::Find or die $!;
545 if (defined $_revision) {
546 die "-r/--revision option doesn't work unless the Perl SVN ",
547 "libraries are used\n";
549 chdir $SVN_WC or croak $!;
550 my %ign;
551 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
552 s#^\./##;
553 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
554 }}, no_chdir=>1},'.');
556 print "\n# /\n";
557 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
558 delete $ign{'.'};
559 foreach my $i (sort keys %ign) {
560 print "\n# ",$i,"\n";
561 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
565 sub show_ignore_lib {
566 my $repo;
567 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
568 $SVN ||= libsvn_connect($repo);
569 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
570 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
573 sub graft_branches {
574 my $gr_file = "$GIT_DIR/info/grafts";
575 my ($grafts, $comments) = read_grafts($gr_file);
576 my $gr_sha1;
578 if (%$grafts) {
579 # temporarily disable our grafts file to make this idempotent
580 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
581 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
584 my $l_map = read_url_paths();
585 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
586 unless ($_no_default_regex) {
587 push @re, ( qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
588 qr/\b(?:from|of)\s+(\S.+)/is );
590 foreach my $u (keys %$l_map) {
591 if (@re) {
592 foreach my $p (keys %{$l_map->{$u}}) {
593 graft_merge_msg($grafts,$l_map,$u,$p);
596 unless ($_no_graft_copy) {
597 if ($_use_lib) {
598 graft_file_copy_lib($grafts,$l_map,$u);
599 } else {
600 graft_file_copy_cmd($grafts,$l_map,$u);
605 write_grafts($grafts, $comments, $gr_file);
606 unlink "$gr_file~$gr_sha1" if $gr_sha1;
609 sub multi_init {
610 my $url = shift;
611 $_trunk ||= 'trunk';
612 $_trunk =~ s#/+$##;
613 $url =~ s#/+$## if $url;
614 if ($_trunk !~ m#^[a-z\+]+://#) {
615 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
616 unless ($url) {
617 print STDERR "E: '$_trunk' is not a complete URL ",
618 "and a separate URL is not specified\n";
619 exit 1;
621 $_trunk = $url . $_trunk;
623 if ($GIT_SVN eq 'git-svn') {
624 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
625 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
627 init_vars();
628 init($_trunk);
629 complete_url_ls_init($url, $_branches, '--branches/-b', '');
630 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
633 sub multi_fetch {
634 # try to do trunk first, since branches/tags
635 # may be descended from it.
636 if (-d "$GIT_DIR/svn/trunk") {
637 print "Fetching trunk\n";
638 defined(my $pid = fork) or croak $!;
639 if (!$pid) {
640 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
641 init_vars();
642 fetch(@_);
643 exit 0;
645 waitpid $pid, 0;
646 croak $? if $?;
648 rec_fetch('', "$GIT_DIR/svn", @_);
651 sub show_log {
652 my (@args) = @_;
653 my ($r_min, $r_max);
654 my $r_last = -1; # prevent dupes
655 rload_authors() if $_authors;
656 if (defined $TZ) {
657 $ENV{TZ} = $TZ;
658 } else {
659 delete $ENV{TZ};
661 if (defined $_revision) {
662 if ($_revision =~ /^(\d+):(\d+)$/) {
663 ($r_min, $r_max) = ($1, $2);
664 } elsif ($_revision =~ /^\d+$/) {
665 $r_min = $r_max = $_revision;
666 } else {
667 print STDERR "-r$_revision is not supported, use ",
668 "standard \'git log\' arguments instead\n";
669 exit 1;
673 my $pid = open(my $log,'-|');
674 defined $pid or croak $!;
675 if (!$pid) {
676 my @rl = (qw/git-log --abbrev-commit --pretty=raw
677 --default/, "remotes/$GIT_SVN");
678 push @rl, '--raw' if $_verbose;
679 exec(@rl, @args) or croak $!;
681 setup_pager();
682 my (@k, $c, $d);
683 while (<$log>) {
684 if (/^commit ($sha1_short)/o) {
685 my $cmt = $1;
686 if ($c && defined $c->{r} && $c->{r} != $r_last) {
687 $r_last = $c->{r};
688 process_commit($c, $r_min, $r_max, \@k) or
689 goto out;
691 $d = undef;
692 $c = { c => $cmt };
693 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
694 get_author_info($c, $1, $2, $3);
695 } elsif (/^(?:tree|parent|committer) /) {
696 # ignore
697 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
698 push @{$c->{raw}}, $_;
699 } elsif (/^diff /) {
700 $d = 1;
701 push @{$c->{diff}}, $_;
702 } elsif ($d) {
703 push @{$c->{diff}}, $_;
704 } elsif (/^ (git-svn-id:.+)$/) {
705 my ($url, $rev, $uuid) = extract_metadata($1);
706 $c->{r} = $rev;
707 } elsif (s/^ //) {
708 push @{$c->{l}}, $_;
711 if ($c && defined $c->{r} && $c->{r} != $r_last) {
712 $r_last = $c->{r};
713 process_commit($c, $r_min, $r_max, \@k);
715 if (@k) {
716 my $swap = $r_max;
717 $r_max = $r_min;
718 $r_min = $swap;
719 process_commit($_, $r_min, $r_max) foreach reverse @k;
721 out:
722 close $log;
723 print '-' x72,"\n" unless $_incremental || $_oneline;
726 ########################### utility functions #########################
728 sub rec_fetch {
729 my ($pfx, $p, @args) = @_;
730 my @dir;
731 foreach (sort <$p/*>) {
732 if (-r "$_/info/url") {
733 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
734 my $id = $pfx . basename $_;
735 next if $id eq 'trunk';
736 print "Fetching $id\n";
737 defined(my $pid = fork) or croak $!;
738 if (!$pid) {
739 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
740 init_vars();
741 fetch(@args);
742 exit 0;
744 waitpid $pid, 0;
745 croak $? if $?;
746 } elsif (-d $_) {
747 push @dir, $_;
750 foreach (@dir) {
751 my $x = $_;
752 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
753 rec_fetch($x, $_);
757 sub complete_url_ls_init {
758 my ($url, $var, $switch, $pfx) = @_;
759 unless ($var) {
760 print STDERR "W: $switch not specified\n";
761 return;
763 $var =~ s#/+$##;
764 if ($var !~ m#^[a-z\+]+://#) {
765 $var = '/' . $var if ($var !~ m#^/#);
766 unless ($url) {
767 print STDERR "E: '$var' is not a complete URL ",
768 "and a separate URL is not specified\n";
769 exit 1;
771 $var = $url . $var;
773 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
774 : safe_qx(qw/svn ls --non-interactive/, $var));
775 my $old = $GIT_SVN;
776 defined(my $pid = fork) or croak $!;
777 if (!$pid) {
778 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
779 $u =~ s#/+$##;
780 if ($u !~ m!\Q$var\E/(.+)$!) {
781 print STDERR "W: Unrecognized URL: $u\n";
782 die "This should never happen\n";
784 my $id = $pfx.$1;
785 print "init $u => $id\n";
786 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
787 init_vars();
788 init($u);
790 exit 0;
792 waitpid $pid, 0;
793 croak $? if $?;
796 sub common_prefix {
797 my $paths = shift;
798 my %common;
799 foreach (@$paths) {
800 my @tmp = split m#/#, $_;
801 my $p = '';
802 while (my $x = shift @tmp) {
803 $p .= "/$x";
804 $common{$p} ||= 0;
805 $common{$p}++;
808 foreach (sort {length $b <=> length $a} keys %common) {
809 if ($common{$_} == @$paths) {
810 return $_;
813 return '';
816 # this isn't funky-filename safe, but good enough for now...
817 sub graft_file_copy_cmd {
818 my ($grafts, $l_map, $u) = @_;
819 my $paths = $l_map->{$u};
820 my $pfx = common_prefix([keys %$paths]);
821 $SVN_URL ||= $u.$pfx;
822 my $pid = open my $fh, '-|';
823 defined $pid or croak $!;
824 unless ($pid) {
825 my @exec = qw/svn log -v/;
826 push @exec, "-r$_revision" if defined $_revision;
827 exec @exec, $u.$pfx or croak $!;
829 my ($r, $mp) = (undef, undef);
830 while (<$fh>) {
831 chomp;
832 if (/^\-{72}$/) {
833 $mp = $r = undef;
834 } elsif (/^r(\d+) \| /) {
835 $r = $1 unless defined $r;
836 } elsif (/^Changed paths:/) {
837 $mp = 1;
838 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
839 my ($p1, $p0, $r0) = ($1, $2, $3);
840 my $c = find_graft_path_commit($paths, $p1, $r);
841 next unless $c;
842 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
847 sub graft_file_copy_lib {
848 my ($grafts, $l_map, $u) = @_;
849 my $tree_paths = $l_map->{$u};
850 my $pfx = common_prefix([keys %$tree_paths]);
851 my ($repo, $path) = repo_path_split($u.$pfx);
852 $SVN_LOG ||= libsvn_connect($repo);
853 $SVN ||= libsvn_connect($repo);
855 my ($base, $head) = libsvn_parse_revision();
856 my $inc = 1000;
857 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
858 my $eh = $SVN::Error::handler;
859 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
860 while (1) {
861 my $pool = SVN::Pool->new;
862 $SVN_LOG->get_log( "/$path", $min, $max, 0, 1, 1,
863 sub {
864 libsvn_graft_file_copies($grafts, $tree_paths,
865 $path, @_);
866 }, $pool);
867 $pool->clear;
868 last if ($max >= $head);
869 $min = $max + 1;
870 $max += $inc;
871 $max = $head if ($max > $head);
873 $SVN::Error::handler = $eh;
876 sub process_merge_msg_matches {
877 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
878 my (@strong, @weak);
879 foreach (@matches) {
880 # merging with ourselves is not interesting
881 next if $_ eq $p;
882 if ($l_map->{$u}->{$_}) {
883 push @strong, $_;
884 } else {
885 push @weak, $_;
888 foreach my $w (@weak) {
889 last if @strong;
890 # no exact match, use branch name as regexp.
891 my $re = qr/\Q$w\E/i;
892 foreach (keys %{$l_map->{$u}}) {
893 if (/$re/) {
894 push @strong, $_;
895 last;
898 last if @strong;
899 $w = basename($w);
900 $re = qr/\Q$w\E/i;
901 foreach (keys %{$l_map->{$u}}) {
902 if (/$re/) {
903 push @strong, $_;
904 last;
908 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
909 \s(?:[a-f\d\-]+)$/xsm);
910 unless (defined $rev) {
911 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
912 \@(?:[a-f\d\-]+)/xsm);
913 return unless defined $rev;
915 foreach my $m (@strong) {
916 my ($r0, $s0) = find_rev_before($rev, $m);
917 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
921 sub graft_merge_msg {
922 my ($grafts, $l_map, $u, $p, @re) = @_;
924 my $x = $l_map->{$u}->{$p};
925 my $rl = rev_list_raw($x);
926 while (my $c = next_rev_list_entry($rl)) {
927 foreach my $re (@re) {
928 my (@br) = ($c->{m} =~ /$re/g);
929 next unless @br;
930 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
935 sub read_uuid {
936 return if $SVN_UUID;
937 if ($_use_lib) {
938 my $pool = SVN::Pool->new;
939 $SVN_UUID = $SVN->get_uuid($pool);
940 $pool->clear;
941 } else {
942 my $info = shift || svn_info('.');
943 $SVN_UUID = $info->{'Repository UUID'} or
944 croak "Repository UUID unreadable\n";
946 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
949 sub quiet_run {
950 my $pid = fork;
951 defined $pid or croak $!;
952 if (!$pid) {
953 open my $null, '>', '/dev/null' or croak $!;
954 open STDERR, '>&', $null or croak $!;
955 open STDOUT, '>&', $null or croak $!;
956 exec @_ or croak $!;
958 waitpid $pid, 0;
959 return $?;
962 sub repo_path_split {
963 my $full_url = shift;
964 $full_url =~ s#/+$##;
966 foreach (@repo_path_split_cache) {
967 if ($full_url =~ s#$_##) {
968 my $u = $1;
969 $full_url =~ s#^/+##;
970 return ($u, $full_url);
974 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
975 $path =~ s#^/+##;
976 my @paths = split(m#/+#, $path);
978 if ($_use_lib) {
979 while (1) {
980 $SVN = libsvn_connect($url);
981 last if (defined $SVN &&
982 defined eval { $SVN->get_latest_revnum });
983 my $n = shift @paths || last;
984 $url .= "/$n";
986 } else {
987 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
988 my $n = shift @paths || last;
989 $url .= "/$n";
992 push @repo_path_split_cache, qr/^(\Q$url\E)/;
993 $path = join('/',@paths);
994 return ($url, $path);
997 sub setup_git_svn {
998 defined $SVN_URL or croak "SVN repository location required\n";
999 unless (-d $GIT_DIR) {
1000 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1002 mkpath([$GIT_SVN_DIR]);
1003 mkpath(["$GIT_SVN_DIR/info"]);
1004 open my $fh, '>>',$REVDB or croak $!;
1005 close $fh;
1006 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1010 sub assert_svn_wc_clean {
1011 return if $_use_lib;
1012 my ($svn_rev) = @_;
1013 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1014 my $lcr = svn_info('.')->{'Last Changed Rev'};
1015 if ($svn_rev != $lcr) {
1016 print STDERR "Checking for copy-tree ... ";
1017 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1018 "-r$lcr:$svn_rev")));
1019 if (@diff) {
1020 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1021 } else {
1022 print STDERR "OK!\n";
1025 my @status = grep(!/^Performing status on external/,(`svn status`));
1026 @status = grep(!/^\s*$/,@status);
1027 if (scalar @status) {
1028 print STDERR "Tree ($SVN_WC) is not clean:\n";
1029 print STDERR $_ foreach @status;
1030 croak;
1034 sub get_tree_from_treeish {
1035 my ($treeish) = @_;
1036 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1037 chomp(my $type = `git-cat-file -t $treeish`);
1038 my $expected;
1039 while ($type eq 'tag') {
1040 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1042 if ($type eq 'commit') {
1043 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1044 ($expected) = ($expected =~ /^tree ($sha1)$/);
1045 die "Unable to get tree from $treeish\n" unless $expected;
1046 } elsif ($type eq 'tree') {
1047 $expected = $treeish;
1048 } else {
1049 die "$treeish is a $type, expected tree, tag or commit\n";
1051 return $expected;
1054 sub assert_tree {
1055 return if $_use_lib;
1056 my ($treeish) = @_;
1057 my $expected = get_tree_from_treeish($treeish);
1059 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1060 if (-e $tmpindex) {
1061 unlink $tmpindex or croak $!;
1063 my $old_index = set_index($tmpindex);
1064 index_changes(1);
1065 chomp(my $tree = `git-write-tree`);
1066 restore_index($old_index);
1067 if ($tree ne $expected) {
1068 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1070 unlink $tmpindex;
1073 sub parse_diff_tree {
1074 my $diff_fh = shift;
1075 local $/ = "\0";
1076 my $state = 'meta';
1077 my @mods;
1078 while (<$diff_fh>) {
1079 chomp $_; # this gets rid of the trailing "\0"
1080 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1081 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1082 push @mods, { mode_a => $1, mode_b => $2,
1083 sha1_b => $3, chg => $4 };
1084 if ($4 =~ /^(?:C|R)$/) {
1085 $state = 'file_a';
1086 } else {
1087 $state = 'file_b';
1089 } elsif ($state eq 'file_a') {
1090 my $x = $mods[$#mods] or croak "Empty array\n";
1091 if ($x->{chg} !~ /^(?:C|R)$/) {
1092 croak "Error parsing $_, $x->{chg}\n";
1094 $x->{file_a} = $_;
1095 $state = 'file_b';
1096 } elsif ($state eq 'file_b') {
1097 my $x = $mods[$#mods] or croak "Empty array\n";
1098 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1099 croak "Error parsing $_, $x->{chg}\n";
1101 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1102 croak "Error parsing $_, $x->{chg}\n";
1104 $x->{file_b} = $_;
1105 $state = 'meta';
1106 } else {
1107 croak "Error parsing $_\n";
1110 close $diff_fh or croak $!;
1112 return \@mods;
1115 sub svn_check_prop_executable {
1116 my $m = shift;
1117 return if -l $m->{file_b};
1118 if ($m->{mode_b} =~ /755$/) {
1119 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1120 if ($m->{mode_a} !~ /755$/) {
1121 sys(qw(svn propset svn:executable 1), $m->{file_b});
1123 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1124 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1125 sys(qw(svn propdel svn:executable), $m->{file_b});
1126 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1127 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1131 sub svn_ensure_parent_path {
1132 my $dir_b = dirname(shift);
1133 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1134 mkpath([$dir_b]) unless (-d $dir_b);
1135 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1138 sub precommit_check {
1139 my $mods = shift;
1140 my (%rm_file, %rmdir_check, %added_check);
1142 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1143 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1144 if ($m->{chg} eq 'R') {
1145 if (-d $m->{file_b}) {
1146 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1148 # dir/$file => dir/file/$file
1149 my $dirname = dirname($m->{file_b});
1150 while ($dirname ne File::Spec->curdir) {
1151 if ($dirname ne $m->{file_a}) {
1152 $dirname = dirname($dirname);
1153 next;
1155 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1157 # baz/zzz => baz (baz is a file)
1158 $dirname = dirname($m->{file_a});
1159 while ($dirname ne File::Spec->curdir) {
1160 if ($dirname ne $m->{file_b}) {
1161 $dirname = dirname($dirname);
1162 next;
1164 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1167 if ($m->{chg} =~ /^(D|R)$/) {
1168 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1169 $rm_file{ $m->{$t} } = 1;
1170 my $dirname = dirname( $m->{$t} );
1171 my $basename = basename( $m->{$t} );
1172 $rmdir_check{$dirname}->{$basename} = 1;
1173 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1174 if (-d $m->{file_b}) {
1175 err_dir_to_file($m->{file_b});
1177 my $dirname = dirname( $m->{file_b} );
1178 my $basename = basename( $m->{file_b} );
1179 $added_check{$dirname}->{$basename} = 1;
1180 while ($dirname ne File::Spec->curdir) {
1181 if ($rm_file{$dirname}) {
1182 err_file_to_dir($m->{file_b});
1184 $dirname = dirname $dirname;
1188 return (\%rmdir_check, \%added_check);
1190 sub err_dir_to_file {
1191 my $file = shift;
1192 print STDERR "Node change from directory to file ",
1193 "is not supported by Subversion: ",$file,"\n";
1194 exit 1;
1196 sub err_file_to_dir {
1197 my $file = shift;
1198 print STDERR "Node change from file to directory ",
1199 "is not supported by Subversion: ",$file,"\n";
1200 exit 1;
1205 sub get_diff {
1206 my ($from, $treeish) = @_;
1207 assert_tree($from);
1208 print "diff-tree $from $treeish\n";
1209 my $pid = open my $diff_fh, '-|';
1210 defined $pid or croak $!;
1211 if ($pid == 0) {
1212 my @diff_tree = qw(git-diff-tree -z -r);
1213 if ($_cp_similarity) {
1214 push @diff_tree, "-C$_cp_similarity";
1215 } else {
1216 push @diff_tree, '-C';
1218 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1219 push @diff_tree, "-l$_l" if defined $_l;
1220 exec(@diff_tree, $from, $treeish) or croak $!;
1222 return parse_diff_tree($diff_fh);
1225 sub svn_checkout_tree {
1226 my ($from, $treeish) = @_;
1227 my $mods = get_diff($from->{commit}, $treeish);
1228 return $mods unless (scalar @$mods);
1229 my ($rm, $add) = precommit_check($mods);
1231 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1232 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1233 if ($m->{chg} eq 'C') {
1234 svn_ensure_parent_path( $m->{file_b} );
1235 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1236 apply_mod_line_blob($m);
1237 svn_check_prop_executable($m);
1238 } elsif ($m->{chg} eq 'D') {
1239 sys(qw(svn rm --force), $m->{file_b});
1240 } elsif ($m->{chg} eq 'R') {
1241 svn_ensure_parent_path( $m->{file_b} );
1242 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1243 apply_mod_line_blob($m);
1244 svn_check_prop_executable($m);
1245 } elsif ($m->{chg} eq 'M') {
1246 apply_mod_line_blob($m);
1247 svn_check_prop_executable($m);
1248 } elsif ($m->{chg} eq 'T') {
1249 sys(qw(svn rm --force),$m->{file_b});
1250 apply_mod_line_blob($m);
1251 sys(qw(svn add --force), $m->{file_b});
1252 svn_check_prop_executable($m);
1253 } elsif ($m->{chg} eq 'A') {
1254 svn_ensure_parent_path( $m->{file_b} );
1255 apply_mod_line_blob($m);
1256 sys(qw(svn add --force), $m->{file_b});
1257 svn_check_prop_executable($m);
1258 } else {
1259 croak "Invalid chg: $m->{chg}\n";
1263 assert_tree($treeish);
1264 if ($_rmdir) { # remove empty directories
1265 handle_rmdir($rm, $add);
1267 assert_tree($treeish);
1268 return $mods;
1271 sub libsvn_checkout_tree {
1272 my ($from, $treeish, $ed) = @_;
1273 my $mods = get_diff($from, $treeish);
1274 return $mods unless (scalar @$mods);
1275 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1276 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1277 my $f = $m->{chg};
1278 if (defined $o{$f}) {
1279 $ed->$f($m);
1280 } else {
1281 croak "Invalid change type: $f\n";
1284 $ed->rmdirs if $_rmdir;
1285 return $mods;
1288 # svn ls doesn't work with respect to the current working tree, but what's
1289 # in the repository. There's not even an option for it... *sigh*
1290 # (added files don't show up and removed files remain in the ls listing)
1291 sub svn_ls_current {
1292 my ($dir, $rm, $add) = @_;
1293 chomp(my @ls = safe_qx('svn','ls',$dir));
1294 my @ret = ();
1295 foreach (@ls) {
1296 s#/$##; # trailing slashes are evil
1297 push @ret, $_ unless $rm->{$dir}->{$_};
1299 if (exists $add->{$dir}) {
1300 push @ret, keys %{$add->{$dir}};
1302 return \@ret;
1305 sub handle_rmdir {
1306 my ($rm, $add) = @_;
1308 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1309 my $ls = svn_ls_current($dir, $rm, $add);
1310 next if (scalar @$ls);
1311 sys(qw(svn rm --force),$dir);
1313 my $dn = dirname $dir;
1314 $rm->{ $dn }->{ basename $dir } = 1;
1315 $ls = svn_ls_current($dn, $rm, $add);
1316 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1317 sys(qw(svn rm --force),$dn);
1318 $dir = basename $dn;
1319 $dn = dirname $dn;
1320 $rm->{ $dn }->{ $dir } = 1;
1321 $ls = svn_ls_current($dn, $rm, $add);
1326 sub get_commit_message {
1327 my ($commit, $commit_msg) = (@_);
1328 my %log_msg = ( msg => '' );
1329 open my $msg, '>', $commit_msg or croak $!;
1331 print "commit: $commit\n";
1332 chomp(my $type = `git-cat-file -t $commit`);
1333 if ($type eq 'commit') {
1334 my $pid = open my $msg_fh, '-|';
1335 defined $pid or croak $!;
1337 if ($pid == 0) {
1338 exec(qw(git-cat-file commit), $commit) or croak $!;
1340 my $in_msg = 0;
1341 while (<$msg_fh>) {
1342 if (!$in_msg) {
1343 $in_msg = 1 if (/^\s*$/);
1344 } elsif (/^git-svn-id: /) {
1345 # skip this, we regenerate the correct one
1346 # on re-fetch anyways
1347 } else {
1348 print $msg $_ or croak $!;
1351 close $msg_fh or croak $!;
1353 close $msg or croak $!;
1355 if ($_edit || ($type eq 'tree')) {
1356 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1357 system($editor, $commit_msg);
1360 # file_to_s removes all trailing newlines, so just use chomp() here:
1361 open $msg, '<', $commit_msg or croak $!;
1362 { local $/; chomp($log_msg{msg} = <$msg>); }
1363 close $msg or croak $!;
1365 return \%log_msg;
1368 sub svn_commit_tree {
1369 my ($last, $commit) = @_;
1370 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1371 my $log_msg = get_commit_message($commit, $commit_msg);
1372 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1373 print "Committing $commit: $oneline\n";
1375 if (defined $LC_ALL) {
1376 $ENV{LC_ALL} = $LC_ALL;
1377 } else {
1378 delete $ENV{LC_ALL};
1380 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1381 $ENV{LC_ALL} = 'C';
1382 unlink $commit_msg;
1383 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1384 if (!defined $committed) {
1385 my $out = join("\n",@ci_output);
1386 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1387 $out, "\n\nAssuming English locale...";
1388 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1389 defined $committed or die " FAILED!\n",
1390 "Commit output failed to parse committed revision!\n",
1391 print STDERR " OK\n";
1394 my @svn_up = qw(svn up);
1395 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1396 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1397 push @svn_up, "-r$committed";
1398 sys(@svn_up);
1399 my $info = svn_info('.');
1400 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1401 if ($info->{'Last Changed Rev'} != $committed) {
1402 croak "$info->{'Last Changed Rev'} != $committed\n"
1404 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1405 /(\d{4})\-(\d\d)\-(\d\d)\s
1406 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1407 or croak "Failed to parse date: $date\n";
1408 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1409 $log_msg->{author} = $info->{'Last Changed Author'};
1410 $log_msg->{revision} = $committed;
1411 $log_msg->{msg} .= "\n";
1412 $log_msg->{parents} = [ $last->{commit} ];
1413 $log_msg->{commit} = git_commit($log_msg, $commit);
1414 return $log_msg;
1416 # resync immediately
1417 push @svn_up, "-r$last->{revision}";
1418 sys(@svn_up);
1419 return fetch("$committed=$commit");
1422 sub rev_list_raw {
1423 my (@args) = @_;
1424 my $pid = open my $fh, '-|';
1425 defined $pid or croak $!;
1426 if (!$pid) {
1427 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1429 return { fh => $fh, t => { } };
1432 sub next_rev_list_entry {
1433 my $rl = shift;
1434 my $fh = $rl->{fh};
1435 my $x = $rl->{t};
1436 while (<$fh>) {
1437 if (/^commit ($sha1)$/o) {
1438 if ($x->{c}) {
1439 $rl->{t} = { c => $1 };
1440 return $x;
1441 } else {
1442 $x->{c} = $1;
1444 } elsif (/^parent ($sha1)$/o) {
1445 $x->{p}->{$1} = 1;
1446 } elsif (s/^ //) {
1447 $x->{m} ||= '';
1448 $x->{m} .= $_;
1451 return ($x != $rl->{t}) ? $x : undef;
1454 # read the entire log into a temporary file (which is removed ASAP)
1455 # and store the file handle + parser state
1456 sub svn_log_raw {
1457 my (@log_args) = @_;
1458 my $log_fh = IO::File->new_tmpfile or croak $!;
1459 my $pid = fork;
1460 defined $pid or croak $!;
1461 if (!$pid) {
1462 open STDOUT, '>&', $log_fh or croak $!;
1463 exec (qw(svn log), @log_args) or croak $!
1465 waitpid $pid, 0;
1466 croak $? if $?;
1467 seek $log_fh, 0, 0 or croak $!;
1468 return { state => 'sep', fh => $log_fh };
1471 sub next_log_entry {
1472 my $log = shift; # retval of svn_log_raw()
1473 my $ret = undef;
1474 my $fh = $log->{fh};
1476 while (<$fh>) {
1477 chomp;
1478 if (/^\-{72}$/) {
1479 if ($log->{state} eq 'msg') {
1480 if ($ret->{lines}) {
1481 $ret->{msg} .= $_."\n";
1482 unless(--$ret->{lines}) {
1483 $log->{state} = 'sep';
1485 } else {
1486 croak "Log parse error at: $_\n",
1487 $ret->{revision},
1488 "\n";
1490 next;
1492 if ($log->{state} ne 'sep') {
1493 croak "Log parse error at: $_\n",
1494 "state: $log->{state}\n",
1495 $ret->{revision},
1496 "\n";
1498 $log->{state} = 'rev';
1500 # if we have an empty log message, put something there:
1501 if ($ret) {
1502 $ret->{msg} ||= "\n";
1503 delete $ret->{lines};
1504 return $ret;
1506 next;
1508 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1509 my $rev = $1;
1510 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1511 ($lines) = ($lines =~ /(\d+)/);
1512 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1513 /(\d{4})\-(\d\d)\-(\d\d)\s
1514 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1515 or croak "Failed to parse date: $date\n";
1516 $ret = { revision => $rev,
1517 date => "$tz $Y-$m-$d $H:$M:$S",
1518 author => $author,
1519 lines => $lines,
1520 msg => '' };
1521 if (defined $_authors && ! defined $users{$author}) {
1522 die "Author: $author not defined in ",
1523 "$_authors file\n";
1525 $log->{state} = 'msg_start';
1526 next;
1528 # skip the first blank line of the message:
1529 if ($log->{state} eq 'msg_start' && /^$/) {
1530 $log->{state} = 'msg';
1531 } elsif ($log->{state} eq 'msg') {
1532 if ($ret->{lines}) {
1533 $ret->{msg} .= $_."\n";
1534 unless (--$ret->{lines}) {
1535 $log->{state} = 'sep';
1537 } else {
1538 croak "Log parse error at: $_\n",
1539 $ret->{revision},"\n";
1543 return $ret;
1546 sub svn_info {
1547 my $url = shift || $SVN_URL;
1549 my $pid = open my $info_fh, '-|';
1550 defined $pid or croak $!;
1552 if ($pid == 0) {
1553 exec(qw(svn info),$url) or croak $!;
1556 my $ret = {};
1557 # only single-lines seem to exist in svn info output
1558 while (<$info_fh>) {
1559 chomp $_;
1560 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1561 $ret->{$1} = $2;
1562 push @{$ret->{-order}}, $1;
1565 close $info_fh or croak $!;
1566 return $ret;
1569 sub sys { system(@_) == 0 or croak $? }
1571 sub eol_cp {
1572 my ($from, $to) = @_;
1573 my $es = svn_propget_base('svn:eol-style', $to);
1574 open my $rfd, '<', $from or croak $!;
1575 binmode $rfd or croak $!;
1576 open my $wfd, '>', $to or croak $!;
1577 binmode $wfd or croak $!;
1578 eol_cp_fd($rfd, $wfd, $es);
1579 close $rfd or croak $!;
1580 close $wfd or croak $!;
1583 sub eol_cp_fd {
1584 my ($rfd, $wfd, $es) = @_;
1585 my $eol = defined $es ? $EOL{$es} : undef;
1586 my $buf;
1587 use bytes;
1588 while (1) {
1589 my ($r, $w, $t);
1590 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1591 return unless $r;
1592 if ($eol) {
1593 if ($buf =~ /\015$/) {
1594 my $c;
1595 defined($r = sysread($rfd,$c,1)) or croak $!;
1596 $buf .= $c if $r > 0;
1598 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1599 $r = length($buf);
1601 for ($w = 0; $w < $r; $w += $t) {
1602 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1605 no bytes;
1608 sub do_update_index {
1609 my ($z_cmd, $cmd, $no_text_base) = @_;
1611 my $z = open my $p, '-|';
1612 defined $z or croak $!;
1613 unless ($z) { exec @$z_cmd or croak $! }
1615 my $pid = open my $ui, '|-';
1616 defined $pid or croak $!;
1617 unless ($pid) {
1618 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1620 local $/ = "\0";
1621 while (my $x = <$p>) {
1622 chomp $x;
1623 if (!$no_text_base && lstat $x && ! -l _ &&
1624 svn_propget_base('svn:keywords', $x)) {
1625 my $mode = -x _ ? 0755 : 0644;
1626 my ($v,$d,$f) = File::Spec->splitpath($x);
1627 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1628 'text-base',"$f.svn-base");
1629 $tb =~ s#^/##;
1630 unless (-f $tb) {
1631 $tb = File::Spec->catfile($d, '.svn',
1632 'text-base',"$f.svn-base");
1633 $tb =~ s#^/##;
1635 unlink $x or croak $!;
1636 eol_cp($tb, $x);
1637 chmod(($mode &~ umask), $x) or croak $!;
1639 print $ui $x,"\0";
1641 close $ui or croak $!;
1644 sub index_changes {
1645 return if $_use_lib;
1647 if (!-f "$GIT_SVN_DIR/info/exclude") {
1648 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1649 print $fd '.svn',"\n";
1650 close $fd or croak $!;
1652 my $no_text_base = shift;
1653 do_update_index([qw/git-diff-files --name-only -z/],
1654 'remove',
1655 $no_text_base);
1656 do_update_index([qw/git-ls-files -z --others/,
1657 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1658 'add',
1659 $no_text_base);
1662 sub s_to_file {
1663 my ($str, $file, $mode) = @_;
1664 open my $fd,'>',$file or croak $!;
1665 print $fd $str,"\n" or croak $!;
1666 close $fd or croak $!;
1667 chmod ($mode &~ umask, $file) if (defined $mode);
1670 sub file_to_s {
1671 my $file = shift;
1672 open my $fd,'<',$file or croak "$!: file: $file\n";
1673 local $/;
1674 my $ret = <$fd>;
1675 close $fd or croak $!;
1676 $ret =~ s/\s*$//s;
1677 return $ret;
1680 sub assert_revision_unknown {
1681 my $r = shift;
1682 if (my $c = revdb_get($REVDB, $r)) {
1683 croak "$r = $c already exists! Why are we refetching it?";
1687 sub trees_eq {
1688 my ($x, $y) = @_;
1689 my @x = safe_qx('git-cat-file','commit',$x);
1690 my @y = safe_qx('git-cat-file','commit',$y);
1691 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1692 || $y[0] !~ /^tree $sha1\n$/) {
1693 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1694 return 0
1696 return 1;
1699 sub git_commit {
1700 my ($log_msg, @parents) = @_;
1701 assert_revision_unknown($log_msg->{revision});
1702 map_tree_joins() if (@_branch_from && !%tree_map);
1704 my (@tmp_parents, @exec_parents, %seen_parent);
1705 if (my $lparents = $log_msg->{parents}) {
1706 @tmp_parents = @$lparents
1708 # commit parents can be conditionally bound to a particular
1709 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1710 foreach my $p (@parents) {
1711 next unless defined $p;
1712 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1713 if ($1 == $log_msg->{revision}) {
1714 push @tmp_parents, $2;
1716 } else {
1717 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1720 my $tree = $log_msg->{tree};
1721 if (!defined $tree) {
1722 my $index = set_index($GIT_SVN_INDEX);
1723 index_changes();
1724 chomp($tree = `git-write-tree`);
1725 croak $? if $?;
1726 restore_index($index);
1728 if (exists $tree_map{$tree}) {
1729 push @tmp_parents, @{$tree_map{$tree}};
1731 foreach (@tmp_parents) {
1732 next if $seen_parent{$_};
1733 $seen_parent{$_} = 1;
1734 push @exec_parents, $_;
1735 # MAXPARENT is defined to 16 in commit-tree.c:
1736 last if @exec_parents > 16;
1739 defined(my $pid = open my $out_fh, '-|') or croak $!;
1740 if ($pid == 0) {
1741 my $msg_fh = IO::File->new_tmpfile or croak $!;
1742 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1743 "$SVN_URL\@$log_msg->{revision}",
1744 " $SVN_UUID\n" or croak $!;
1745 $msg_fh->flush == 0 or croak $!;
1746 seek $msg_fh, 0, 0 or croak $!;
1747 set_commit_env($log_msg);
1748 my @exec = ('git-commit-tree',$tree);
1749 push @exec, '-p', $_ foreach @exec_parents;
1750 open STDIN, '<&', $msg_fh or croak $!;
1751 exec @exec or croak $!;
1753 chomp(my $commit = do { local $/; <$out_fh> });
1754 close $out_fh or croak $?;
1755 if ($commit !~ /^$sha1$/o) {
1756 croak "Failed to commit, invalid sha1: $commit\n";
1758 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1759 if (my $primary_parent = shift @exec_parents) {
1760 quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1761 push @update_ref, $primary_parent unless $?;
1763 sys(@update_ref);
1764 revdb_set($REVDB, $log_msg->{revision}, $commit);
1766 # this output is read via pipe, do not change:
1767 print "r$log_msg->{revision} = $commit\n";
1768 if ($_repack && (--$_repack_nr == 0)) {
1769 $_repack_nr = $_repack;
1770 sys("git repack $_repack_flags");
1772 return $commit;
1775 sub set_commit_env {
1776 my ($log_msg) = @_;
1777 my $author = $log_msg->{author};
1778 if (!defined $author || length $author == 0) {
1779 $author = '(no author)';
1781 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1782 : ($author,"$author\@$SVN_UUID");
1783 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1784 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1785 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1788 sub apply_mod_line_blob {
1789 my $m = shift;
1790 if ($m->{mode_b} =~ /^120/) {
1791 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1792 } else {
1793 blob_to_file($m->{sha1_b}, $m->{file_b});
1797 sub blob_to_symlink {
1798 my ($blob, $link) = @_;
1799 defined $link or croak "\$link not defined!\n";
1800 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1801 if (-l $link || -f _) {
1802 unlink $link or croak $!;
1805 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1806 symlink $dest, $link or croak $!;
1809 sub blob_to_file {
1810 my ($blob, $file) = @_;
1811 defined $file or croak "\$file not defined!\n";
1812 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1813 if (-l $file || -f _) {
1814 unlink $file or croak $!;
1817 open my $blob_fh, '>', $file or croak "$!: $file\n";
1818 my $pid = fork;
1819 defined $pid or croak $!;
1821 if ($pid == 0) {
1822 open STDOUT, '>&', $blob_fh or croak $!;
1823 exec('git-cat-file','blob',$blob) or croak $!;
1825 waitpid $pid, 0;
1826 croak $? if $?;
1828 close $blob_fh or croak $!;
1831 sub safe_qx {
1832 my $pid = open my $child, '-|';
1833 defined $pid or croak $!;
1834 if ($pid == 0) {
1835 exec(@_) or croak $!;
1837 my @ret = (<$child>);
1838 close $child or croak $?;
1839 die $? if $?; # just in case close didn't error out
1840 return wantarray ? @ret : join('',@ret);
1843 sub svn_compat_check {
1844 my @co_help = safe_qx(qw(svn co -h));
1845 unless (grep /ignore-externals/,@co_help) {
1846 print STDERR "W: Installed svn version does not support ",
1847 "--ignore-externals\n";
1848 $_no_ignore_ext = 1;
1850 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1851 $_svn_co_url_revs = 1;
1853 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1854 $_svn_pg_peg_revs = 1;
1857 # I really, really hope nobody hits this...
1858 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1859 print STDERR <<'';
1860 W: The installed svn version does not support the --stop-on-copy flag in
1861 the log command.
1862 Lets hope the directory you're tracking is not a branch or tag
1863 and was never moved within the repository...
1865 $_no_stop_copy = 1;
1869 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1870 # (and they won't honor URL@<rev> without -r<rev>, too!)
1871 sub svn_cmd_checkout {
1872 my ($url, $rev, $dir) = @_;
1873 my @cmd = ('svn','co', "-r$rev");
1874 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1875 $url .= "\@$rev" if $_svn_co_url_revs;
1876 sys(@cmd, $url, $dir);
1879 sub check_upgrade_needed {
1880 my $old = eval {
1881 my $pid = open my $child, '-|';
1882 defined $pid or croak $!;
1883 if ($pid == 0) {
1884 close STDERR;
1885 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1887 my @ret = (<$child>);
1888 close $child or croak $?;
1889 die $? if $?; # just in case close didn't error out
1890 return wantarray ? @ret : join('',@ret);
1892 return unless $old;
1893 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1894 if ($@ || !$head) {
1895 print STDERR "Please run: $0 rebuild --upgrade\n";
1896 exit 1;
1900 # fills %tree_map with a reverse mapping of trees to commits. Useful
1901 # for finding parents to commit on.
1902 sub map_tree_joins {
1903 my %seen;
1904 foreach my $br (@_branch_from) {
1905 my $pid = open my $pipe, '-|';
1906 defined $pid or croak $!;
1907 if ($pid == 0) {
1908 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1909 or croak $!;
1911 while (<$pipe>) {
1912 if (/^commit ($sha1)$/o) {
1913 my $commit = $1;
1915 # if we've seen a commit,
1916 # we've seen its parents
1917 last if $seen{$commit};
1918 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1919 unless (defined $tree) {
1920 die "Failed to parse commit $commit\n";
1922 push @{$tree_map{$tree}}, $commit;
1923 $seen{$commit} = 1;
1926 close $pipe; # we could be breaking the pipe early
1930 sub load_all_refs {
1931 if (@_branch_from) {
1932 print STDERR '--branch|-b parameters are ignored when ',
1933 "--branch-all-refs|-B is passed\n";
1936 # don't worry about rev-list on non-commit objects/tags,
1937 # it shouldn't blow up if a ref is a blob or tree...
1938 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1941 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1942 sub load_authors {
1943 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1944 while (<$authors>) {
1945 chomp;
1946 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1947 my ($user, $name, $email) = ($1, $2, $3);
1948 $users{$user} = [$name, $email];
1950 close $authors or croak $!;
1953 sub rload_authors {
1954 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1955 while (<$authors>) {
1956 chomp;
1957 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1958 my ($user, $name, $email) = ($1, $2, $3);
1959 $rusers{"$name <$email>"} = $user;
1961 close $authors or croak $!;
1964 sub svn_propget_base {
1965 my ($p, $f) = @_;
1966 $f .= '@BASE' if $_svn_pg_peg_revs;
1967 return safe_qx(qw/svn propget/, $p, $f);
1970 sub git_svn_each {
1971 my $sub = shift;
1972 foreach (`git-rev-parse --symbolic --all`) {
1973 next unless s#^refs/remotes/##;
1974 chomp $_;
1975 next unless -f "$GIT_DIR/svn/$_/info/url";
1976 &$sub($_);
1980 sub migrate_revdb {
1981 git_svn_each(sub {
1982 my $id = shift;
1983 defined(my $pid = fork) or croak $!;
1984 if (!$pid) {
1985 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1986 init_vars();
1987 exit 0 if -r $REVDB;
1988 print "Upgrading svn => git mapping...\n";
1989 open my $fh, '>>',$REVDB or croak $!;
1990 close $fh;
1991 rebuild();
1992 print "Done upgrading. You may now delete the ",
1993 "deprecated $GIT_SVN_DIR/revs directory\n";
1994 exit 0;
1996 waitpid $pid, 0;
1997 croak $? if $?;
2001 sub migration_check {
2002 migrate_revdb() unless (-e $REVDB);
2003 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2004 print "Upgrading repository...\n";
2005 unless (-d "$GIT_DIR/svn") {
2006 mkdir "$GIT_DIR/svn" or croak $!;
2008 print "Data from a previous version of git-svn exists, but\n\t",
2009 "$GIT_SVN_DIR\n\t(required for this version ",
2010 "($VERSION) of git-svn) does not.\n";
2012 foreach my $x (`git-rev-parse --symbolic --all`) {
2013 next unless $x =~ s#^refs/remotes/##;
2014 chomp $x;
2015 next unless -f "$GIT_DIR/$x/info/url";
2016 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2017 next unless $u;
2018 my $dn = dirname("$GIT_DIR/svn/$x");
2019 mkpath([$dn]) unless -d $dn;
2020 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2022 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2023 print "Done upgrading.\n";
2026 sub find_rev_before {
2027 my ($r, $id, $eq_ok) = @_;
2028 my $f = "$GIT_DIR/svn/$id/.rev_db";
2029 # --$r unless $eq_ok;
2030 while ($r > 0) {
2031 if (my $c = revdb_get($f, $r)) {
2032 return ($r, $c);
2034 --$r;
2036 return (undef, undef);
2039 sub init_vars {
2040 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2041 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2042 $REVDB = "$GIT_SVN_DIR/.rev_db";
2043 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2044 $SVN_URL = undef;
2045 $SVN_WC = "$GIT_SVN_DIR/tree";
2048 # convert GetOpt::Long specs for use by git-repo-config
2049 sub read_repo_config {
2050 return unless -d $GIT_DIR;
2051 my $opts = shift;
2052 foreach my $o (keys %$opts) {
2053 my $v = $opts->{$o};
2054 my ($key) = ($o =~ /^([a-z\-]+)/);
2055 $key =~ s/-//g;
2056 my $arg = 'git-repo-config';
2057 $arg .= ' --int' if ($o =~ /[:=]i$/);
2058 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2059 if (ref $v eq 'ARRAY') {
2060 chomp(my @tmp = `$arg --get-all svn.$key`);
2061 @$v = @tmp if @tmp;
2062 } else {
2063 chomp(my $tmp = `$arg --get svn.$key`);
2064 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2065 $$v = $tmp;
2071 sub set_default_vals {
2072 if (defined $_repack) {
2073 $_repack = 1000 if ($_repack <= 0);
2074 $_repack_nr = $_repack;
2075 $_repack_flags ||= '';
2079 sub read_grafts {
2080 my $gr_file = shift;
2081 my ($grafts, $comments) = ({}, {});
2082 if (open my $fh, '<', $gr_file) {
2083 my @tmp;
2084 while (<$fh>) {
2085 if (/^($sha1)\s+/) {
2086 my $c = $1;
2087 if (@tmp) {
2088 @{$comments->{$c}} = @tmp;
2089 @tmp = ();
2091 foreach my $p (split /\s+/, $_) {
2092 $grafts->{$c}->{$p} = 1;
2094 } else {
2095 push @tmp, $_;
2098 close $fh or croak $!;
2099 @{$comments->{'END'}} = @tmp if @tmp;
2101 return ($grafts, $comments);
2104 sub write_grafts {
2105 my ($grafts, $comments, $gr_file) = @_;
2107 open my $fh, '>', $gr_file or croak $!;
2108 foreach my $c (sort keys %$grafts) {
2109 if ($comments->{$c}) {
2110 print $fh $_ foreach @{$comments->{$c}};
2112 my $p = $grafts->{$c};
2113 delete $p->{$c}; # commits are not self-reproducing...
2114 my $pid = open my $ch, '-|';
2115 defined $pid or croak $!;
2116 if (!$pid) {
2117 exec(qw/git-cat-file commit/, $c) or croak $!;
2119 while (<$ch>) {
2120 if (/^parent ([a-f\d]{40})/) {
2121 $p->{$1} = 1;
2122 } else {
2123 last unless /^\S/i;
2126 close $ch; # breaking the pipe
2127 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2129 if ($comments->{'END'}) {
2130 print $fh $_ foreach @{$comments->{'END'}};
2132 close $fh or croak $!;
2135 sub read_url_paths {
2136 my $l_map = {};
2137 git_svn_each(sub { my $x = shift;
2138 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2139 my ($u, $p) = repo_path_split($url);
2140 $l_map->{$u}->{$p} = $x;
2142 return $l_map;
2145 sub extract_metadata {
2146 my $id = shift;
2147 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2148 \s([a-f\d\-]+)$/x);
2149 if (!$rev || !$uuid || !$url) {
2150 # some of the original repositories I made had
2151 # indentifiers like this:
2152 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2154 return ($url, $rev, $uuid);
2157 sub tz_to_s_offset {
2158 my ($tz) = @_;
2159 $tz =~ s/(\d\d)$//;
2160 return ($1 * 60) + ($tz * 3600);
2163 sub setup_pager { # translated to Perl from pager.c
2164 return unless (-t *STDOUT);
2165 my $pager = $ENV{PAGER};
2166 if (!defined $pager) {
2167 $pager = 'less';
2168 } elsif (length $pager == 0 || $pager eq 'cat') {
2169 return;
2171 pipe my $rfd, my $wfd or return;
2172 defined(my $pid = fork) or croak $!;
2173 if (!$pid) {
2174 open STDOUT, '>&', $wfd or croak $!;
2175 return;
2177 open STDIN, '<&', $rfd or croak $!;
2178 $ENV{LESS} ||= '-S';
2179 exec $pager or croak "Can't run pager: $!\n";;
2182 sub get_author_info {
2183 my ($dest, $author, $t, $tz) = @_;
2184 $author =~ s/(?:^\s*|\s*$)//g;
2185 my $_a;
2186 if ($_authors) {
2187 $_a = $rusers{$author} || undef;
2189 if (!$_a) {
2190 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2192 $dest->{t} = $t;
2193 $dest->{tz} = $tz;
2194 $dest->{a} = $_a;
2195 # Date::Parse isn't in the standard Perl distro :(
2196 if ($tz =~ s/^\+//) {
2197 $t += tz_to_s_offset($tz);
2198 } elsif ($tz =~ s/^\-//) {
2199 $t -= tz_to_s_offset($tz);
2201 $dest->{t_utc} = $t;
2204 sub process_commit {
2205 my ($c, $r_min, $r_max, $defer) = @_;
2206 if (defined $r_min && defined $r_max) {
2207 if ($r_min == $c->{r} && $r_min == $r_max) {
2208 show_commit($c);
2209 return 0;
2211 return 1 if $r_min == $r_max;
2212 if ($r_min < $r_max) {
2213 # we need to reverse the print order
2214 return 0 if (defined $_limit && --$_limit < 0);
2215 push @$defer, $c;
2216 return 1;
2218 if ($r_min != $r_max) {
2219 return 1 if ($r_min < $c->{r});
2220 return 1 if ($r_max > $c->{r});
2223 return 0 if (defined $_limit && --$_limit < 0);
2224 show_commit($c);
2225 return 1;
2228 sub show_commit {
2229 my $c = shift;
2230 if ($_oneline) {
2231 my $x = "\n";
2232 if (my $l = $c->{l}) {
2233 while ($l->[0] =~ /^\s*$/) { shift @$l }
2234 $x = $l->[0];
2236 $_l_fmt ||= 'A' . length($c->{r});
2237 print 'r',pack($_l_fmt, $c->{r}),' | ';
2238 print "$c->{c} | " if $_show_commit;
2239 print $x;
2240 } else {
2241 show_commit_normal($c);
2245 sub show_commit_normal {
2246 my ($c) = @_;
2247 print '-' x72, "\nr$c->{r} | ";
2248 print "$c->{c} | " if $_show_commit;
2249 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2250 localtime($c->{t_utc})), ' | ';
2251 my $nr_line = 0;
2253 if (my $l = $c->{l}) {
2254 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2255 pop @$l;
2257 $nr_line = scalar @$l;
2258 if (!$nr_line) {
2259 print "1 line\n\n\n";
2260 } else {
2261 if ($nr_line == 1) {
2262 $nr_line = '1 line';
2263 } else {
2264 $nr_line .= ' lines';
2266 print $nr_line, "\n\n";
2267 print $_ foreach @$l;
2269 } else {
2270 print "1 line\n\n";
2273 foreach my $x (qw/raw diff/) {
2274 if ($c->{$x}) {
2275 print "\n";
2276 print $_ foreach @{$c->{$x}}
2281 sub libsvn_load {
2282 return unless $_use_lib;
2283 $_use_lib = eval {
2284 require SVN::Core;
2285 if ($SVN::Core::VERSION lt '1.2.1') {
2286 die "Need SVN::Core 1.2.1 or better ",
2287 "(got $SVN::Core::VERSION) ",
2288 "Falling back to command-line svn\n";
2290 require SVN::Ra;
2291 require SVN::Delta;
2292 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2293 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2294 $SVN::Node::dir.$SVN::Node::unknown.
2295 $SVN::Node::none.$SVN::Node::file.
2296 $SVN::Node::dir.$SVN::Node::unknown;
2301 sub libsvn_connect {
2302 my ($url) = @_;
2303 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2304 SVN::Client::get_ssl_server_trust_file_provider(),
2305 SVN::Client::get_username_provider()]);
2306 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2307 return $s;
2310 sub libsvn_get_file {
2311 my ($gui, $f, $rev) = @_;
2312 my $p = $f;
2313 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2315 my $fd = IO::File->new_tmpfile or croak $!;
2316 my $pool = SVN::Pool->new;
2317 my ($r, $props) = $SVN->get_file($f, $rev, $fd, $pool);
2318 $pool->clear;
2319 $fd->flush == 0 or croak $!;
2320 seek $fd, 0, 0 or croak $!;
2321 if (my $es = $props->{'svn:eol-style'}) {
2322 my $new_fd = IO::File->new_tmpfile or croak $!;
2323 eol_cp_fd($fd, $new_fd, $es);
2324 close $fd or croak $!;
2325 $fd = $new_fd;
2326 seek $fd, 0, 0 or croak $!;
2327 $fd->flush == 0 or croak $!;
2329 my $mode = '100644';
2330 if (exists $props->{'svn:executable'}) {
2331 $mode = '100755';
2333 if (exists $props->{'svn:special'}) {
2334 $mode = '120000';
2335 local $/;
2336 my $link = <$fd>;
2337 $link =~ s/^link // or die "svn:special file with contents: <",
2338 $link, "> is not understood\n";
2339 seek $fd, 0, 0 or croak $!;
2340 truncate $fd, 0 or croak $!;
2341 print $fd $link or croak $!;
2342 seek $fd, 0, 0 or croak $!;
2343 $fd->flush == 0 or croak $!;
2345 my $pid = open my $ho, '-|';
2346 defined $pid or croak $!;
2347 if (!$pid) {
2348 open STDIN, '<&', $fd or croak $!;
2349 exec qw/git-hash-object -w --stdin/ or croak $!;
2351 chomp(my $hash = do { local $/; <$ho> });
2352 close $ho or croak $?;
2353 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2354 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2355 close $fd or croak $!;
2358 sub libsvn_log_entry {
2359 my ($rev, $author, $date, $msg, $parents) = @_;
2360 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2361 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2362 or die "Unable to parse date: $date\n";
2363 if (defined $_authors && ! defined $users{$author}) {
2364 die "Author: $author not defined in $_authors file\n";
2366 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2367 author => $author, msg => $msg."\n", parents => $parents || [] }
2370 sub process_rm {
2371 my ($gui, $last_commit, $f) = @_;
2372 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2373 # remove entire directories.
2374 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2375 defined(my $pid = open my $ls, '-|') or croak $!;
2376 if (!$pid) {
2377 exec(qw/git-ls-tree -r --name-only -z/,
2378 $last_commit,'--',$f) or croak $!;
2380 local $/ = "\0";
2381 while (<$ls>) {
2382 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2384 close $ls or croak $!;
2385 } else {
2386 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2390 sub libsvn_fetch {
2391 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2392 open my $gui, '| git-update-index -z --index-info' or croak $!;
2393 my @amr;
2394 foreach my $f (keys %$paths) {
2395 my $m = $paths->{$f}->action();
2396 $f =~ s#^/+##;
2397 if ($m =~ /^[DR]$/) {
2398 process_rm($gui, $last_commit, $f);
2399 next if $m eq 'D';
2400 # 'R' can be file replacements, too, right?
2402 my $pool = SVN::Pool->new;
2403 my $t = $SVN->check_path($f, $rev, $pool);
2404 if ($t == $SVN::Node::file) {
2405 if ($m =~ /^[AMR]$/) {
2406 push @amr, $f;
2407 } else {
2408 die "Unrecognized action: $m, ($f r$rev)\n";
2411 $pool->clear;
2413 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2414 close $gui or croak $!;
2415 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2418 sub svn_grab_base_rev {
2419 defined(my $pid = open my $fh, '-|') or croak $!;
2420 if (!$pid) {
2421 open my $null, '>', '/dev/null' or croak $!;
2422 open STDERR, '>&', $null or croak $!;
2423 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2424 or croak $!;
2426 chomp(my $c = do { local $/; <$fh> });
2427 close $fh;
2428 if (defined $c && length $c) {
2429 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2430 safe_qx(qw/git-cat-file commit/, $c)))[0]);
2431 return ($rev, $c);
2433 return (undef, undef);
2436 sub libsvn_parse_revision {
2437 my $base = shift;
2438 my $head = $SVN->get_latest_revnum();
2439 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2440 return ($base + 1, $head) if (defined $base);
2441 return (0, $head);
2443 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2444 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2445 if ($_revision =~ /^BASE:(\d+)$/) {
2446 return ($base + 1, $1) if (defined $base);
2447 return (0, $head);
2449 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2450 die "revision argument: $_revision not understood by git-svn\n",
2451 "Try using the command-line svn client instead\n";
2454 sub libsvn_traverse {
2455 my ($gui, $pfx, $path, $rev) = @_;
2456 my $cwd = "$pfx/$path";
2457 my $pool = SVN::Pool->new;
2458 $cwd =~ s#^/+##g;
2459 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2460 foreach my $d (keys %$dirent) {
2461 my $t = $dirent->{$d}->kind;
2462 if ($t == $SVN::Node::dir) {
2463 libsvn_traverse($gui, $cwd, $d, $rev);
2464 } elsif ($t == $SVN::Node::file) {
2465 libsvn_get_file($gui, "$cwd/$d", $rev);
2468 $pool->clear;
2471 sub libsvn_traverse_ignore {
2472 my ($fh, $path, $r) = @_;
2473 $path =~ s#^/+##g;
2474 my $pool = SVN::Pool->new;
2475 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2476 my $p = $path;
2477 $p =~ s#^\Q$SVN_PATH\E/?##;
2478 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2479 if (my $s = $props->{'svn:ignore'}) {
2480 $s =~ s/[\r\n]+/\n/g;
2481 chomp $s;
2482 if (length $p == 0) {
2483 $s =~ s#\n#\n/$p#g;
2484 print $fh "/$s\n";
2485 } else {
2486 $s =~ s#\n#\n/$p/#g;
2487 print $fh "/$p/$s\n";
2490 foreach (sort keys %$dirent) {
2491 next if $dirent->{$_}->kind != $SVN::Node::dir;
2492 libsvn_traverse_ignore($fh, "$path/$_", $r);
2494 $pool->clear;
2497 sub revisions_eq {
2498 my ($path, $r0, $r1) = @_;
2499 return 1 if $r0 == $r1;
2500 my $nr = 0;
2501 if ($_use_lib) {
2502 # should be OK to use Pool here (r1 - r0) should be small
2503 my $pool = SVN::Pool->new;
2504 $SVN->get_log("/$path", $r0, $r1, 0, 1, 1, sub {$nr++},$pool);
2505 $pool->clear;
2506 } else {
2507 my ($url, undef) = repo_path_split($SVN_URL);
2508 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2509 while (next_log_entry($svn_log)) { $nr++ }
2510 close $svn_log->{fh};
2512 return 0 if ($nr > 1);
2513 return 1;
2516 sub libsvn_find_parent_branch {
2517 return undef; # XXX this function is disabled atm (not tested enough)
2518 my ($paths, $rev, $author, $date, $msg) = @_;
2519 my $svn_path = '/'.$SVN_PATH;
2521 # look for a parent from another branch:
2522 foreach (keys %$paths) {
2523 next if ($_ ne $svn_path);
2524 my $i = $paths->{$_};
2525 my $branch_from = $i->copyfrom_path or next;
2526 my $r = $i->copyfrom_rev;
2527 print STDERR "Found possible branch point: ",
2528 "$branch_from => $svn_path, $r\n";
2529 $branch_from =~ s#^/##;
2530 my $l_map = read_url_paths();
2531 my $url = $SVN->{url};
2532 defined $l_map->{$url} or next;
2533 my $id = $l_map->{$url}->{$branch_from} or next;
2534 my ($r0, $parent) = find_rev_before($r,$id,1);
2535 if (defined $r0 && defined $parent &&
2536 revisions_eq($branch_from, $r0, $r)) {
2537 unlink $GIT_SVN_INDEX;
2538 print STDERR "Found branch parent: $parent\n";
2539 sys(qw/git-read-tree/, $parent);
2540 return libsvn_fetch($parent, $paths, $rev,
2541 $author, $date, $msg);
2542 } else {
2543 print STDERR
2544 "Nope, branch point not imported or unknown\n";
2547 return undef;
2550 sub libsvn_new_tree {
2551 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2552 return $log_entry;
2554 my ($paths, $rev, $author, $date, $msg) = @_;
2555 open my $gui, '| git-update-index -z --index-info' or croak $!;
2556 my $pool = SVN::Pool->new;
2557 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2558 $pool->clear;
2559 close $gui or croak $!;
2560 return libsvn_log_entry($rev, $author, $date, $msg);
2563 sub find_graft_path_commit {
2564 my ($tree_paths, $p1, $r1) = @_;
2565 foreach my $x (keys %$tree_paths) {
2566 next unless ($p1 =~ /^\Q$x\E/);
2567 my $i = $tree_paths->{$x};
2568 my ($r0, $parent) = find_rev_before($r1,$i,1);
2569 return $parent if (defined $r0 && $r0 == $r1);
2570 print STDERR "r$r1 of $i not imported\n";
2571 next;
2573 return undef;
2576 sub find_graft_path_parents {
2577 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2578 foreach my $x (keys %$tree_paths) {
2579 next unless ($p0 =~ /^\Q$x\E/);
2580 my $i = $tree_paths->{$x};
2581 my ($r, $parent) = find_rev_before($r0, $i, 1);
2582 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2583 $grafts->{$c}->{$parent} = 1;
2588 sub libsvn_graft_file_copies {
2589 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2590 foreach (keys %$paths) {
2591 my $i = $paths->{$_};
2592 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2593 $i->copyfrom_rev);
2594 next unless (defined $p0 && defined $r0);
2596 my $p1 = $_;
2597 $p1 =~ s#^/##;
2598 $p0 =~ s#^/##;
2599 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2600 next unless $c;
2601 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2605 sub set_index {
2606 my $old = $ENV{GIT_INDEX_FILE};
2607 $ENV{GIT_INDEX_FILE} = shift;
2608 return $old;
2611 sub restore_index {
2612 my ($old) = @_;
2613 if (defined $old) {
2614 $ENV{GIT_INDEX_FILE} = $old;
2615 } else {
2616 delete $ENV{GIT_INDEX_FILE};
2620 sub libsvn_commit_cb {
2621 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2622 if ($_optimize_commits && $rev == ($r_last + 1)) {
2623 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2624 $log->{tree} = get_tree_from_treeish($c);
2625 my $cmt = git_commit($log, $cmt_last, $c);
2626 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2627 if (@diff) {
2628 print STDERR "Trees differ: $cmt $c\n",
2629 join('',@diff),"\n";
2630 exit 1;
2632 } else {
2633 fetch_lib("$rev=$c");
2637 sub libsvn_ls_fullurl {
2638 my $fullurl = shift;
2639 my ($repo, $path) = repo_path_split($fullurl);
2640 $SVN ||= libsvn_connect($repo);
2641 my @ret;
2642 my $pool = SVN::Pool->new;
2643 my ($dirent, undef, undef) = $SVN->get_dir($path,
2644 $SVN->get_latest_revnum, $pool);
2645 foreach my $d (keys %$dirent) {
2646 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2647 push @ret, "$d/"; # add '/' for compat with cli svn
2650 $pool->clear;
2651 return @ret;
2655 sub libsvn_skip_unknown_revs {
2656 my $err = shift;
2657 my $errno = $err->apr_err();
2658 # Maybe the branch we're tracking didn't
2659 # exist when the repo started, so it's
2660 # not an error if it doesn't, just continue
2662 # Wonderfully consistent library, eh?
2663 # 160013 - svn:// and file://
2664 # 175002 - http(s)://
2665 # More codes may be discovered later...
2666 if ($errno == 175002 || $errno == 160013) {
2667 print STDERR "directory non-existent\n";
2668 return;
2670 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2673 # Tie::File seems to be prone to offset errors if revisions get sparse,
2674 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2675 # one of my favorite modules is out :< Next up would be one of the DBM
2676 # modules, but I'm not sure which is most portable... So I'll just
2677 # go with something that's plain-text, but still capable of
2678 # being randomly accessed. So here's my ultra-simple fixed-width
2679 # database. All records are 40 characters + "\n", so it's easy to seek
2680 # to a revision: (41 * rev) is the byte offset.
2681 # A record of 40 0s denotes an empty revision.
2682 # And yes, it's still pretty fast (faster than Tie::File).
2683 sub revdb_set {
2684 my ($file, $rev, $commit) = @_;
2685 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2686 open my $fh, '+<', $file or croak $!;
2687 my $offset = $rev * 41;
2688 # assume that append is the common case:
2689 seek $fh, 0, 2 or croak $!;
2690 my $pos = tell $fh;
2691 if ($pos < $offset) {
2692 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2694 seek $fh, $offset, 0 or croak $!;
2695 print $fh $commit,"\n";
2696 close $fh or croak $!;
2699 sub revdb_get {
2700 my ($file, $rev) = @_;
2701 my $ret;
2702 my $offset = $rev * 41;
2703 open my $fh, '<', $file or croak $!;
2704 seek $fh, $offset, 0;
2705 if (tell $fh == $offset) {
2706 $ret = readline $fh;
2707 if (defined $ret) {
2708 chomp $ret;
2709 $ret = undef if ($ret =~ /^0{40}$/);
2712 close $fh or croak $!;
2713 return $ret;
2716 package SVN::Git::Editor;
2717 use vars qw/@ISA/;
2718 use strict;
2719 use warnings;
2720 use Carp qw/croak/;
2721 use IO::File;
2723 sub new {
2724 my $class = shift;
2725 my $git_svn = shift;
2726 my $self = SVN::Delta::Editor->new(@_);
2727 bless $self, $class;
2728 foreach (qw/svn_path c r ra /) {
2729 die "$_ required!\n" unless (defined $git_svn->{$_});
2730 $self->{$_} = $git_svn->{$_};
2732 $self->{pool} = SVN::Pool->new;
2733 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2734 $self->{rm} = { };
2735 require Digest::MD5;
2736 return $self;
2739 sub split_path {
2740 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2743 sub repo_path {
2744 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2745 : $_[0]->{svn_path}
2748 sub url_path {
2749 my ($self, $path) = @_;
2750 $self->{ra}->{url} . '/' . $self->repo_path($path);
2753 sub rmdirs {
2754 my ($self) = @_;
2755 my $rm = $self->{rm};
2756 delete $rm->{''}; # we never delete the url we're tracking
2757 return unless %$rm;
2759 foreach (keys %$rm) {
2760 my @d = split m#/#, $_;
2761 my $c = shift @d;
2762 $rm->{$c} = 1;
2763 while (@d) {
2764 $c .= '/' . shift @d;
2765 $rm->{$c} = 1;
2768 delete $rm->{$self->{svn_path}};
2769 delete $rm->{''}; # we never delete the url we're tracking
2770 return unless %$rm;
2772 defined(my $pid = open my $fh,'-|') or croak $!;
2773 if (!$pid) {
2774 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2776 local $/ = "\0";
2777 while (<$fh>) {
2778 chomp;
2779 $_ = $self->{svn_path} . '/' . $_;
2780 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2781 delete $rm->{$dn};
2782 last unless %$rm;
2784 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2785 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2786 $self->close_directory($bat->{$d}, $p);
2787 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2788 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2789 delete $bat->{$d};
2793 sub open_or_add_dir {
2794 my ($self, $full_path, $baton) = @_;
2795 my $p = SVN::Pool->new;
2796 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2797 $p->clear;
2798 if ($t == $SVN::Node::none) {
2799 return $self->add_directory($full_path, $baton,
2800 undef, -1, $self->{pool});
2801 } elsif ($t == $SVN::Node::dir) {
2802 return $self->open_directory($full_path, $baton,
2803 $self->{r}, $self->{pool});
2805 print STDERR "$full_path already exists in repository at ",
2806 "r$self->{r} and it is not a directory (",
2807 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2808 exit 1;
2811 sub ensure_path {
2812 my ($self, $path) = @_;
2813 my $bat = $self->{bat};
2814 $path = $self->repo_path($path);
2815 return $bat->{''} unless (length $path);
2816 my @p = split m#/+#, $path;
2817 my $c = shift @p;
2818 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2819 while (@p) {
2820 my $c0 = $c;
2821 $c .= '/' . shift @p;
2822 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2824 return $bat->{$c};
2827 sub A {
2828 my ($self, $m) = @_;
2829 my ($dir, $file) = split_path($m->{file_b});
2830 my $pbat = $self->ensure_path($dir);
2831 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2832 undef, -1);
2833 $self->chg_file($fbat, $m);
2834 $self->close_file($fbat,undef,$self->{pool});
2837 sub C {
2838 my ($self, $m) = @_;
2839 my ($dir, $file) = split_path($m->{file_b});
2840 my $pbat = $self->ensure_path($dir);
2841 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2842 $self->url_path($m->{file_a}), $self->{r});
2843 $self->chg_file($fbat, $m);
2844 $self->close_file($fbat,undef,$self->{pool});
2847 sub delete_entry {
2848 my ($self, $path, $pbat) = @_;
2849 my $rpath = $self->repo_path($path);
2850 my ($dir, $file) = split_path($rpath);
2851 $self->{rm}->{$dir} = 1;
2852 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2855 sub R {
2856 my ($self, $m) = @_;
2857 my ($dir, $file) = split_path($m->{file_b});
2858 my $pbat = $self->ensure_path($dir);
2859 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2860 $self->url_path($m->{file_a}), $self->{r});
2861 $self->chg_file($fbat, $m);
2862 $self->close_file($fbat,undef,$self->{pool});
2864 ($dir, $file) = split_path($m->{file_a});
2865 $pbat = $self->ensure_path($dir);
2866 $self->delete_entry($m->{file_a}, $pbat);
2869 sub M {
2870 my ($self, $m) = @_;
2871 my ($dir, $file) = split_path($m->{file_b});
2872 my $pbat = $self->ensure_path($dir);
2873 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2874 $pbat,$self->{r},$self->{pool});
2875 $self->chg_file($fbat, $m);
2876 $self->close_file($fbat,undef,$self->{pool});
2879 sub T { shift->M(@_) }
2881 sub change_file_prop {
2882 my ($self, $fbat, $pname, $pval) = @_;
2883 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2886 sub chg_file {
2887 my ($self, $fbat, $m) = @_;
2888 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2889 $self->change_file_prop($fbat,'svn:executable','*');
2890 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2891 $self->change_file_prop($fbat,'svn:executable',undef);
2893 my $fh = IO::File->new_tmpfile or croak $!;
2894 if ($m->{mode_b} =~ /^120/) {
2895 print $fh 'link ' or croak $!;
2896 $self->change_file_prop($fbat,'svn:special','*');
2897 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2898 $self->change_file_prop($fbat,'svn:special',undef);
2900 defined(my $pid = fork) or croak $!;
2901 if (!$pid) {
2902 open STDOUT, '>&', $fh or croak $!;
2903 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2905 waitpid $pid, 0;
2906 croak $? if $?;
2907 $fh->flush == 0 or croak $!;
2908 seek $fh, 0, 0 or croak $!;
2910 my $md5 = Digest::MD5->new;
2911 $md5->addfile($fh) or croak $!;
2912 seek $fh, 0, 0 or croak $!;
2914 my $exp = $md5->hexdigest;
2915 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2916 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2917 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2919 close $fh or croak $!;
2922 sub D {
2923 my ($self, $m) = @_;
2924 my ($dir, $file) = split_path($m->{file_b});
2925 my $pbat = $self->ensure_path($dir);
2926 $self->delete_entry($m->{file_b}, $pbat);
2929 sub close_edit {
2930 my ($self) = @_;
2931 my ($p,$bat) = ($self->{pool}, $self->{bat});
2932 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2933 $self->close_directory($bat->{$_}, $p);
2935 $self->SUPER::close_edit($p);
2936 $p->clear;
2939 sub abort_edit {
2940 my ($self) = @_;
2941 $self->SUPER::abort_edit($self->{pool});
2942 $self->{pool}->clear;
2945 __END__
2947 Data structures:
2949 $svn_log hashref (as returned by svn_log_raw)
2951 fh => file handle of the log file,
2952 state => state of the log file parser (sep/msg/rev/msg_start...)
2955 $log_msg hashref as returned by next_log_entry($svn_log)
2957 msg => 'whitespace-formatted log entry
2958 ', # trailing newline is preserved
2959 revision => '8', # integer
2960 date => '2004-02-24T17:01:44.108345Z', # commit date
2961 author => 'committer name'
2965 @mods = array of diff-index line hashes, each element represents one line
2966 of diff-index output
2968 diff-index line ($m hash)
2970 mode_a => first column of diff-index output, no leading ':',
2971 mode_b => second column of diff-index output,
2972 sha1_b => sha1sum of the final blob,
2973 chg => change type [MCRADT],
2974 file_a => original file name of a file (iff chg is 'C' or 'R')
2975 file_b => new/current file name of a file (any chg)
2979 Notes:
2980 I don't trust the each() function on unless I created %hash myself
2981 because the internal iterator may not have started at base.