git-svn: make the $GIT_DIR/svn/*/revs directory obsolete
[git/jnareb-git.git] / contrib / git-svn / git-svn.perl
blob884969ebdd5ca3caf34e2b3c28bf86f44467f09f
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");
1008 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1009 print $fd '.svn',"\n";
1010 close $fd or croak $!;
1011 my ($url, $path) = repo_path_split($SVN_URL);
1012 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
1013 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
1016 sub assert_svn_wc_clean {
1017 return if $_use_lib;
1018 my ($svn_rev) = @_;
1019 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1020 my $lcr = svn_info('.')->{'Last Changed Rev'};
1021 if ($svn_rev != $lcr) {
1022 print STDERR "Checking for copy-tree ... ";
1023 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1024 "-r$lcr:$svn_rev")));
1025 if (@diff) {
1026 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1027 } else {
1028 print STDERR "OK!\n";
1031 my @status = grep(!/^Performing status on external/,(`svn status`));
1032 @status = grep(!/^\s*$/,@status);
1033 if (scalar @status) {
1034 print STDERR "Tree ($SVN_WC) is not clean:\n";
1035 print STDERR $_ foreach @status;
1036 croak;
1040 sub get_tree_from_treeish {
1041 my ($treeish) = @_;
1042 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1043 chomp(my $type = `git-cat-file -t $treeish`);
1044 my $expected;
1045 while ($type eq 'tag') {
1046 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1048 if ($type eq 'commit') {
1049 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1050 ($expected) = ($expected =~ /^tree ($sha1)$/);
1051 die "Unable to get tree from $treeish\n" unless $expected;
1052 } elsif ($type eq 'tree') {
1053 $expected = $treeish;
1054 } else {
1055 die "$treeish is a $type, expected tree, tag or commit\n";
1057 return $expected;
1060 sub assert_tree {
1061 return if $_use_lib;
1062 my ($treeish) = @_;
1063 my $expected = get_tree_from_treeish($treeish);
1065 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1066 if (-e $tmpindex) {
1067 unlink $tmpindex or croak $!;
1069 my $old_index = set_index($tmpindex);
1070 index_changes(1);
1071 chomp(my $tree = `git-write-tree`);
1072 restore_index($old_index);
1073 if ($tree ne $expected) {
1074 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1076 unlink $tmpindex;
1079 sub parse_diff_tree {
1080 my $diff_fh = shift;
1081 local $/ = "\0";
1082 my $state = 'meta';
1083 my @mods;
1084 while (<$diff_fh>) {
1085 chomp $_; # this gets rid of the trailing "\0"
1086 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1087 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1088 push @mods, { mode_a => $1, mode_b => $2,
1089 sha1_b => $3, chg => $4 };
1090 if ($4 =~ /^(?:C|R)$/) {
1091 $state = 'file_a';
1092 } else {
1093 $state = 'file_b';
1095 } elsif ($state eq 'file_a') {
1096 my $x = $mods[$#mods] or croak "Empty array\n";
1097 if ($x->{chg} !~ /^(?:C|R)$/) {
1098 croak "Error parsing $_, $x->{chg}\n";
1100 $x->{file_a} = $_;
1101 $state = 'file_b';
1102 } elsif ($state eq 'file_b') {
1103 my $x = $mods[$#mods] or croak "Empty array\n";
1104 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1105 croak "Error parsing $_, $x->{chg}\n";
1107 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1108 croak "Error parsing $_, $x->{chg}\n";
1110 $x->{file_b} = $_;
1111 $state = 'meta';
1112 } else {
1113 croak "Error parsing $_\n";
1116 close $diff_fh or croak $!;
1118 return \@mods;
1121 sub svn_check_prop_executable {
1122 my $m = shift;
1123 return if -l $m->{file_b};
1124 if ($m->{mode_b} =~ /755$/) {
1125 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1126 if ($m->{mode_a} !~ /755$/) {
1127 sys(qw(svn propset svn:executable 1), $m->{file_b});
1129 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1130 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1131 sys(qw(svn propdel svn:executable), $m->{file_b});
1132 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1133 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1137 sub svn_ensure_parent_path {
1138 my $dir_b = dirname(shift);
1139 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1140 mkpath([$dir_b]) unless (-d $dir_b);
1141 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1144 sub precommit_check {
1145 my $mods = shift;
1146 my (%rm_file, %rmdir_check, %added_check);
1148 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1149 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1150 if ($m->{chg} eq 'R') {
1151 if (-d $m->{file_b}) {
1152 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1154 # dir/$file => dir/file/$file
1155 my $dirname = dirname($m->{file_b});
1156 while ($dirname ne File::Spec->curdir) {
1157 if ($dirname ne $m->{file_a}) {
1158 $dirname = dirname($dirname);
1159 next;
1161 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1163 # baz/zzz => baz (baz is a file)
1164 $dirname = dirname($m->{file_a});
1165 while ($dirname ne File::Spec->curdir) {
1166 if ($dirname ne $m->{file_b}) {
1167 $dirname = dirname($dirname);
1168 next;
1170 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1173 if ($m->{chg} =~ /^(D|R)$/) {
1174 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1175 $rm_file{ $m->{$t} } = 1;
1176 my $dirname = dirname( $m->{$t} );
1177 my $basename = basename( $m->{$t} );
1178 $rmdir_check{$dirname}->{$basename} = 1;
1179 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1180 if (-d $m->{file_b}) {
1181 err_dir_to_file($m->{file_b});
1183 my $dirname = dirname( $m->{file_b} );
1184 my $basename = basename( $m->{file_b} );
1185 $added_check{$dirname}->{$basename} = 1;
1186 while ($dirname ne File::Spec->curdir) {
1187 if ($rm_file{$dirname}) {
1188 err_file_to_dir($m->{file_b});
1190 $dirname = dirname $dirname;
1194 return (\%rmdir_check, \%added_check);
1196 sub err_dir_to_file {
1197 my $file = shift;
1198 print STDERR "Node change from directory to file ",
1199 "is not supported by Subversion: ",$file,"\n";
1200 exit 1;
1202 sub err_file_to_dir {
1203 my $file = shift;
1204 print STDERR "Node change from file to directory ",
1205 "is not supported by Subversion: ",$file,"\n";
1206 exit 1;
1211 sub get_diff {
1212 my ($from, $treeish) = @_;
1213 assert_tree($from);
1214 print "diff-tree $from $treeish\n";
1215 my $pid = open my $diff_fh, '-|';
1216 defined $pid or croak $!;
1217 if ($pid == 0) {
1218 my @diff_tree = qw(git-diff-tree -z -r);
1219 if ($_cp_similarity) {
1220 push @diff_tree, "-C$_cp_similarity";
1221 } else {
1222 push @diff_tree, '-C';
1224 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1225 push @diff_tree, "-l$_l" if defined $_l;
1226 exec(@diff_tree, $from, $treeish) or croak $!;
1228 return parse_diff_tree($diff_fh);
1231 sub svn_checkout_tree {
1232 my ($from, $treeish) = @_;
1233 my $mods = get_diff($from->{commit}, $treeish);
1234 return $mods unless (scalar @$mods);
1235 my ($rm, $add) = precommit_check($mods);
1237 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1238 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1239 if ($m->{chg} eq 'C') {
1240 svn_ensure_parent_path( $m->{file_b} );
1241 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1242 apply_mod_line_blob($m);
1243 svn_check_prop_executable($m);
1244 } elsif ($m->{chg} eq 'D') {
1245 sys(qw(svn rm --force), $m->{file_b});
1246 } elsif ($m->{chg} eq 'R') {
1247 svn_ensure_parent_path( $m->{file_b} );
1248 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1249 apply_mod_line_blob($m);
1250 svn_check_prop_executable($m);
1251 } elsif ($m->{chg} eq 'M') {
1252 apply_mod_line_blob($m);
1253 svn_check_prop_executable($m);
1254 } elsif ($m->{chg} eq 'T') {
1255 sys(qw(svn rm --force),$m->{file_b});
1256 apply_mod_line_blob($m);
1257 sys(qw(svn add --force), $m->{file_b});
1258 svn_check_prop_executable($m);
1259 } elsif ($m->{chg} eq 'A') {
1260 svn_ensure_parent_path( $m->{file_b} );
1261 apply_mod_line_blob($m);
1262 sys(qw(svn add --force), $m->{file_b});
1263 svn_check_prop_executable($m);
1264 } else {
1265 croak "Invalid chg: $m->{chg}\n";
1269 assert_tree($treeish);
1270 if ($_rmdir) { # remove empty directories
1271 handle_rmdir($rm, $add);
1273 assert_tree($treeish);
1274 return $mods;
1277 sub libsvn_checkout_tree {
1278 my ($from, $treeish, $ed) = @_;
1279 my $mods = get_diff($from, $treeish);
1280 return $mods unless (scalar @$mods);
1281 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1282 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1283 my $f = $m->{chg};
1284 if (defined $o{$f}) {
1285 $ed->$f($m);
1286 } else {
1287 croak "Invalid change type: $f\n";
1290 $ed->rmdirs if $_rmdir;
1291 return $mods;
1294 # svn ls doesn't work with respect to the current working tree, but what's
1295 # in the repository. There's not even an option for it... *sigh*
1296 # (added files don't show up and removed files remain in the ls listing)
1297 sub svn_ls_current {
1298 my ($dir, $rm, $add) = @_;
1299 chomp(my @ls = safe_qx('svn','ls',$dir));
1300 my @ret = ();
1301 foreach (@ls) {
1302 s#/$##; # trailing slashes are evil
1303 push @ret, $_ unless $rm->{$dir}->{$_};
1305 if (exists $add->{$dir}) {
1306 push @ret, keys %{$add->{$dir}};
1308 return \@ret;
1311 sub handle_rmdir {
1312 my ($rm, $add) = @_;
1314 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1315 my $ls = svn_ls_current($dir, $rm, $add);
1316 next if (scalar @$ls);
1317 sys(qw(svn rm --force),$dir);
1319 my $dn = dirname $dir;
1320 $rm->{ $dn }->{ basename $dir } = 1;
1321 $ls = svn_ls_current($dn, $rm, $add);
1322 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1323 sys(qw(svn rm --force),$dn);
1324 $dir = basename $dn;
1325 $dn = dirname $dn;
1326 $rm->{ $dn }->{ $dir } = 1;
1327 $ls = svn_ls_current($dn, $rm, $add);
1332 sub get_commit_message {
1333 my ($commit, $commit_msg) = (@_);
1334 my %log_msg = ( msg => '' );
1335 open my $msg, '>', $commit_msg or croak $!;
1337 print "commit: $commit\n";
1338 chomp(my $type = `git-cat-file -t $commit`);
1339 if ($type eq 'commit') {
1340 my $pid = open my $msg_fh, '-|';
1341 defined $pid or croak $!;
1343 if ($pid == 0) {
1344 exec(qw(git-cat-file commit), $commit) or croak $!;
1346 my $in_msg = 0;
1347 while (<$msg_fh>) {
1348 if (!$in_msg) {
1349 $in_msg = 1 if (/^\s*$/);
1350 } elsif (/^git-svn-id: /) {
1351 # skip this, we regenerate the correct one
1352 # on re-fetch anyways
1353 } else {
1354 print $msg $_ or croak $!;
1357 close $msg_fh or croak $!;
1359 close $msg or croak $!;
1361 if ($_edit || ($type eq 'tree')) {
1362 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1363 system($editor, $commit_msg);
1366 # file_to_s removes all trailing newlines, so just use chomp() here:
1367 open $msg, '<', $commit_msg or croak $!;
1368 { local $/; chomp($log_msg{msg} = <$msg>); }
1369 close $msg or croak $!;
1371 return \%log_msg;
1374 sub svn_commit_tree {
1375 my ($last, $commit) = @_;
1376 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1377 my $log_msg = get_commit_message($commit, $commit_msg);
1378 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1379 print "Committing $commit: $oneline\n";
1381 if (defined $LC_ALL) {
1382 $ENV{LC_ALL} = $LC_ALL;
1383 } else {
1384 delete $ENV{LC_ALL};
1386 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1387 $ENV{LC_ALL} = 'C';
1388 unlink $commit_msg;
1389 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1390 if (!defined $committed) {
1391 my $out = join("\n",@ci_output);
1392 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1393 $out, "\n\nAssuming English locale...";
1394 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1395 defined $committed or die " FAILED!\n",
1396 "Commit output failed to parse committed revision!\n",
1397 print STDERR " OK\n";
1400 my @svn_up = qw(svn up);
1401 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1402 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1403 push @svn_up, "-r$committed";
1404 sys(@svn_up);
1405 my $info = svn_info('.');
1406 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1407 if ($info->{'Last Changed Rev'} != $committed) {
1408 croak "$info->{'Last Changed Rev'} != $committed\n"
1410 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1411 /(\d{4})\-(\d\d)\-(\d\d)\s
1412 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1413 or croak "Failed to parse date: $date\n";
1414 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1415 $log_msg->{author} = $info->{'Last Changed Author'};
1416 $log_msg->{revision} = $committed;
1417 $log_msg->{msg} .= "\n";
1418 $log_msg->{parents} = [ $last->{commit} ];
1419 $log_msg->{commit} = git_commit($log_msg, $commit);
1420 return $log_msg;
1422 # resync immediately
1423 push @svn_up, "-r$last->{revision}";
1424 sys(@svn_up);
1425 return fetch("$committed=$commit");
1428 sub rev_list_raw {
1429 my (@args) = @_;
1430 my $pid = open my $fh, '-|';
1431 defined $pid or croak $!;
1432 if (!$pid) {
1433 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1435 return { fh => $fh, t => { } };
1438 sub next_rev_list_entry {
1439 my $rl = shift;
1440 my $fh = $rl->{fh};
1441 my $x = $rl->{t};
1442 while (<$fh>) {
1443 if (/^commit ($sha1)$/o) {
1444 if ($x->{c}) {
1445 $rl->{t} = { c => $1 };
1446 return $x;
1447 } else {
1448 $x->{c} = $1;
1450 } elsif (/^parent ($sha1)$/o) {
1451 $x->{p}->{$1} = 1;
1452 } elsif (s/^ //) {
1453 $x->{m} ||= '';
1454 $x->{m} .= $_;
1457 return ($x != $rl->{t}) ? $x : undef;
1460 # read the entire log into a temporary file (which is removed ASAP)
1461 # and store the file handle + parser state
1462 sub svn_log_raw {
1463 my (@log_args) = @_;
1464 my $log_fh = IO::File->new_tmpfile or croak $!;
1465 my $pid = fork;
1466 defined $pid or croak $!;
1467 if (!$pid) {
1468 open STDOUT, '>&', $log_fh or croak $!;
1469 exec (qw(svn log), @log_args) or croak $!
1471 waitpid $pid, 0;
1472 croak $? if $?;
1473 seek $log_fh, 0, 0 or croak $!;
1474 return { state => 'sep', fh => $log_fh };
1477 sub next_log_entry {
1478 my $log = shift; # retval of svn_log_raw()
1479 my $ret = undef;
1480 my $fh = $log->{fh};
1482 while (<$fh>) {
1483 chomp;
1484 if (/^\-{72}$/) {
1485 if ($log->{state} eq 'msg') {
1486 if ($ret->{lines}) {
1487 $ret->{msg} .= $_."\n";
1488 unless(--$ret->{lines}) {
1489 $log->{state} = 'sep';
1491 } else {
1492 croak "Log parse error at: $_\n",
1493 $ret->{revision},
1494 "\n";
1496 next;
1498 if ($log->{state} ne 'sep') {
1499 croak "Log parse error at: $_\n",
1500 "state: $log->{state}\n",
1501 $ret->{revision},
1502 "\n";
1504 $log->{state} = 'rev';
1506 # if we have an empty log message, put something there:
1507 if ($ret) {
1508 $ret->{msg} ||= "\n";
1509 delete $ret->{lines};
1510 return $ret;
1512 next;
1514 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1515 my $rev = $1;
1516 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1517 ($lines) = ($lines =~ /(\d+)/);
1518 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1519 /(\d{4})\-(\d\d)\-(\d\d)\s
1520 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1521 or croak "Failed to parse date: $date\n";
1522 $ret = { revision => $rev,
1523 date => "$tz $Y-$m-$d $H:$M:$S",
1524 author => $author,
1525 lines => $lines,
1526 msg => '' };
1527 if (defined $_authors && ! defined $users{$author}) {
1528 die "Author: $author not defined in ",
1529 "$_authors file\n";
1531 $log->{state} = 'msg_start';
1532 next;
1534 # skip the first blank line of the message:
1535 if ($log->{state} eq 'msg_start' && /^$/) {
1536 $log->{state} = 'msg';
1537 } elsif ($log->{state} eq 'msg') {
1538 if ($ret->{lines}) {
1539 $ret->{msg} .= $_."\n";
1540 unless (--$ret->{lines}) {
1541 $log->{state} = 'sep';
1543 } else {
1544 croak "Log parse error at: $_\n",
1545 $ret->{revision},"\n";
1549 return $ret;
1552 sub svn_info {
1553 my $url = shift || $SVN_URL;
1555 my $pid = open my $info_fh, '-|';
1556 defined $pid or croak $!;
1558 if ($pid == 0) {
1559 exec(qw(svn info),$url) or croak $!;
1562 my $ret = {};
1563 # only single-lines seem to exist in svn info output
1564 while (<$info_fh>) {
1565 chomp $_;
1566 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1567 $ret->{$1} = $2;
1568 push @{$ret->{-order}}, $1;
1571 close $info_fh or croak $!;
1572 return $ret;
1575 sub sys { system(@_) == 0 or croak $? }
1577 sub eol_cp {
1578 my ($from, $to) = @_;
1579 my $es = svn_propget_base('svn:eol-style', $to);
1580 open my $rfd, '<', $from or croak $!;
1581 binmode $rfd or croak $!;
1582 open my $wfd, '>', $to or croak $!;
1583 binmode $wfd or croak $!;
1584 eol_cp_fd($rfd, $wfd, $es);
1585 close $rfd or croak $!;
1586 close $wfd or croak $!;
1589 sub eol_cp_fd {
1590 my ($rfd, $wfd, $es) = @_;
1591 my $eol = defined $es ? $EOL{$es} : undef;
1592 my $buf;
1593 use bytes;
1594 while (1) {
1595 my ($r, $w, $t);
1596 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1597 return unless $r;
1598 if ($eol) {
1599 if ($buf =~ /\015$/) {
1600 my $c;
1601 defined($r = sysread($rfd,$c,1)) or croak $!;
1602 $buf .= $c if $r > 0;
1604 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1605 $r = length($buf);
1607 for ($w = 0; $w < $r; $w += $t) {
1608 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1611 no bytes;
1614 sub do_update_index {
1615 my ($z_cmd, $cmd, $no_text_base) = @_;
1617 my $z = open my $p, '-|';
1618 defined $z or croak $!;
1619 unless ($z) { exec @$z_cmd or croak $! }
1621 my $pid = open my $ui, '|-';
1622 defined $pid or croak $!;
1623 unless ($pid) {
1624 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1626 local $/ = "\0";
1627 while (my $x = <$p>) {
1628 chomp $x;
1629 if (!$no_text_base && lstat $x && ! -l _ &&
1630 svn_propget_base('svn:keywords', $x)) {
1631 my $mode = -x _ ? 0755 : 0644;
1632 my ($v,$d,$f) = File::Spec->splitpath($x);
1633 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1634 'text-base',"$f.svn-base");
1635 $tb =~ s#^/##;
1636 unless (-f $tb) {
1637 $tb = File::Spec->catfile($d, '.svn',
1638 'text-base',"$f.svn-base");
1639 $tb =~ s#^/##;
1641 unlink $x or croak $!;
1642 eol_cp($tb, $x);
1643 chmod(($mode &~ umask), $x) or croak $!;
1645 print $ui $x,"\0";
1647 close $ui or croak $!;
1650 sub index_changes {
1651 return if $_use_lib;
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";
2021 my ($url, $path) = repo_path_split($u);
2022 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
2023 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
2025 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2026 print "Done upgrading.\n";
2029 sub find_rev_before {
2030 my ($r, $id, $eq_ok) = @_;
2031 my $f = "$GIT_DIR/svn/$id/.rev_db";
2032 # --$r unless $eq_ok;
2033 while ($r > 0) {
2034 if (my $c = revdb_get($f, $r)) {
2035 return ($r, $c);
2037 --$r;
2039 return (undef, undef);
2042 sub init_vars {
2043 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2044 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2045 $REVDB = "$GIT_SVN_DIR/.rev_db";
2046 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2047 $SVN_URL = undef;
2048 $SVN_WC = "$GIT_SVN_DIR/tree";
2051 # convert GetOpt::Long specs for use by git-repo-config
2052 sub read_repo_config {
2053 return unless -d $GIT_DIR;
2054 my $opts = shift;
2055 foreach my $o (keys %$opts) {
2056 my $v = $opts->{$o};
2057 my ($key) = ($o =~ /^([a-z\-]+)/);
2058 $key =~ s/-//g;
2059 my $arg = 'git-repo-config';
2060 $arg .= ' --int' if ($o =~ /[:=]i$/);
2061 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2062 if (ref $v eq 'ARRAY') {
2063 chomp(my @tmp = `$arg --get-all svn.$key`);
2064 @$v = @tmp if @tmp;
2065 } else {
2066 chomp(my $tmp = `$arg --get svn.$key`);
2067 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2068 $$v = $tmp;
2074 sub set_default_vals {
2075 if (defined $_repack) {
2076 $_repack = 1000 if ($_repack <= 0);
2077 $_repack_nr = $_repack;
2078 $_repack_flags ||= '';
2082 sub read_grafts {
2083 my $gr_file = shift;
2084 my ($grafts, $comments) = ({}, {});
2085 if (open my $fh, '<', $gr_file) {
2086 my @tmp;
2087 while (<$fh>) {
2088 if (/^($sha1)\s+/) {
2089 my $c = $1;
2090 if (@tmp) {
2091 @{$comments->{$c}} = @tmp;
2092 @tmp = ();
2094 foreach my $p (split /\s+/, $_) {
2095 $grafts->{$c}->{$p} = 1;
2097 } else {
2098 push @tmp, $_;
2101 close $fh or croak $!;
2102 @{$comments->{'END'}} = @tmp if @tmp;
2104 return ($grafts, $comments);
2107 sub write_grafts {
2108 my ($grafts, $comments, $gr_file) = @_;
2110 open my $fh, '>', $gr_file or croak $!;
2111 foreach my $c (sort keys %$grafts) {
2112 if ($comments->{$c}) {
2113 print $fh $_ foreach @{$comments->{$c}};
2115 my $p = $grafts->{$c};
2116 delete $p->{$c}; # commits are not self-reproducing...
2117 my $pid = open my $ch, '-|';
2118 defined $pid or croak $!;
2119 if (!$pid) {
2120 exec(qw/git-cat-file commit/, $c) or croak $!;
2122 while (<$ch>) {
2123 if (/^parent ([a-f\d]{40})/) {
2124 $p->{$1} = 1;
2125 } else {
2126 last unless /^\S/i;
2129 close $ch; # breaking the pipe
2130 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2132 if ($comments->{'END'}) {
2133 print $fh $_ foreach @{$comments->{'END'}};
2135 close $fh or croak $!;
2138 sub read_url_paths {
2139 my $l_map = {};
2140 git_svn_each(sub { my $x = shift;
2141 my $u = file_to_s("$GIT_DIR/svn/$x/info/repo_url");
2142 my $p = file_to_s("$GIT_DIR/svn/$x/info/repo_path");
2143 # we hate trailing slashes
2144 if ($u =~ s#(?:^\/+|\/+$)##g) {
2145 s_to_file($u,"$GIT_DIR/svn/$x/info/repo_url");
2147 if ($p =~ s#(?:^\/+|\/+$)##g) {
2148 s_to_file($p,"$GIT_DIR/svn/$x/info/repo_path");
2150 $l_map->{$u}->{$p} = $x;
2152 return $l_map;
2155 sub extract_metadata {
2156 my $id = shift;
2157 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2158 \s([a-f\d\-]+)$/x);
2159 if (!$rev || !$uuid || !$url) {
2160 # some of the original repositories I made had
2161 # indentifiers like this:
2162 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2164 return ($url, $rev, $uuid);
2167 sub tz_to_s_offset {
2168 my ($tz) = @_;
2169 $tz =~ s/(\d\d)$//;
2170 return ($1 * 60) + ($tz * 3600);
2173 sub setup_pager { # translated to Perl from pager.c
2174 return unless (-t *STDOUT);
2175 my $pager = $ENV{PAGER};
2176 if (!defined $pager) {
2177 $pager = 'less';
2178 } elsif (length $pager == 0 || $pager eq 'cat') {
2179 return;
2181 pipe my $rfd, my $wfd or return;
2182 defined(my $pid = fork) or croak $!;
2183 if (!$pid) {
2184 open STDOUT, '>&', $wfd or croak $!;
2185 return;
2187 open STDIN, '<&', $rfd or croak $!;
2188 $ENV{LESS} ||= '-S';
2189 exec $pager or croak "Can't run pager: $!\n";;
2192 sub get_author_info {
2193 my ($dest, $author, $t, $tz) = @_;
2194 $author =~ s/(?:^\s*|\s*$)//g;
2195 my $_a;
2196 if ($_authors) {
2197 $_a = $rusers{$author} || undef;
2199 if (!$_a) {
2200 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2202 $dest->{t} = $t;
2203 $dest->{tz} = $tz;
2204 $dest->{a} = $_a;
2205 # Date::Parse isn't in the standard Perl distro :(
2206 if ($tz =~ s/^\+//) {
2207 $t += tz_to_s_offset($tz);
2208 } elsif ($tz =~ s/^\-//) {
2209 $t -= tz_to_s_offset($tz);
2211 $dest->{t_utc} = $t;
2214 sub process_commit {
2215 my ($c, $r_min, $r_max, $defer) = @_;
2216 if (defined $r_min && defined $r_max) {
2217 if ($r_min == $c->{r} && $r_min == $r_max) {
2218 show_commit($c);
2219 return 0;
2221 return 1 if $r_min == $r_max;
2222 if ($r_min < $r_max) {
2223 # we need to reverse the print order
2224 return 0 if (defined $_limit && --$_limit < 0);
2225 push @$defer, $c;
2226 return 1;
2228 if ($r_min != $r_max) {
2229 return 1 if ($r_min < $c->{r});
2230 return 1 if ($r_max > $c->{r});
2233 return 0 if (defined $_limit && --$_limit < 0);
2234 show_commit($c);
2235 return 1;
2238 sub show_commit {
2239 my $c = shift;
2240 if ($_oneline) {
2241 my $x = "\n";
2242 if (my $l = $c->{l}) {
2243 while ($l->[0] =~ /^\s*$/) { shift @$l }
2244 $x = $l->[0];
2246 $_l_fmt ||= 'A' . length($c->{r});
2247 print 'r',pack($_l_fmt, $c->{r}),' | ';
2248 print "$c->{c} | " if $_show_commit;
2249 print $x;
2250 } else {
2251 show_commit_normal($c);
2255 sub show_commit_normal {
2256 my ($c) = @_;
2257 print '-' x72, "\nr$c->{r} | ";
2258 print "$c->{c} | " if $_show_commit;
2259 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2260 localtime($c->{t_utc})), ' | ';
2261 my $nr_line = 0;
2263 if (my $l = $c->{l}) {
2264 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2265 pop @$l;
2267 $nr_line = scalar @$l;
2268 if (!$nr_line) {
2269 print "1 line\n\n\n";
2270 } else {
2271 if ($nr_line == 1) {
2272 $nr_line = '1 line';
2273 } else {
2274 $nr_line .= ' lines';
2276 print $nr_line, "\n\n";
2277 print $_ foreach @$l;
2279 } else {
2280 print "1 line\n\n";
2283 foreach my $x (qw/raw diff/) {
2284 if ($c->{$x}) {
2285 print "\n";
2286 print $_ foreach @{$c->{$x}}
2291 sub libsvn_load {
2292 return unless $_use_lib;
2293 $_use_lib = eval {
2294 require SVN::Core;
2295 if ($SVN::Core::VERSION lt '1.2.1') {
2296 die "Need SVN::Core 1.2.1 or better ",
2297 "(got $SVN::Core::VERSION) ",
2298 "Falling back to command-line svn\n";
2300 require SVN::Ra;
2301 require SVN::Delta;
2302 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2303 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2304 $SVN::Node::dir.$SVN::Node::unknown.
2305 $SVN::Node::none.$SVN::Node::file.
2306 $SVN::Node::dir.$SVN::Node::unknown;
2311 sub libsvn_connect {
2312 my ($url) = @_;
2313 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2314 SVN::Client::get_ssl_server_trust_file_provider(),
2315 SVN::Client::get_username_provider()]);
2316 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2317 return $s;
2320 sub libsvn_get_file {
2321 my ($gui, $f, $rev) = @_;
2322 my $p = $f;
2323 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2325 my $fd = IO::File->new_tmpfile or croak $!;
2326 my $pool = SVN::Pool->new;
2327 my ($r, $props) = $SVN->get_file($f, $rev, $fd, $pool);
2328 $pool->clear;
2329 $fd->flush == 0 or croak $!;
2330 seek $fd, 0, 0 or croak $!;
2331 if (my $es = $props->{'svn:eol-style'}) {
2332 my $new_fd = IO::File->new_tmpfile or croak $!;
2333 eol_cp_fd($fd, $new_fd, $es);
2334 close $fd or croak $!;
2335 $fd = $new_fd;
2336 seek $fd, 0, 0 or croak $!;
2337 $fd->flush == 0 or croak $!;
2339 my $mode = '100644';
2340 if (exists $props->{'svn:executable'}) {
2341 $mode = '100755';
2343 if (exists $props->{'svn:special'}) {
2344 $mode = '120000';
2345 local $/;
2346 my $link = <$fd>;
2347 $link =~ s/^link // or die "svn:special file with contents: <",
2348 $link, "> is not understood\n";
2349 seek $fd, 0, 0 or croak $!;
2350 truncate $fd, 0 or croak $!;
2351 print $fd $link or croak $!;
2352 seek $fd, 0, 0 or croak $!;
2353 $fd->flush == 0 or croak $!;
2355 my $pid = open my $ho, '-|';
2356 defined $pid or croak $!;
2357 if (!$pid) {
2358 open STDIN, '<&', $fd or croak $!;
2359 exec qw/git-hash-object -w --stdin/ or croak $!;
2361 chomp(my $hash = do { local $/; <$ho> });
2362 close $ho or croak $?;
2363 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2364 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2365 close $fd or croak $!;
2368 sub libsvn_log_entry {
2369 my ($rev, $author, $date, $msg, $parents) = @_;
2370 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2371 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2372 or die "Unable to parse date: $date\n";
2373 if (defined $_authors && ! defined $users{$author}) {
2374 die "Author: $author not defined in $_authors file\n";
2376 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2377 author => $author, msg => $msg."\n", parents => $parents || [] }
2380 sub process_rm {
2381 my ($gui, $last_commit, $f) = @_;
2382 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2383 # remove entire directories.
2384 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2385 defined(my $pid = open my $ls, '-|') or croak $!;
2386 if (!$pid) {
2387 exec(qw/git-ls-tree -r --name-only -z/,
2388 $last_commit,'--',$f) or croak $!;
2390 local $/ = "\0";
2391 while (<$ls>) {
2392 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2394 close $ls or croak $!;
2395 } else {
2396 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2400 sub libsvn_fetch {
2401 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2402 open my $gui, '| git-update-index -z --index-info' or croak $!;
2403 my @amr;
2404 foreach my $f (keys %$paths) {
2405 my $m = $paths->{$f}->action();
2406 $f =~ s#^/+##;
2407 if ($m =~ /^[DR]$/) {
2408 process_rm($gui, $last_commit, $f);
2409 next if $m eq 'D';
2410 # 'R' can be file replacements, too, right?
2412 my $pool = SVN::Pool->new;
2413 my $t = $SVN->check_path($f, $rev, $pool);
2414 if ($t == $SVN::Node::file) {
2415 if ($m =~ /^[AMR]$/) {
2416 push @amr, $f;
2417 } else {
2418 die "Unrecognized action: $m, ($f r$rev)\n";
2421 $pool->clear;
2423 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2424 close $gui or croak $!;
2425 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2428 sub svn_grab_base_rev {
2429 defined(my $pid = open my $fh, '-|') or croak $!;
2430 if (!$pid) {
2431 open my $null, '>', '/dev/null' or croak $!;
2432 open STDERR, '>&', $null or croak $!;
2433 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2434 or croak $!;
2436 chomp(my $c = do { local $/; <$fh> });
2437 close $fh;
2438 if (defined $c && length $c) {
2439 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2440 safe_qx(qw/git-cat-file commit/, $c)))[0]);
2441 return ($rev, $c);
2443 return (undef, undef);
2446 sub libsvn_parse_revision {
2447 my $base = shift;
2448 my $head = $SVN->get_latest_revnum();
2449 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2450 return ($base + 1, $head) if (defined $base);
2451 return (0, $head);
2453 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2454 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2455 if ($_revision =~ /^BASE:(\d+)$/) {
2456 return ($base + 1, $1) if (defined $base);
2457 return (0, $head);
2459 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2460 die "revision argument: $_revision not understood by git-svn\n",
2461 "Try using the command-line svn client instead\n";
2464 sub libsvn_traverse {
2465 my ($gui, $pfx, $path, $rev) = @_;
2466 my $cwd = "$pfx/$path";
2467 my $pool = SVN::Pool->new;
2468 $cwd =~ s#^/+##g;
2469 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2470 foreach my $d (keys %$dirent) {
2471 my $t = $dirent->{$d}->kind;
2472 if ($t == $SVN::Node::dir) {
2473 libsvn_traverse($gui, $cwd, $d, $rev);
2474 } elsif ($t == $SVN::Node::file) {
2475 libsvn_get_file($gui, "$cwd/$d", $rev);
2478 $pool->clear;
2481 sub libsvn_traverse_ignore {
2482 my ($fh, $path, $r) = @_;
2483 $path =~ s#^/+##g;
2484 my $pool = SVN::Pool->new;
2485 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2486 my $p = $path;
2487 $p =~ s#^\Q$SVN_PATH\E/?##;
2488 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2489 if (my $s = $props->{'svn:ignore'}) {
2490 $s =~ s/[\r\n]+/\n/g;
2491 chomp $s;
2492 if (length $p == 0) {
2493 $s =~ s#\n#\n/$p#g;
2494 print $fh "/$s\n";
2495 } else {
2496 $s =~ s#\n#\n/$p/#g;
2497 print $fh "/$p/$s\n";
2500 foreach (sort keys %$dirent) {
2501 next if $dirent->{$_}->kind != $SVN::Node::dir;
2502 libsvn_traverse_ignore($fh, "$path/$_", $r);
2504 $pool->clear;
2507 sub revisions_eq {
2508 my ($path, $r0, $r1) = @_;
2509 return 1 if $r0 == $r1;
2510 my $nr = 0;
2511 if ($_use_lib) {
2512 # should be OK to use Pool here (r1 - r0) should be small
2513 my $pool = SVN::Pool->new;
2514 $SVN->get_log("/$path", $r0, $r1, 0, 1, 1, sub {$nr++},$pool);
2515 $pool->clear;
2516 } else {
2517 my ($url, undef) = repo_path_split($SVN_URL);
2518 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2519 while (next_log_entry($svn_log)) { $nr++ }
2520 close $svn_log->{fh};
2522 return 0 if ($nr > 1);
2523 return 1;
2526 sub libsvn_find_parent_branch {
2527 return undef; # XXX this function is disabled atm (not tested enough)
2528 my ($paths, $rev, $author, $date, $msg) = @_;
2529 my $svn_path = '/'.$SVN_PATH;
2531 # look for a parent from another branch:
2532 foreach (keys %$paths) {
2533 next if ($_ ne $svn_path);
2534 my $i = $paths->{$_};
2535 my $branch_from = $i->copyfrom_path or next;
2536 my $r = $i->copyfrom_rev;
2537 print STDERR "Found possible branch point: ",
2538 "$branch_from => $svn_path, $r\n";
2539 $branch_from =~ s#^/##;
2540 my $l_map = read_url_paths();
2541 my $url = $SVN->{url};
2542 defined $l_map->{$url} or next;
2543 my $id = $l_map->{$url}->{$branch_from} or next;
2544 my ($r0, $parent) = find_rev_before($r,$id,1);
2545 if (defined $r0 && defined $parent &&
2546 revisions_eq($branch_from, $r0, $r)) {
2547 unlink $GIT_SVN_INDEX;
2548 print STDERR "Found branch parent: $parent\n";
2549 sys(qw/git-read-tree/, $parent);
2550 return libsvn_fetch($parent, $paths, $rev,
2551 $author, $date, $msg);
2552 } else {
2553 print STDERR
2554 "Nope, branch point not imported or unknown\n";
2557 return undef;
2560 sub libsvn_new_tree {
2561 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2562 return $log_entry;
2564 my ($paths, $rev, $author, $date, $msg) = @_;
2565 open my $gui, '| git-update-index -z --index-info' or croak $!;
2566 my $pool = SVN::Pool->new;
2567 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2568 $pool->clear;
2569 close $gui or croak $!;
2570 return libsvn_log_entry($rev, $author, $date, $msg);
2573 sub find_graft_path_commit {
2574 my ($tree_paths, $p1, $r1) = @_;
2575 foreach my $x (keys %$tree_paths) {
2576 next unless ($p1 =~ /^\Q$x\E/);
2577 my $i = $tree_paths->{$x};
2578 my ($r0, $parent) = find_rev_before($r1,$i,1);
2579 return $parent if (defined $r0 && $r0 == $r1);
2580 print STDERR "r$r1 of $i not imported\n";
2581 next;
2583 return undef;
2586 sub find_graft_path_parents {
2587 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2588 foreach my $x (keys %$tree_paths) {
2589 next unless ($p0 =~ /^\Q$x\E/);
2590 my $i = $tree_paths->{$x};
2591 my ($r, $parent) = find_rev_before($r0, $i, 1);
2592 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2593 $grafts->{$c}->{$parent} = 1;
2598 sub libsvn_graft_file_copies {
2599 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2600 foreach (keys %$paths) {
2601 my $i = $paths->{$_};
2602 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2603 $i->copyfrom_rev);
2604 next unless (defined $p0 && defined $r0);
2606 my $p1 = $_;
2607 $p1 =~ s#^/##;
2608 $p0 =~ s#^/##;
2609 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2610 next unless $c;
2611 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2615 sub set_index {
2616 my $old = $ENV{GIT_INDEX_FILE};
2617 $ENV{GIT_INDEX_FILE} = shift;
2618 return $old;
2621 sub restore_index {
2622 my ($old) = @_;
2623 if (defined $old) {
2624 $ENV{GIT_INDEX_FILE} = $old;
2625 } else {
2626 delete $ENV{GIT_INDEX_FILE};
2630 sub libsvn_commit_cb {
2631 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2632 if ($_optimize_commits && $rev == ($r_last + 1)) {
2633 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2634 $log->{tree} = get_tree_from_treeish($c);
2635 my $cmt = git_commit($log, $cmt_last, $c);
2636 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2637 if (@diff) {
2638 print STDERR "Trees differ: $cmt $c\n",
2639 join('',@diff),"\n";
2640 exit 1;
2642 } else {
2643 fetch_lib("$rev=$c");
2647 sub libsvn_ls_fullurl {
2648 my $fullurl = shift;
2649 my ($repo, $path) = repo_path_split($fullurl);
2650 $SVN ||= libsvn_connect($repo);
2651 my @ret;
2652 my $pool = SVN::Pool->new;
2653 my ($dirent, undef, undef) = $SVN->get_dir($path,
2654 $SVN->get_latest_revnum, $pool);
2655 foreach my $d (keys %$dirent) {
2656 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2657 push @ret, "$d/"; # add '/' for compat with cli svn
2660 $pool->clear;
2661 return @ret;
2665 sub libsvn_skip_unknown_revs {
2666 my $err = shift;
2667 my $errno = $err->apr_err();
2668 # Maybe the branch we're tracking didn't
2669 # exist when the repo started, so it's
2670 # not an error if it doesn't, just continue
2672 # Wonderfully consistent library, eh?
2673 # 160013 - svn:// and file://
2674 # 175002 - http(s)://
2675 # More codes may be discovered later...
2676 if ($errno == 175002 || $errno == 160013) {
2677 print STDERR "directory non-existent\n";
2678 return;
2680 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2683 # Tie::File seems to be prone to offset errors if revisions get sparse,
2684 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2685 # one of my favorite modules is out :< Next up would be one of the DBM
2686 # modules, but I'm not sure which is most portable... So I'll just
2687 # go with something that's plain-text, but still capable of
2688 # being randomly accessed. So here's my ultra-simple fixed-width
2689 # database. All records are 40 characters + "\n", so it's easy to seek
2690 # to a revision: (41 * rev) is the byte offset.
2691 # A record of 40 0s denotes an empty revision.
2692 # And yes, it's still pretty fast (faster than Tie::File).
2693 sub revdb_set {
2694 my ($file, $rev, $commit) = @_;
2695 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2696 open my $fh, '+<', $file or croak $!;
2697 my $offset = $rev * 41;
2698 # assume that append is the common case:
2699 seek $fh, 0, 2 or croak $!;
2700 my $pos = tell $fh;
2701 if ($pos < $offset) {
2702 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2704 seek $fh, $offset, 0 or croak $!;
2705 print $fh $commit,"\n";
2706 close $fh or croak $!;
2709 sub revdb_get {
2710 my ($file, $rev) = @_;
2711 my $ret;
2712 my $offset = $rev * 41;
2713 open my $fh, '<', $file or croak $!;
2714 seek $fh, $offset, 0;
2715 if (tell $fh == $offset) {
2716 $ret = readline $fh;
2717 if (defined $ret) {
2718 chomp $ret;
2719 $ret = undef if ($ret =~ /^0{40}$/);
2722 close $fh or croak $!;
2723 return $ret;
2726 package SVN::Git::Editor;
2727 use vars qw/@ISA/;
2728 use strict;
2729 use warnings;
2730 use Carp qw/croak/;
2731 use IO::File;
2733 sub new {
2734 my $class = shift;
2735 my $git_svn = shift;
2736 my $self = SVN::Delta::Editor->new(@_);
2737 bless $self, $class;
2738 foreach (qw/svn_path c r ra /) {
2739 die "$_ required!\n" unless (defined $git_svn->{$_});
2740 $self->{$_} = $git_svn->{$_};
2742 $self->{pool} = SVN::Pool->new;
2743 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2744 $self->{rm} = { };
2745 require Digest::MD5;
2746 return $self;
2749 sub split_path {
2750 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2753 sub repo_path {
2754 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2755 : $_[0]->{svn_path}
2758 sub url_path {
2759 my ($self, $path) = @_;
2760 $self->{ra}->{url} . '/' . $self->repo_path($path);
2763 sub rmdirs {
2764 my ($self) = @_;
2765 my $rm = $self->{rm};
2766 delete $rm->{''}; # we never delete the url we're tracking
2767 return unless %$rm;
2769 foreach (keys %$rm) {
2770 my @d = split m#/#, $_;
2771 my $c = shift @d;
2772 $rm->{$c} = 1;
2773 while (@d) {
2774 $c .= '/' . shift @d;
2775 $rm->{$c} = 1;
2778 delete $rm->{$self->{svn_path}};
2779 delete $rm->{''}; # we never delete the url we're tracking
2780 return unless %$rm;
2782 defined(my $pid = open my $fh,'-|') or croak $!;
2783 if (!$pid) {
2784 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2786 local $/ = "\0";
2787 while (<$fh>) {
2788 chomp;
2789 $_ = $self->{svn_path} . '/' . $_;
2790 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2791 delete $rm->{$dn};
2792 last unless %$rm;
2794 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2795 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2796 $self->close_directory($bat->{$d}, $p);
2797 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2798 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2799 delete $bat->{$d};
2803 sub open_or_add_dir {
2804 my ($self, $full_path, $baton) = @_;
2805 my $p = SVN::Pool->new;
2806 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2807 $p->clear;
2808 if ($t == $SVN::Node::none) {
2809 return $self->add_directory($full_path, $baton,
2810 undef, -1, $self->{pool});
2811 } elsif ($t == $SVN::Node::dir) {
2812 return $self->open_directory($full_path, $baton,
2813 $self->{r}, $self->{pool});
2815 print STDERR "$full_path already exists in repository at ",
2816 "r$self->{r} and it is not a directory (",
2817 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2818 exit 1;
2821 sub ensure_path {
2822 my ($self, $path) = @_;
2823 my $bat = $self->{bat};
2824 $path = $self->repo_path($path);
2825 return $bat->{''} unless (length $path);
2826 my @p = split m#/+#, $path;
2827 my $c = shift @p;
2828 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2829 while (@p) {
2830 my $c0 = $c;
2831 $c .= '/' . shift @p;
2832 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2834 return $bat->{$c};
2837 sub A {
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 undef, -1);
2843 $self->chg_file($fbat, $m);
2844 $self->close_file($fbat,undef,$self->{pool});
2847 sub C {
2848 my ($self, $m) = @_;
2849 my ($dir, $file) = split_path($m->{file_b});
2850 my $pbat = $self->ensure_path($dir);
2851 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2852 $self->url_path($m->{file_a}), $self->{r});
2853 $self->chg_file($fbat, $m);
2854 $self->close_file($fbat,undef,$self->{pool});
2857 sub delete_entry {
2858 my ($self, $path, $pbat) = @_;
2859 my $rpath = $self->repo_path($path);
2860 my ($dir, $file) = split_path($rpath);
2861 $self->{rm}->{$dir} = 1;
2862 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2865 sub R {
2866 my ($self, $m) = @_;
2867 my ($dir, $file) = split_path($m->{file_b});
2868 my $pbat = $self->ensure_path($dir);
2869 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2870 $self->url_path($m->{file_a}), $self->{r});
2871 $self->chg_file($fbat, $m);
2872 $self->close_file($fbat,undef,$self->{pool});
2874 ($dir, $file) = split_path($m->{file_a});
2875 $pbat = $self->ensure_path($dir);
2876 $self->delete_entry($m->{file_a}, $pbat);
2879 sub M {
2880 my ($self, $m) = @_;
2881 my ($dir, $file) = split_path($m->{file_b});
2882 my $pbat = $self->ensure_path($dir);
2883 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2884 $pbat,$self->{r},$self->{pool});
2885 $self->chg_file($fbat, $m);
2886 $self->close_file($fbat,undef,$self->{pool});
2889 sub T { shift->M(@_) }
2891 sub change_file_prop {
2892 my ($self, $fbat, $pname, $pval) = @_;
2893 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2896 sub chg_file {
2897 my ($self, $fbat, $m) = @_;
2898 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2899 $self->change_file_prop($fbat,'svn:executable','*');
2900 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2901 $self->change_file_prop($fbat,'svn:executable',undef);
2903 my $fh = IO::File->new_tmpfile or croak $!;
2904 if ($m->{mode_b} =~ /^120/) {
2905 print $fh 'link ' or croak $!;
2906 $self->change_file_prop($fbat,'svn:special','*');
2907 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2908 $self->change_file_prop($fbat,'svn:special',undef);
2910 defined(my $pid = fork) or croak $!;
2911 if (!$pid) {
2912 open STDOUT, '>&', $fh or croak $!;
2913 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2915 waitpid $pid, 0;
2916 croak $? if $?;
2917 $fh->flush == 0 or croak $!;
2918 seek $fh, 0, 0 or croak $!;
2920 my $md5 = Digest::MD5->new;
2921 $md5->addfile($fh) or croak $!;
2922 seek $fh, 0, 0 or croak $!;
2924 my $exp = $md5->hexdigest;
2925 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2926 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2927 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2929 close $fh or croak $!;
2932 sub D {
2933 my ($self, $m) = @_;
2934 my ($dir, $file) = split_path($m->{file_b});
2935 my $pbat = $self->ensure_path($dir);
2936 $self->delete_entry($m->{file_b}, $pbat);
2939 sub close_edit {
2940 my ($self) = @_;
2941 my ($p,$bat) = ($self->{pool}, $self->{bat});
2942 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2943 $self->close_directory($bat->{$_}, $p);
2945 $self->SUPER::close_edit($p);
2946 $p->clear;
2949 sub abort_edit {
2950 my ($self) = @_;
2951 $self->SUPER::abort_edit($self->{pool});
2952 $self->{pool}->clear;
2955 __END__
2957 Data structures:
2959 $svn_log hashref (as returned by svn_log_raw)
2961 fh => file handle of the log file,
2962 state => state of the log file parser (sep/msg/rev/msg_start...)
2965 $log_msg hashref as returned by next_log_entry($svn_log)
2967 msg => 'whitespace-formatted log entry
2968 ', # trailing newline is preserved
2969 revision => '8', # integer
2970 date => '2004-02-24T17:01:44.108345Z', # commit date
2971 author => 'committer name'
2975 @mods = array of diff-index line hashes, each element represents one line
2976 of diff-index output
2978 diff-index line ($m hash)
2980 mode_a => first column of diff-index output, no leading ':',
2981 mode_b => second column of diff-index output,
2982 sha1_b => sha1sum of the final blob,
2983 chg => change type [MCRADT],
2984 file_a => original file name of a file (iff chg is 'C' or 'R')
2985 file_b => new/current file name of a file (any chg)
2989 Notes:
2990 I don't trust the each() function on unless I created %hash myself
2991 because the internal iterator may not have started at base.