PageRenderTime 84ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/git-svn.perl

https://bitbucket.org/evzijst/git
Perl | 6288 lines | 5587 code | 417 blank | 284 comment | 789 complexity | f11e5e65e8f23a0fedb5c48fccfa2674 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-2-Clause
  1. #!/usr/bin/env perl
  2. # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
  3. # License: GPL v2 or later
  4. use 5.008;
  5. use warnings;
  6. use strict;
  7. use vars qw/ $AUTHOR $VERSION
  8. $sha1 $sha1_short $_revision $_repository
  9. $_q $_authors $_authors_prog %users/;
  10. $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  11. $VERSION = '@@GIT_VERSION@@';
  12. # From which subdir have we been invoked?
  13. my $cmd_dir_prefix = eval {
  14. command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  15. } || '';
  16. my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  17. $ENV{GIT_DIR} ||= '.git';
  18. $Git::SVN::default_repo_id = 'svn';
  19. $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
  20. $Git::SVN::Ra::_log_window_size = 100;
  21. $Git::SVN::_minimize_url = 'unset';
  22. if (! exists $ENV{SVN_SSH}) {
  23. if (exists $ENV{GIT_SSH}) {
  24. $ENV{SVN_SSH} = $ENV{GIT_SSH};
  25. if ($^O eq 'msys') {
  26. $ENV{SVN_SSH} =~ s/\\/\\\\/g;
  27. $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
  28. }
  29. }
  30. }
  31. $Git::SVN::Log::TZ = $ENV{TZ};
  32. $ENV{TZ} = 'UTC';
  33. $| = 1; # unbuffer STDOUT
  34. sub fatal (@) { print STDERR "@_\n"; exit 1 }
  35. sub _req_svn {
  36. require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  37. require SVN::Ra;
  38. require SVN::Delta;
  39. if ($SVN::Core::VERSION lt '1.1.0') {
  40. fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  41. }
  42. }
  43. my $can_compress = eval { require Compress::Zlib; 1};
  44. push @Git::SVN::Ra::ISA, 'SVN::Ra';
  45. push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
  46. push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
  47. use Carp qw/croak/;
  48. use Digest::MD5;
  49. use IO::File qw//;
  50. use File::Basename qw/dirname basename/;
  51. use File::Path qw/mkpath/;
  52. use File::Spec;
  53. use File::Find;
  54. use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  55. use IPC::Open3;
  56. use Git;
  57. use Memoize; # core since 5.8.0, Jul 2002
  58. BEGIN {
  59. # import functions from Git into our packages, en masse
  60. no strict 'refs';
  61. foreach (qw/command command_oneline command_noisy command_output_pipe
  62. command_input_pipe command_close_pipe
  63. command_bidi_pipe command_close_bidi_pipe/) {
  64. for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
  65. Git::SVN::Migration Git::SVN::Log Git::SVN),
  66. __PACKAGE__) {
  67. *{"${package}::$_"} = \&{"Git::$_"};
  68. }
  69. }
  70. Memoize::memoize 'Git::config';
  71. Memoize::memoize 'Git::config_bool';
  72. }
  73. my ($SVN);
  74. $sha1 = qr/[a-f\d]{40}/;
  75. $sha1_short = qr/[a-f\d]{4,40}/;
  76. my ($_stdin, $_help, $_edit,
  77. $_message, $_file, $_branch_dest,
  78. $_template, $_shared,
  79. $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
  80. $_merge, $_strategy, $_dry_run, $_local,
  81. $_prefix, $_no_checkout, $_url, $_verbose,
  82. $_git_format, $_commit_url, $_tag, $_merge_info);
  83. $Git::SVN::_follow_parent = 1;
  84. $_q ||= 0;
  85. my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  86. 'config-dir=s' => \$Git::SVN::Ra::config_dir,
  87. 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
  88. 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
  89. my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  90. 'authors-file|A=s' => \$_authors,
  91. 'authors-prog=s' => \$_authors_prog,
  92. 'repack:i' => \$Git::SVN::_repack,
  93. 'noMetadata' => \$Git::SVN::_no_metadata,
  94. 'useSvmProps' => \$Git::SVN::_use_svm_props,
  95. 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  96. 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  97. 'no-checkout' => \$_no_checkout,
  98. 'quiet|q+' => \$_q,
  99. 'repack-flags|repack-args|repack-opts=s' =>
  100. \$Git::SVN::_repack_flags,
  101. 'use-log-author' => \$Git::SVN::_use_log_author,
  102. 'add-author-from' => \$Git::SVN::_add_author_from,
  103. 'localtime' => \$Git::SVN::_localtime,
  104. %remote_opts );
  105. my ($_trunk, @_tags, @_branches, $_stdlayout);
  106. my %icv;
  107. my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  108. 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
  109. 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
  110. 'stdlayout|s' => \$_stdlayout,
  111. 'minimize-url|m!' => \$Git::SVN::_minimize_url,
  112. 'no-metadata' => sub { $icv{noMetadata} = 1 },
  113. 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  114. 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  115. 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  116. 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
  117. %remote_opts );
  118. my %cmt_opts = ( 'edit|e' => \$_edit,
  119. 'rmdir' => \$SVN::Git::Editor::_rmdir,
  120. 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
  121. 'l=i' => \$SVN::Git::Editor::_rename_limit,
  122. 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
  123. );
  124. my %cmd = (
  125. fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  126. { 'revision|r=s' => \$_revision,
  127. 'fetch-all|all' => \$_fetch_all,
  128. 'parent|p' => \$_fetch_parent,
  129. %fc_opts } ],
  130. clone => [ \&cmd_clone, "Initialize and fetch revisions",
  131. { 'revision|r=s' => \$_revision,
  132. %fc_opts, %init_opts } ],
  133. init => [ \&cmd_init, "Initialize a repo for tracking" .
  134. " (requires URL argument)",
  135. \%init_opts ],
  136. 'multi-init' => [ \&cmd_multi_init,
  137. "Deprecated alias for ".
  138. "'$0 init -T<trunk> -b<branches> -t<tags>'",
  139. \%init_opts ],
  140. dcommit => [ \&cmd_dcommit,
  141. 'Commit several diffs to merge with upstream',
  142. { 'merge|m|M' => \$_merge,
  143. 'strategy|s=s' => \$_strategy,
  144. 'verbose|v' => \$_verbose,
  145. 'dry-run|n' => \$_dry_run,
  146. 'fetch-all|all' => \$_fetch_all,
  147. 'commit-url=s' => \$_commit_url,
  148. 'revision|r=i' => \$_revision,
  149. 'no-rebase' => \$_no_rebase,
  150. 'mergeinfo=s' => \$_merge_info,
  151. %cmt_opts, %fc_opts } ],
  152. branch => [ \&cmd_branch,
  153. 'Create a branch in the SVN repository',
  154. { 'message|m=s' => \$_message,
  155. 'destination|d=s' => \$_branch_dest,
  156. 'dry-run|n' => \$_dry_run,
  157. 'tag|t' => \$_tag,
  158. 'username=s' => \$Git::SVN::Prompt::_username,
  159. 'commit-url=s' => \$_commit_url } ],
  160. tag => [ sub { $_tag = 1; cmd_branch(@_) },
  161. 'Create a tag in the SVN repository',
  162. { 'message|m=s' => \$_message,
  163. 'destination|d=s' => \$_branch_dest,
  164. 'dry-run|n' => \$_dry_run,
  165. 'username=s' => \$Git::SVN::Prompt::_username,
  166. 'commit-url=s' => \$_commit_url } ],
  167. 'set-tree' => [ \&cmd_set_tree,
  168. "Set an SVN repository to a git tree-ish",
  169. { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
  170. 'create-ignore' => [ \&cmd_create_ignore,
  171. 'Create a .gitignore per svn:ignore',
  172. { 'revision|r=i' => \$_revision
  173. } ],
  174. 'mkdirs' => [ \&cmd_mkdirs ,
  175. "recreate empty directories after a checkout",
  176. { 'revision|r=i' => \$_revision } ],
  177. 'propget' => [ \&cmd_propget,
  178. 'Print the value of a property on a file or directory',
  179. { 'revision|r=i' => \$_revision } ],
  180. 'proplist' => [ \&cmd_proplist,
  181. 'List all properties of a file or directory',
  182. { 'revision|r=i' => \$_revision } ],
  183. 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
  184. { 'revision|r=i' => \$_revision
  185. } ],
  186. 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
  187. { 'revision|r=i' => \$_revision
  188. } ],
  189. 'multi-fetch' => [ \&cmd_multi_fetch,
  190. "Deprecated alias for $0 fetch --all",
  191. { 'revision|r=s' => \$_revision, %fc_opts } ],
  192. 'migrate' => [ sub { },
  193. # no-op, we automatically run this anyways,
  194. 'Migrate configuration/metadata/layout from
  195. previous versions of git-svn',
  196. { 'minimize' => \$Git::SVN::Migration::_minimize,
  197. %remote_opts } ],
  198. 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
  199. { 'limit=i' => \$Git::SVN::Log::limit,
  200. 'revision|r=s' => \$_revision,
  201. 'verbose|v' => \$Git::SVN::Log::verbose,
  202. 'incremental' => \$Git::SVN::Log::incremental,
  203. 'oneline' => \$Git::SVN::Log::oneline,
  204. 'show-commit' => \$Git::SVN::Log::show_commit,
  205. 'non-recursive' => \$Git::SVN::Log::non_recursive,
  206. 'authors-file|A=s' => \$_authors,
  207. 'color' => \$Git::SVN::Log::color,
  208. 'pager=s' => \$Git::SVN::Log::pager
  209. } ],
  210. 'find-rev' => [ \&cmd_find_rev,
  211. "Translate between SVN revision numbers and tree-ish",
  212. {} ],
  213. 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
  214. { 'merge|m|M' => \$_merge,
  215. 'verbose|v' => \$_verbose,
  216. 'strategy|s=s' => \$_strategy,
  217. 'local|l' => \$_local,
  218. 'fetch-all|all' => \$_fetch_all,
  219. 'dry-run|n' => \$_dry_run,
  220. %fc_opts } ],
  221. 'commit-diff' => [ \&cmd_commit_diff,
  222. 'Commit a diff between two trees',
  223. { 'message|m=s' => \$_message,
  224. 'file|F=s' => \$_file,
  225. 'revision|r=s' => \$_revision,
  226. %cmt_opts } ],
  227. 'info' => [ \&cmd_info,
  228. "Show info about the latest SVN revision
  229. on the current branch",
  230. { 'url' => \$_url, } ],
  231. 'blame' => [ \&Git::SVN::Log::cmd_blame,
  232. "Show what revision and author last modified each line of a file",
  233. { 'git-format' => \$_git_format } ],
  234. 'reset' => [ \&cmd_reset,
  235. "Undo fetches back to the specified SVN revision",
  236. { 'revision|r=s' => \$_revision,
  237. 'parent|p' => \$_fetch_parent } ],
  238. 'gc' => [ \&cmd_gc,
  239. "Compress unhandled.log files in .git/svn and remove " .
  240. "index files in .git/svn",
  241. {} ],
  242. );
  243. my $cmd;
  244. for (my $i = 0; $i < @ARGV; $i++) {
  245. if (defined $cmd{$ARGV[$i]}) {
  246. $cmd = $ARGV[$i];
  247. splice @ARGV, $i, 1;
  248. last;
  249. } elsif ($ARGV[$i] eq 'help') {
  250. $cmd = $ARGV[$i+1];
  251. usage(0);
  252. }
  253. };
  254. # make sure we're always running at the top-level working directory
  255. unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
  256. unless (-d $ENV{GIT_DIR}) {
  257. if ($git_dir_user_set) {
  258. die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
  259. "but it is not a directory\n";
  260. }
  261. my $git_dir = delete $ENV{GIT_DIR};
  262. my $cdup = undef;
  263. git_cmd_try {
  264. $cdup = command_oneline(qw/rev-parse --show-cdup/);
  265. $git_dir = '.' unless ($cdup);
  266. chomp $cdup if ($cdup);
  267. $cdup = "." unless ($cdup && length $cdup);
  268. } "Already at toplevel, but $git_dir not found\n";
  269. chdir $cdup or die "Unable to chdir up to '$cdup'\n";
  270. unless (-d $git_dir) {
  271. die "$git_dir still not found after going to ",
  272. "'$cdup'\n";
  273. }
  274. $ENV{GIT_DIR} = $git_dir;
  275. }
  276. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  277. }
  278. my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  279. read_git_config(\%opts);
  280. if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
  281. Getopt::Long::Configure('pass_through');
  282. }
  283. my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
  284. 'minimize-connections' => \$Git::SVN::Migration::_minimize,
  285. 'id|i=s' => \$Git::SVN::default_ref_id,
  286. 'svn-remote|remote|R=s' => sub {
  287. $Git::SVN::no_reuse_existing = 1;
  288. $Git::SVN::default_repo_id = $_[1] });
  289. exit 1 if (!$rv && $cmd && $cmd ne 'log');
  290. usage(0) if $_help;
  291. version() if $_version;
  292. usage(1) unless defined $cmd;
  293. load_authors() if $_authors;
  294. if (defined $_authors_prog) {
  295. $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
  296. }
  297. unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
  298. Git::SVN::Migration::migration_check();
  299. }
  300. Git::SVN::init_vars();
  301. eval {
  302. Git::SVN::verify_remotes_sanity();
  303. $cmd{$cmd}->[0]->(@ARGV);
  304. };
  305. fatal $@ if $@;
  306. post_fetch_checkout();
  307. exit 0;
  308. ####################### primary functions ######################
  309. sub usage {
  310. my $exit = shift || 0;
  311. my $fd = $exit ? \*STDERR : \*STDOUT;
  312. print $fd <<"";
  313. git-svn - bidirectional operations between a single Subversion tree and git
  314. Usage: git svn <command> [options] [arguments]\n
  315. print $fd "Available commands:\n" unless $cmd;
  316. foreach (sort keys %cmd) {
  317. next if $cmd && $cmd ne $_;
  318. next if /^multi-/; # don't show deprecated commands
  319. print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
  320. foreach (sort keys %{$cmd{$_}->[2]}) {
  321. # mixed-case options are for .git/config only
  322. next if /[A-Z]/ && /^[a-z]+$/i;
  323. # prints out arguments as they should be passed:
  324. my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
  325. print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
  326. "--$_" : "-$_" }
  327. split /\|/,$_)," $x\n";
  328. }
  329. }
  330. print $fd <<"";
  331. \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
  332. arbitrary identifier if you're tracking multiple SVN branches/repositories in
  333. one git repository and want to keep them separate. See git-svn(1) for more
  334. information.
  335. exit $exit;
  336. }
  337. sub version {
  338. ::_req_svn();
  339. print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
  340. exit 0;
  341. }
  342. sub do_git_init_db {
  343. unless (-d $ENV{GIT_DIR}) {
  344. my @init_db = ('init');
  345. push @init_db, "--template=$_template" if defined $_template;
  346. if (defined $_shared) {
  347. if ($_shared =~ /[a-z]/) {
  348. push @init_db, "--shared=$_shared";
  349. } else {
  350. push @init_db, "--shared";
  351. }
  352. }
  353. command_noisy(@init_db);
  354. $_repository = Git->repository(Repository => ".git");
  355. }
  356. my $set;
  357. my $pfx = "svn-remote.$Git::SVN::default_repo_id";
  358. foreach my $i (keys %icv) {
  359. die "'$set' and '$i' cannot both be set\n" if $set;
  360. next unless defined $icv{$i};
  361. command_noisy('config', "$pfx.$i", $icv{$i});
  362. $set = $i;
  363. }
  364. my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
  365. command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
  366. if defined $$ignore_regex;
  367. }
  368. sub init_subdir {
  369. my $repo_path = shift or return;
  370. mkpath([$repo_path]) unless -d $repo_path;
  371. chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
  372. $ENV{GIT_DIR} = '.git';
  373. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  374. }
  375. sub cmd_clone {
  376. my ($url, $path) = @_;
  377. if (!defined $path &&
  378. (defined $_trunk || @_branches || @_tags ||
  379. defined $_stdlayout) &&
  380. $url !~ m#^[a-z\+]+://#) {
  381. $path = $url;
  382. }
  383. $path = basename($url) if !defined $path || !length $path;
  384. my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
  385. cmd_init($url, $path);
  386. command_oneline('config', 'svn.authorsfile', $authors_absolute)
  387. if $_authors;
  388. Git::SVN::fetch_all($Git::SVN::default_repo_id);
  389. }
  390. sub cmd_init {
  391. if (defined $_stdlayout) {
  392. $_trunk = 'trunk' if (!defined $_trunk);
  393. @_tags = 'tags' if (! @_tags);
  394. @_branches = 'branches' if (! @_branches);
  395. }
  396. if (defined $_trunk || @_branches || @_tags) {
  397. return cmd_multi_init(@_);
  398. }
  399. my $url = shift or die "SVN repository location required ",
  400. "as a command-line argument\n";
  401. $url = canonicalize_url($url);
  402. init_subdir(@_);
  403. do_git_init_db();
  404. if ($Git::SVN::_minimize_url eq 'unset') {
  405. $Git::SVN::_minimize_url = 0;
  406. }
  407. Git::SVN->init($url);
  408. }
  409. sub cmd_fetch {
  410. if (grep /^\d+=./, @_) {
  411. die "'<rev>=<commit>' fetch arguments are ",
  412. "no longer supported.\n";
  413. }
  414. my ($remote) = @_;
  415. if (@_ > 1) {
  416. die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
  417. }
  418. $Git::SVN::no_reuse_existing = undef;
  419. if ($_fetch_parent) {
  420. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  421. unless ($gs) {
  422. die "Unable to determine upstream SVN information from ",
  423. "working tree history\n";
  424. }
  425. # just fetch, don't checkout.
  426. $_no_checkout = 'true';
  427. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  428. } elsif ($_fetch_all) {
  429. cmd_multi_fetch();
  430. } else {
  431. $remote ||= $Git::SVN::default_repo_id;
  432. Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
  433. }
  434. }
  435. sub cmd_set_tree {
  436. my (@commits) = @_;
  437. if ($_stdin || !@commits) {
  438. print "Reading from stdin...\n";
  439. @commits = ();
  440. while (<STDIN>) {
  441. if (/\b($sha1_short)\b/o) {
  442. unshift @commits, $1;
  443. }
  444. }
  445. }
  446. my @revs;
  447. foreach my $c (@commits) {
  448. my @tmp = command('rev-parse',$c);
  449. if (scalar @tmp == 1) {
  450. push @revs, $tmp[0];
  451. } elsif (scalar @tmp > 1) {
  452. push @revs, reverse(command('rev-list',@tmp));
  453. } else {
  454. fatal "Failed to rev-parse $c";
  455. }
  456. }
  457. my $gs = Git::SVN->new;
  458. my ($r_last, $cmt_last) = $gs->last_rev_commit;
  459. $gs->fetch;
  460. if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
  461. fatal "There are new revisions that were fetched ",
  462. "and need to be merged (or acknowledged) ",
  463. "before committing.\nlast rev: $r_last\n",
  464. " current: $gs->{last_rev}";
  465. }
  466. $gs->set_tree($_) foreach @revs;
  467. print "Done committing ",scalar @revs," revisions to SVN\n";
  468. unlink $gs->{index};
  469. }
  470. sub cmd_dcommit {
  471. my $head = shift;
  472. command_noisy(qw/update-index --refresh/);
  473. git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
  474. 'Cannot dcommit with a dirty index. Commit your changes first, '
  475. . "or stash them with `git stash'.\n";
  476. $head ||= 'HEAD';
  477. my $old_head;
  478. if ($head ne 'HEAD') {
  479. $old_head = eval {
  480. command_oneline([qw/symbolic-ref -q HEAD/])
  481. };
  482. if ($old_head) {
  483. $old_head =~ s{^refs/heads/}{};
  484. } else {
  485. $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
  486. }
  487. command(['checkout', $head], STDERR => 0);
  488. }
  489. my @refs;
  490. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
  491. unless ($gs) {
  492. die "Unable to determine upstream SVN information from ",
  493. "$head history.\nPerhaps the repository is empty.";
  494. }
  495. if (defined $_commit_url) {
  496. $url = $_commit_url;
  497. } else {
  498. $url = eval { command_oneline('config', '--get',
  499. "svn-remote.$gs->{repo_id}.commiturl") };
  500. if (!$url) {
  501. $url = $gs->full_pushurl
  502. }
  503. }
  504. my $last_rev = $_revision if defined $_revision;
  505. if ($url) {
  506. print "Committing to $url ...\n";
  507. }
  508. my ($linear_refs, $parents) = linearize_history($gs, \@refs);
  509. if ($_no_rebase && scalar(@$linear_refs) > 1) {
  510. warn "Attempting to commit more than one change while ",
  511. "--no-rebase is enabled.\n",
  512. "If these changes depend on each other, re-running ",
  513. "without --no-rebase may be required."
  514. }
  515. my $expect_url = $url;
  516. Git::SVN::remove_username($expect_url);
  517. while (1) {
  518. my $d = shift @$linear_refs or last;
  519. unless (defined $last_rev) {
  520. (undef, $last_rev, undef) = cmt_metadata("$d~1");
  521. unless (defined $last_rev) {
  522. fatal "Unable to extract revision information ",
  523. "from commit $d~1";
  524. }
  525. }
  526. if ($_dry_run) {
  527. print "diff-tree $d~1 $d\n";
  528. } else {
  529. my $cmt_rev;
  530. my %ed_opts = ( r => $last_rev,
  531. log => get_commit_entry($d)->{log},
  532. ra => Git::SVN::Ra->new($url),
  533. config => SVN::Core::config_get_config(
  534. $Git::SVN::Ra::config_dir
  535. ),
  536. tree_a => "$d~1",
  537. tree_b => $d,
  538. editor_cb => sub {
  539. print "Committed r$_[0]\n";
  540. $cmt_rev = $_[0];
  541. },
  542. mergeinfo => $_merge_info,
  543. svn_path => '');
  544. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  545. print "No changes\n$d~1 == $d\n";
  546. } elsif ($parents->{$d} && @{$parents->{$d}}) {
  547. $gs->{inject_parents_dcommit}->{$cmt_rev} =
  548. $parents->{$d};
  549. }
  550. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  551. $last_rev = $cmt_rev;
  552. next if $_no_rebase;
  553. # we always want to rebase against the current HEAD,
  554. # not any head that was passed to us
  555. my @diff = command('diff-tree', $d,
  556. $gs->refname, '--');
  557. my @finish;
  558. if (@diff) {
  559. @finish = rebase_cmd();
  560. print STDERR "W: $d and ", $gs->refname,
  561. " differ, using @finish:\n",
  562. join("\n", @diff), "\n";
  563. } else {
  564. print "No changes between current HEAD and ",
  565. $gs->refname,
  566. "\nResetting to the latest ",
  567. $gs->refname, "\n";
  568. @finish = qw/reset --mixed/;
  569. }
  570. command_noisy(@finish, $gs->refname);
  571. if (@diff) {
  572. @refs = ();
  573. my ($url_, $rev_, $uuid_, $gs_) =
  574. working_head_info('HEAD', \@refs);
  575. my ($linear_refs_, $parents_) =
  576. linearize_history($gs_, \@refs);
  577. if (scalar(@$linear_refs) !=
  578. scalar(@$linear_refs_)) {
  579. fatal "# of revisions changed ",
  580. "\nbefore:\n",
  581. join("\n", @$linear_refs),
  582. "\n\nafter:\n",
  583. join("\n", @$linear_refs_), "\n",
  584. 'If you are attempting to commit ',
  585. "merges, try running:\n\t",
  586. 'git rebase --interactive',
  587. '--preserve-merges ',
  588. $gs->refname,
  589. "\nBefore dcommitting";
  590. }
  591. if ($url_ ne $expect_url) {
  592. if ($url_ eq $gs->metadata_url) {
  593. print
  594. "Accepting rewritten URL:",
  595. " $url_\n";
  596. } else {
  597. fatal
  598. "URL mismatch after rebase:",
  599. " $url_ != $expect_url";
  600. }
  601. }
  602. if ($uuid_ ne $uuid) {
  603. fatal "uuid mismatch after rebase: ",
  604. "$uuid_ != $uuid";
  605. }
  606. # remap parents
  607. my (%p, @l, $i);
  608. for ($i = 0; $i < scalar @$linear_refs; $i++) {
  609. my $new = $linear_refs_->[$i] or next;
  610. $p{$new} =
  611. $parents->{$linear_refs->[$i]};
  612. push @l, $new;
  613. }
  614. $parents = \%p;
  615. $linear_refs = \@l;
  616. }
  617. }
  618. }
  619. if ($old_head) {
  620. my $new_head = command_oneline(qw/rev-parse HEAD/);
  621. my $new_is_symbolic = eval {
  622. command_oneline(qw/symbolic-ref -q HEAD/);
  623. };
  624. if ($new_is_symbolic) {
  625. print "dcommitted the branch ", $head, "\n";
  626. } else {
  627. print "dcommitted on a detached HEAD because you gave ",
  628. "a revision argument.\n",
  629. "The rewritten commit is: ", $new_head, "\n";
  630. }
  631. command(['checkout', $old_head], STDERR => 0);
  632. }
  633. unlink $gs->{index};
  634. }
  635. sub cmd_branch {
  636. my ($branch_name, $head) = @_;
  637. unless (defined $branch_name && length $branch_name) {
  638. die(($_tag ? "tag" : "branch") . " name required\n");
  639. }
  640. $head ||= 'HEAD';
  641. my (undef, $rev, undef, $gs) = working_head_info($head);
  642. my $src = $gs->full_pushurl;
  643. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  644. my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
  645. my $glob;
  646. if ($#{$allglobs} == 0) {
  647. $glob = $allglobs->[0];
  648. } else {
  649. unless(defined $_branch_dest) {
  650. die "Multiple ",
  651. $_tag ? "tag" : "branch",
  652. " paths defined for Subversion repository.\n",
  653. "You must specify where you want to create the ",
  654. $_tag ? "tag" : "branch",
  655. " with the --destination argument.\n";
  656. }
  657. foreach my $g (@{$allglobs}) {
  658. # SVN::Git::Editor could probably be moved to Git.pm..
  659. my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
  660. if ($_branch_dest =~ /$re/) {
  661. $glob = $g;
  662. last;
  663. }
  664. }
  665. unless (defined $glob) {
  666. my $dest_re = qr/\b\Q$_branch_dest\E\b/;
  667. foreach my $g (@{$allglobs}) {
  668. $g->{path}->{left} =~ /$dest_re/ or next;
  669. if (defined $glob) {
  670. die "Ambiguous destination: ",
  671. $_branch_dest, "\nmatches both '",
  672. $glob->{path}->{left}, "' and '",
  673. $g->{path}->{left}, "'\n";
  674. }
  675. $glob = $g;
  676. }
  677. unless (defined $glob) {
  678. die "Unknown ",
  679. $_tag ? "tag" : "branch",
  680. " destination $_branch_dest\n";
  681. }
  682. }
  683. }
  684. my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
  685. my $url;
  686. if (defined $_commit_url) {
  687. $url = $_commit_url;
  688. } else {
  689. $url = eval { command_oneline('config', '--get',
  690. "svn-remote.$gs->{repo_id}.commiturl") };
  691. if (!$url) {
  692. $url = $remote->{pushurl} || $remote->{url};
  693. }
  694. }
  695. my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
  696. if ($dst =~ /^https:/ && $src =~ /^http:/) {
  697. $src=~s/^http:/https:/;
  698. }
  699. ::_req_svn();
  700. my $ctx = SVN::Client->new(
  701. auth => Git::SVN::Ra::_auth_providers(),
  702. log_msg => sub {
  703. ${ $_[0] } = defined $_message
  704. ? $_message
  705. : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
  706. . $branch_name;
  707. },
  708. );
  709. eval {
  710. $ctx->ls($dst, 'HEAD', 0);
  711. } and die "branch ${branch_name} already exists\n";
  712. print "Copying ${src} at r${rev} to ${dst}...\n";
  713. $ctx->copy($src, $rev, $dst)
  714. unless $_dry_run;
  715. $gs->fetch_all;
  716. }
  717. sub cmd_find_rev {
  718. my $revision_or_hash = shift or die "SVN or git revision required ",
  719. "as a command-line argument\n";
  720. my $result;
  721. if ($revision_or_hash =~ /^r\d+$/) {
  722. my $head = shift;
  723. $head ||= 'HEAD';
  724. my @refs;
  725. my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
  726. unless ($gs) {
  727. die "Unable to determine upstream SVN information from ",
  728. "$head history\n";
  729. }
  730. my $desired_revision = substr($revision_or_hash, 1);
  731. $result = $gs->rev_map_get($desired_revision, $uuid);
  732. } else {
  733. my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
  734. $result = $rev;
  735. }
  736. print "$result\n" if $result;
  737. }
  738. sub auto_create_empty_directories {
  739. my ($gs) = @_;
  740. my $var = eval { command_oneline('config', '--get', '--bool',
  741. "svn-remote.$gs->{repo_id}.automkdirs") };
  742. # By default, create empty directories by consulting the unhandled log,
  743. # but allow setting it to 'false' to skip it.
  744. return !($var && $var eq 'false');
  745. }
  746. sub cmd_rebase {
  747. command_noisy(qw/update-index --refresh/);
  748. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  749. unless ($gs) {
  750. die "Unable to determine upstream SVN information from ",
  751. "working tree history\n";
  752. }
  753. if ($_dry_run) {
  754. print "Remote Branch: " . $gs->refname . "\n";
  755. print "SVN URL: " . $url . "\n";
  756. return;
  757. }
  758. if (command(qw/diff-index HEAD --/)) {
  759. print STDERR "Cannot rebase with uncommited changes:\n";
  760. command_noisy('status');
  761. exit 1;
  762. }
  763. unless ($_local) {
  764. # rebase will checkout for us, so no need to do it explicitly
  765. $_no_checkout = 'true';
  766. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  767. }
  768. command_noisy(rebase_cmd(), $gs->refname);
  769. if (auto_create_empty_directories($gs)) {
  770. $gs->mkemptydirs;
  771. }
  772. }
  773. sub cmd_show_ignore {
  774. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  775. $gs ||= Git::SVN->new;
  776. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  777. $gs->prop_walk($gs->{path}, $r, sub {
  778. my ($gs, $path, $props) = @_;
  779. print STDOUT "\n# $path\n";
  780. my $s = $props->{'svn:ignore'} or return;
  781. $s =~ s/[\r\n]+/\n/g;
  782. $s =~ s/^\n+//;
  783. chomp $s;
  784. $s =~ s#^#$path#gm;
  785. print STDOUT "$s\n";
  786. });
  787. }
  788. sub cmd_show_externals {
  789. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  790. $gs ||= Git::SVN->new;
  791. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  792. $gs->prop_walk($gs->{path}, $r, sub {
  793. my ($gs, $path, $props) = @_;
  794. print STDOUT "\n# $path\n";
  795. my $s = $props->{'svn:externals'} or return;
  796. $s =~ s/[\r\n]+/\n/g;
  797. chomp $s;
  798. $s =~ s#^#$path#gm;
  799. print STDOUT "$s\n";
  800. });
  801. }
  802. sub cmd_create_ignore {
  803. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  804. $gs ||= Git::SVN->new;
  805. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  806. $gs->prop_walk($gs->{path}, $r, sub {
  807. my ($gs, $path, $props) = @_;
  808. # $path is of the form /path/to/dir/
  809. $path = '.' . $path;
  810. # SVN can have attributes on empty directories,
  811. # which git won't track
  812. mkpath([$path]) unless -d $path;
  813. my $ignore = $path . '.gitignore';
  814. my $s = $props->{'svn:ignore'} or return;
  815. open(GITIGNORE, '>', $ignore)
  816. or fatal("Failed to open `$ignore' for writing: $!");
  817. $s =~ s/[\r\n]+/\n/g;
  818. $s =~ s/^\n+//;
  819. chomp $s;
  820. # Prefix all patterns so that the ignore doesn't apply
  821. # to sub-directories.
  822. $s =~ s#^#/#gm;
  823. print GITIGNORE "$s\n";
  824. close(GITIGNORE)
  825. or fatal("Failed to close `$ignore': $!");
  826. command_noisy('add', '-f', $ignore);
  827. });
  828. }
  829. sub cmd_mkdirs {
  830. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  831. $gs ||= Git::SVN->new;
  832. $gs->mkemptydirs($_revision);
  833. }
  834. sub canonicalize_path {
  835. my ($path) = @_;
  836. my $dot_slash_added = 0;
  837. if (substr($path, 0, 1) ne "/") {
  838. $path = "./" . $path;
  839. $dot_slash_added = 1;
  840. }
  841. # File::Spec->canonpath doesn't collapse x/../y into y (for a
  842. # good reason), so let's do this manually.
  843. $path =~ s#/+#/#g;
  844. $path =~ s#/\.(?:/|$)#/#g;
  845. $path =~ s#/[^/]+/\.\.##g;
  846. $path =~ s#/$##g;
  847. $path =~ s#^\./## if $dot_slash_added;
  848. $path =~ s#^/##;
  849. $path =~ s#^\.$##;
  850. return $path;
  851. }
  852. sub canonicalize_url {
  853. my ($url) = @_;
  854. $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
  855. return $url;
  856. }
  857. # get_svnprops(PATH)
  858. # ------------------
  859. # Helper for cmd_propget and cmd_proplist below.
  860. sub get_svnprops {
  861. my $path = shift;
  862. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  863. $gs ||= Git::SVN->new;
  864. # prefix THE PATH by the sub-directory from which the user
  865. # invoked us.
  866. $path = $cmd_dir_prefix . $path;
  867. fatal("No such file or directory: $path") unless -e $path;
  868. my $is_dir = -d $path ? 1 : 0;
  869. $path = $gs->{path} . '/' . $path;
  870. # canonicalize the path (otherwise libsvn will abort or fail to
  871. # find the file)
  872. $path = canonicalize_path($path);
  873. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  874. my $props;
  875. if ($is_dir) {
  876. (undef, undef, $props) = $gs->ra->get_dir($path, $r);
  877. }
  878. else {
  879. (undef, $props) = $gs->ra->get_file($path, $r, undef);
  880. }
  881. return $props;
  882. }
  883. # cmd_propget (PROP, PATH)
  884. # ------------------------
  885. # Print the SVN property PROP for PATH.
  886. sub cmd_propget {
  887. my ($prop, $path) = @_;
  888. $path = '.' if not defined $path;
  889. usage(1) if not defined $prop;
  890. my $props = get_svnprops($path);
  891. if (not defined $props->{$prop}) {
  892. fatal("`$path' does not have a `$prop' SVN property.");
  893. }
  894. print $props->{$prop} . "\n";
  895. }
  896. # cmd_proplist (PATH)
  897. # -------------------
  898. # Print the list of SVN properties for PATH.
  899. sub cmd_proplist {
  900. my $path = shift;
  901. $path = '.' if not defined $path;
  902. my $props = get_svnprops($path);
  903. print "Properties on '$path':\n";
  904. foreach (sort keys %{$props}) {
  905. print " $_\n";
  906. }
  907. }
  908. sub cmd_multi_init {
  909. my $url = shift;
  910. unless (defined $_trunk || @_branches || @_tags) {
  911. usage(1);
  912. }
  913. $_prefix = '' unless defined $_prefix;
  914. if (defined $url) {
  915. $url = canonicalize_url($url);
  916. init_subdir(@_);
  917. }
  918. do_git_init_db();
  919. if (defined $_trunk) {
  920. $_trunk =~ s#^/+##;
  921. my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
  922. # try both old-style and new-style lookups:
  923. my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
  924. unless ($gs_trunk) {
  925. my ($trunk_url, $trunk_path) =
  926. complete_svn_url($url, $_trunk);
  927. $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
  928. undef, $trunk_ref);
  929. }
  930. }
  931. return unless @_branches || @_tags;
  932. my $ra = $url ? Git::SVN::Ra->new($url) : undef;
  933. foreach my $path (@_branches) {
  934. complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
  935. }
  936. foreach my $path (@_tags) {
  937. complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
  938. }
  939. }
  940. sub cmd_multi_fetch {
  941. $Git::SVN::no_reuse_existing = undef;
  942. my $remotes = Git::SVN::read_all_remotes();
  943. foreach my $repo_id (sort keys %$remotes) {
  944. if ($remotes->{$repo_id}->{url}) {
  945. Git::SVN::fetch_all($repo_id, $remotes);
  946. }
  947. }
  948. }
  949. # this command is special because it requires no metadata
  950. sub cmd_commit_diff {
  951. my ($ta, $tb, $url) = @_;
  952. my $usage = "Usage: $0 commit-diff -r<revision> ".
  953. "<tree-ish> <tree-ish> [<URL>]";
  954. fatal($usage) if (!defined $ta || !defined $tb);
  955. my $svn_path = '';
  956. if (!defined $url) {
  957. my $gs = eval { Git::SVN->new };
  958. if (!$gs) {
  959. fatal("Needed URL or usable git-svn --id in ",
  960. "the command-line\n", $usage);
  961. }
  962. $url = $gs->{url};
  963. $svn_path = $gs->{path};
  964. }
  965. unless (defined $_revision) {
  966. fatal("-r|--revision is a required argument\n", $usage);
  967. }
  968. if (defined $_message && defined $_file) {
  969. fatal("Both --message/-m and --file/-F specified ",
  970. "for the commit message.\n",
  971. "I have no idea what you mean");
  972. }
  973. if (defined $_file) {
  974. $_message = file_to_s($_file);
  975. } else {
  976. $_message ||= get_commit_entry($tb)->{log};
  977. }
  978. my $ra ||= Git::SVN::Ra->new($url);
  979. my $r = $_revision;
  980. if ($r eq 'HEAD') {
  981. $r = $ra->get_latest_revnum;
  982. } elsif ($r !~ /^\d+$/) {
  983. die "revision argument: $r not understood by git-svn\n";
  984. }
  985. my %ed_opts = ( r => $r,
  986. log => $_message,
  987. ra => $ra,
  988. tree_a => $ta,
  989. tree_b => $tb,
  990. editor_cb => sub { print "Committed r$_[0]\n" },
  991. svn_path => $svn_path );
  992. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  993. print "No changes\n$ta == $tb\n";
  994. }
  995. }
  996. sub escape_uri_only {
  997. my ($uri) = @_;
  998. my @tmp;
  999. foreach (split m{/}, $uri) {
  1000. s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
  1001. push @tmp, $_;
  1002. }
  1003. join('/', @tmp);
  1004. }
  1005. sub escape_url {
  1006. my ($url) = @_;
  1007. if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
  1008. my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
  1009. $url = "$scheme://$domain$uri";
  1010. }
  1011. $url;
  1012. }
  1013. sub cmd_info {
  1014. my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
  1015. my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
  1016. if (exists $_[1]) {
  1017. die "Too many arguments specified\n";
  1018. }
  1019. my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
  1020. if (!$file_type && !$diff_status) {
  1021. print STDERR "svn: '$path' is not under version control\n";
  1022. exit 1;
  1023. }
  1024. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1025. unless ($gs) {
  1026. die "Unable to determine upstream SVN information from ",
  1027. "working tree history\n";
  1028. }
  1029. # canonicalize_path() will return "" to make libsvn 1.5.x happy,
  1030. $path = "." if $path eq "";
  1031. my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
  1032. if ($_url) {
  1033. print escape_url($full_url), "\n";
  1034. return;
  1035. }
  1036. my $result = "Path: $path\n";
  1037. $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
  1038. $result .= "URL: " . escape_url($full_url) . "\n";
  1039. eval {
  1040. my $repos_root = $gs->repos_root;
  1041. Git::SVN::remove_username($repos_root);
  1042. $result .= "Repository Root: " . escape_url($repos_root) . "\n";
  1043. };
  1044. if ($@) {
  1045. $result .= "Repository Root: (offline)\n";
  1046. }
  1047. ::_req_svn();
  1048. $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
  1049. ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
  1050. $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
  1051. $result .= "Node Kind: " .
  1052. ($file_type eq "dir" ? "directory" : "file") . "\n";
  1053. my $schedule = $diff_status eq "A"
  1054. ? "add"
  1055. : ($diff_status eq "D" ? "delete" : "normal");
  1056. $result .= "Schedule: $schedule\n";
  1057. if ($diff_status eq "A") {
  1058. print $result, "\n";
  1059. return;
  1060. }
  1061. my ($lc_author, $lc_rev, $lc_date_utc);
  1062. my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
  1063. my $log = command_output_pipe(@args);
  1064. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  1065. while (<$log>) {
  1066. if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
  1067. $lc_author = $1;
  1068. $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
  1069. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  1070. (undef, $lc_rev, undef) = ::extract_metadata($1);
  1071. }
  1072. }
  1073. close $log;
  1074. Git::SVN::Log::set_local_timezone();
  1075. $result .= "Last Changed Author: $lc_author\n";
  1076. $result .= "Last Changed Rev: $lc_rev\n";
  1077. $result .= "Last Changed Date: " .
  1078. Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
  1079. if ($file_type ne "dir") {
  1080. my $text_last_updated_date =
  1081. ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
  1082. $result .=
  1083. "Text Last Updated: " .
  1084. Git::SVN::Log::format_svn_date($text_last_updated_date) .
  1085. "\n";
  1086. my $checksum;
  1087. if ($diff_status eq "D") {
  1088. my ($fh, $ctx) =
  1089. command_output_pipe(qw(cat-file blob), "HEAD:$path");
  1090. if ($file_type eq "link") {
  1091. my $file_name = <$fh>;
  1092. $checksum = md5sum("link $file_name");
  1093. } else {
  1094. $checksum = md5sum($fh);
  1095. }
  1096. command_close_pipe($fh, $ctx);
  1097. } elsif ($file_type eq "link") {
  1098. my $file_name =
  1099. command(qw(cat-file blob), "HEAD:$path");
  1100. $checksum =
  1101. md5sum("link " . $file_name);
  1102. } else {
  1103. open FILE, "<", $path or die $!;
  1104. $checksum = md5sum(\*FILE);
  1105. close FILE or die $!;
  1106. }
  1107. $result .= "Checksum: " . $checksum . "\n";
  1108. }
  1109. print $result, "\n";
  1110. }
  1111. sub cmd_reset {
  1112. my $target = shift || $_revision or die "SVN revision required\n";
  1113. $target = $1 if $target =~ /^r(\d+)$/;
  1114. $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
  1115. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1116. unless ($gs) {
  1117. die "Unable to determine upstream SVN information from ".
  1118. "history\n";
  1119. }
  1120. my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
  1121. die "Cannot find SVN revision $target\n" unless defined($c);
  1122. $gs->rev_map_set($r, $c, 'reset', $uuid);
  1123. print "r$r = $c ($gs->{ref_id})\n";
  1124. }
  1125. sub cmd_gc {
  1126. if (!$can_compress) {
  1127. warn "Compress::Zlib could not be found; unhandled.log " .
  1128. "files will not be compressed.\n";
  1129. }
  1130. find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
  1131. }
  1132. ########################### utility functions #########################
  1133. sub rebase_cmd {
  1134. my @cmd = qw/rebase/;
  1135. push @cmd, '-v' if $_verbose;
  1136. push @cmd, qw/--merge/ if $_merge;
  1137. push @cmd, "--strategy=$_strategy" if $_strategy;
  1138. @cmd;
  1139. }
  1140. sub post_fetch_checkout {
  1141. return if $_no_checkout;
  1142. my $gs = $Git::SVN::_head or return;
  1143. return if verify_ref('refs/heads/master^0');
  1144. # look for "trunk" ref if it exists
  1145. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1146. my $fetch = $remote->{fetch};
  1147. if ($fetch) {
  1148. foreach my $p (keys %$fetch) {
  1149. basename($fetch->{$p}) eq 'trunk' or next;
  1150. $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
  1151. last;
  1152. }
  1153. }
  1154. my $valid_head = verify_ref('HEAD^0');
  1155. command_noisy(qw(update-ref refs/heads/master), $gs->refname);
  1156. return if ($valid_head || !verify_ref('HEAD^0'));
  1157. return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
  1158. my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
  1159. return if -f $index;
  1160. return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
  1161. return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
  1162. command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
  1163. print STDERR "Checked out HEAD:\n ",
  1164. $gs->full_url, " r", $gs->last_rev, "\n";
  1165. if (auto_create_empty_directories($gs)) {
  1166. $gs->mkemptydirs($gs->last_rev);
  1167. }
  1168. }
  1169. sub complete_svn_url {
  1170. my ($url, $path) = @_;
  1171. $path =~ s#/+$##;
  1172. if ($path !~ m#^[a-z\+]+://#) {
  1173. if (!defined $url || $url !~ m#^[a-z\+]+://#) {
  1174. fatal("E: '$path' is not a complete URL ",
  1175. "and a separate URL is not specified");
  1176. }
  1177. return ($url, $path);
  1178. }
  1179. return ($path, '');
  1180. }
  1181. sub complete_url_ls_init {
  1182. my ($ra, $repo_path, $switch, $pfx) = @_;
  1183. unless ($repo_path) {
  1184. print STDERR "W: $switch not specified\n";
  1185. return;
  1186. }
  1187. $repo_path =~ s#/+$##;
  1188. if ($repo_path =~ m#^[a-z\+]+://#) {
  1189. $ra = Git::SVN::Ra->new($repo_path);
  1190. $repo_path = '';
  1191. } else {
  1192. $repo_path =~ s#^/+##;
  1193. unless ($ra) {
  1194. fatal("E: '$repo_path' is not a complete URL ",
  1195. "and a separate URL is not specified");
  1196. }
  1197. }
  1198. my $url = $ra->{url};
  1199. my $gs = Git::SVN->init($url, undef, undef, undef, 1);
  1200. my $k = "svn-remote.$gs->{repo_id}.url";
  1201. my $orig_url = eval { command_oneline(qw/config --get/, $k) };
  1202. if ($orig_url && ($orig_url ne $gs->{url})) {
  1203. die "$k already set: $orig_url\n",
  1204. "wanted to set to: $gs->{url}\n";
  1205. }
  1206. command_oneline('config', $k, $gs->{url}) unless $orig_url;
  1207. my $remote_path = "$gs->{path}/$repo_path";
  1208. $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1209. $remote_path =~ s#/+#/#g;
  1210. $remote_path =~ s#^/##g;
  1211. $remote_path .= "/*" if $remote_path !~ /\*/;
  1212. my ($n) = ($switch =~ /^--(\w+)/);
  1213. if (length $pfx && $pfx !~ m#/$#) {
  1214. die "--prefix='$pfx' must have a trailing slash '/'\n";
  1215. }
  1216. command_noisy('config',
  1217. '--add',
  1218. "svn-remote.$gs->{repo_id}.$n",
  1219. "$remote_path:refs/remotes/$pfx*" .
  1220. ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
  1221. }
  1222. sub verify_ref {
  1223. my ($ref) = @_;
  1224. eval { command_oneline([ 'rev-parse', '--verify', $ref ],
  1225. { STDERR => 0 }); };
  1226. }
  1227. sub get_tree_from_treeish {
  1228. my ($treeish) = @_;
  1229. # $treeish can be a symbolic ref, too:
  1230. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1231. my $expected;
  1232. while ($type eq 'tag') {
  1233. ($treeish, $type) = command(qw/cat-file tag/, $treeish);
  1234. }
  1235. if ($type eq 'commit') {
  1236. $expected = (grep /^tree /, command(qw/cat-file commit/,
  1237. $treeish))[0];
  1238. ($expected) = ($expected =~ /^tree ($sha1)$/o);
  1239. die "Unable to get tree from $treeish\n" unless $expected;
  1240. } elsif ($type eq 'tree') {
  1241. $expected = $treeish;
  1242. } else {
  1243. die "$treeish is a $type, expected tree, tag or commit\n";
  1244. }
  1245. return $expected;
  1246. }
  1247. sub get_commit_entry {
  1248. my ($treeish) = shift;
  1249. my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
  1250. my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
  1251. my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
  1252. open my $log_fh, '>', $commit_editmsg or croak $!;
  1253. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1254. if ($type eq 'commit' || $type eq 'tag') {
  1255. my ($msg_fh, $ctx) = command_output_pipe('cat-file',
  1256. $type, $treeish);
  1257. my $in_msg = 0;
  1258. my $author;
  1259. my $saw_from = 0;
  1260. my $msgbuf = "";
  1261. while (<$msg_fh>) {
  1262. if (!$in_msg) {
  1263. $in_msg = 1 if (/^\s*$/);
  1264. $author = $1 if (/^author (.*>)/);
  1265. } elsif (/^git-svn-id: /) {
  1266. # skip this for now, we regenerate the
  1267. # correct one on re-fetch anyways
  1268. # TODO: set *:merge properties or like...
  1269. } else {
  1270. if (/^From:/ || /^Signed-off-by:/) {
  1271. $saw_from = 1;
  1272. }
  1273. $msgbuf .= $_;
  1274. }
  1275. }
  1276. $msgbuf =~ s/\s+$//s;
  1277. if ($Git::SVN::_add_author_from && defined($author)
  1278. && !$saw_from) {
  1279. $msgbuf .= "\n\nFrom: $author";
  1280. }
  1281. print $log_fh $msgbuf or croak $!;
  1282. command_close_pipe($msg_fh, $ctx);
  1283. }
  1284. close $log_fh or croak $!;
  1285. if ($_edit || ($type eq 'tree')) {
  1286. chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
  1287. system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
  1288. }
  1289. rename $commit_editmsg, $commit_msg or croak $!;
  1290. {
  1291. require Encode;
  1292. # SVN requires messages to be UTF-8 when entering the repo
  1293. local $/;
  1294. open $log_fh, '<', $commit_msg or croak $!;
  1295. binmode $log_fh;
  1296. chomp($log_entry{log} = <$log_fh>);
  1297. my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
  1298. my $msg = $log_entry{log};
  1299. eval { $msg = Encode::decode($enc, $msg, 1) };
  1300. if ($@) {
  1301. die "Could not decode as $enc:\n", $msg,
  1302. "\nPerhaps you need to set i18n.commitencoding\n";
  1303. }
  1304. eval { $msg = Encode::encode('UTF-8', $msg, 1) };
  1305. die "Could not encode as UTF-8:\n$msg\n" if $@;
  1306. $log_entry{log} = $msg;
  1307. close $log_fh or croak $!;
  1308. }
  1309. unlink $commit_msg;
  1310. \%log_entry;
  1311. }
  1312. sub s_to_file {
  1313. my ($str, $file, $mode) = @_;
  1314. open my $fd,'>',$file or croak $!;
  1315. print $fd $str,"\n" or croak $!;
  1316. close $fd or croak $!;
  1317. chmod ($mode &~ umask, $file) if (defined $mode);
  1318. }
  1319. sub file_to_s {
  1320. my $file = shift;
  1321. open my $fd,'<',$file or croak "$!: file: $file\n";
  1322. local $/;
  1323. my $ret = <$fd>;
  1324. close $fd or croak $!;
  1325. $ret =~ s/\s*$//s;
  1326. return $ret;
  1327. }
  1328. # '<svn username> = real-name <email address>' mapping based on git-svnimport:
  1329. sub load_authors {
  1330. open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
  1331. my $log = $cmd eq 'log';
  1332. while (<$authors>) {
  1333. chomp;
  1334. next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
  1335. my ($user, $name, $email) = ($1, $2, $3);
  1336. if ($log) {
  1337. $Git::SVN::Log::rusers{"$name <$email>"} = $user;
  1338. } else {
  1339. $users{$user} = [$name, $email];
  1340. }
  1341. }
  1342. close $authors or croak $!;
  1343. }
  1344. # convert GetOpt::Long specs for use by git-config
  1345. sub read_git_config {
  1346. my $opts = shift;
  1347. my @config_only;
  1348. foreach my $o (keys %$opts) {
  1349. # if we have mixedCase and a long option-only, then
  1350. # it's a config-only variable that we don't need for
  1351. # the command-line.
  1352. push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
  1353. my $v = $opts->{$o};
  1354. my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
  1355. $key =~ s/-//g;
  1356. my $arg = 'git config';
  1357. $arg .= ' --int' if ($o =~ /[:=]i$/);
  1358. $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
  1359. if (ref $v eq 'ARRAY') {
  1360. chomp(my @tmp = `$arg --get-all svn.$key`);
  1361. @$v = @tmp if @tmp;
  1362. } else {
  1363. chomp(my $tmp = `$arg --get svn.$key`);
  1364. if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
  1365. $$v = $tmp;
  1366. }
  1367. }
  1368. }
  1369. delete @$opts{@config_only} if @config_only;
  1370. }
  1371. sub extract_metadata {
  1372. my $id = shift or return (undef, undef, undef);
  1373. my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
  1374. \s([a-f\d\-]+)$/ix);
  1375. if (!defined $rev || !$uuid || !$url) {
  1376. # some of the original repositories I made had
  1377. # identifiers like this:
  1378. ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
  1379. }
  1380. return ($url, $rev, $uuid);
  1381. }
  1382. sub cmt_metadata {
  1383. return extract_metadata((grep(/^git-svn-id: /,
  1384. command(qw/cat-file commit/, shift)))[-1]);
  1385. }
  1386. sub cmt_sha2rev_batch {
  1387. my %s2r;
  1388. my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
  1389. my $list = shift;
  1390. foreach my $sha (@{$list}) {
  1391. my $first = 1;
  1392. my $size = 0;
  1393. print $out $sha, "\n";
  1394. while (my $line = <$in>) {
  1395. if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
  1396. last;
  1397. } elsif ($first &&
  1398. $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
  1399. $first = 0;
  1400. $size = $1;
  1401. next;
  1402. } elsif ($line =~ /^(git-svn-id: )/) {
  1403. my (undef, $rev, undef) =
  1404. extract_metadata($line);
  1405. $s2r{$sha} = $rev;
  1406. }
  1407. $size -= length($line);
  1408. last if ($size == 0);
  1409. }
  1410. }
  1411. command_close_bidi_pipe($pid, $in, $out, $ctx);
  1412. return \%s2r;
  1413. }
  1414. sub working_head_info {
  1415. my ($head, $refs) = @_;
  1416. my @args = qw/log --no-color --no-decorate --first-parent
  1417. --pretty=medium/;
  1418. my ($fh, $ctx) = command_output_pipe(@args, $head);
  1419. my $hash;
  1420. my %max;
  1421. while (<$fh>) {
  1422. if ( m{^commit ($::sha1)$} ) {
  1423. unshift @$refs, $hash if $hash and $refs;
  1424. $hash = $1;
  1425. next;
  1426. }
  1427. next unless s{^\s*(git-svn-id:)}{$1};
  1428. my ($url, $rev, $uuid) = extract_metadata($_);
  1429. if (defined $url && defined $rev) {
  1430. next if $max{$url} and $max{$url} < $rev;
  1431. if (my $gs = Git::SVN->find_by_url($url)) {
  1432. my $c = $gs->rev_map_get($rev, $uuid);
  1433. if ($c && $c eq $hash) {
  1434. close $fh; # break the pipe
  1435. return ($url, $rev, $uuid, $gs);
  1436. } else {
  1437. $max{$url} ||= $gs->rev_map_max;
  1438. }
  1439. }
  1440. }
  1441. }
  1442. command_close_pipe($fh, $ctx);
  1443. (undef, undef, undef, undef);
  1444. }
  1445. sub read_commit_parents {
  1446. my ($parents, $c) = @_;
  1447. chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
  1448. $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
  1449. @{$parents->{$c}} = split(/ /, $p);
  1450. }
  1451. sub linearize_history {
  1452. my ($gs, $refs) = @_;
  1453. my %parents;
  1454. foreach my $c (@$refs) {
  1455. read_commit_parents(\%parents, $c);
  1456. }
  1457. my @linear_refs;
  1458. my %skip = ();
  1459. my $last_svn_commit = $gs->last_commit;
  1460. foreach my $c (reverse @$refs) {
  1461. next if $c eq $last_svn_commit;
  1462. last if $skip{$c};
  1463. unshift @linear_refs, $c;
  1464. $skip{$c} = 1;
  1465. # we only want the first parent to diff against for linear
  1466. # history, we save the rest to inject when we finalize the
  1467. # svn commit
  1468. my $fp_a = verify_ref("$c~1");
  1469. my $fp_b = shift @{$parents{$c}} if $parents{$c};
  1470. if (!$fp_a || !$fp_b) {
  1471. die "Commit $c\n",
  1472. "has no parent commit, and therefore ",
  1473. "nothing to diff against.\n",
  1474. "You should be working from a repository ",
  1475. "originally created by git-svn\n";
  1476. }
  1477. if ($fp_a ne $fp_b) {
  1478. die "$c~1 = $fp_a, however parsing commit $c ",
  1479. "revealed that:\n$c~1 = $fp_b\nBUG!\n";
  1480. }
  1481. foreach my $p (@{$parents{$c}}) {
  1482. $skip{$p} = 1;
  1483. }
  1484. }
  1485. (\@linear_refs, \%parents);
  1486. }
  1487. sub find_file_type_and_diff_status {
  1488. my ($path) = @_;
  1489. return ('dir', '') if $path eq '';
  1490. my $diff_output =
  1491. command_oneline(qw(diff --cached --name-status --), $path) || "";
  1492. my $diff_status = (split(' ', $diff_output))[0] || "";
  1493. my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
  1494. return (undef, undef) if !$diff_status && !$ls_tree;
  1495. if ($diff_status eq "A") {
  1496. return ("link", $diff_status) if -l $path;
  1497. return ("dir", $diff_status) if -d $path;
  1498. return ("file", $diff_status);
  1499. }
  1500. my $mode = (split(' ', $ls_tree))[0] || "";
  1501. return ("link", $diff_status) if $mode eq "120000";
  1502. return ("dir", $diff_status) if $mode eq "040000";
  1503. return ("file", $diff_status);
  1504. }
  1505. sub md5sum {
  1506. my $arg = shift;
  1507. my $ref = ref $arg;
  1508. my $md5 = Digest::MD5->new();
  1509. if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
  1510. $md5->addfile($arg) or croak $!;
  1511. } elsif ($ref eq 'SCALAR') {
  1512. $md5->add($$arg) or croak $!;
  1513. } elsif (!$ref) {
  1514. $md5->add($arg) or croak $!;
  1515. } else {
  1516. ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
  1517. }
  1518. return $md5->hexdigest();
  1519. }
  1520. sub gc_directory {
  1521. if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
  1522. my $out_filename = $_ . ".gz";
  1523. open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
  1524. binmode $in_fh;
  1525. my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
  1526. die "Unable to open $out_filename: $!\n";
  1527. my $res;
  1528. while ($res = sysread($in_fh, my $str, 1024)) {
  1529. $gz->gzwrite($str) or
  1530. die "Unable to write: ".$gz->gzerror()."!\n";
  1531. }
  1532. unlink $_ or die "unlink $File::Find::name: $!\n";
  1533. } elsif (-f $_ && basename($_) eq "index") {
  1534. unlink $_ or die "unlink $_: $!\n";
  1535. }
  1536. }
  1537. package Git::SVN;
  1538. use strict;
  1539. use warnings;
  1540. use Fcntl qw/:DEFAULT :seek/;
  1541. use constant rev_map_fmt => 'NH40';
  1542. use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
  1543. $_repack $_repack_flags $_use_svm_props $_head
  1544. $_use_svnsync_props $no_reuse_existing $_minimize_url
  1545. $_use_log_author $_add_author_from $_localtime/;
  1546. use Carp qw/croak/;
  1547. use File::Path qw/mkpath/;
  1548. use File::Copy qw/copy/;
  1549. use IPC::Open3;
  1550. use Memoize; # core since 5.8.0, Jul 2002
  1551. use Memoize::Storable;
  1552. my ($_gc_nr, $_gc_period);
  1553. # properties that we do not log:
  1554. my %SKIP_PROP;
  1555. BEGIN {
  1556. %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
  1557. svn:special svn:executable
  1558. svn:entry:committed-rev
  1559. svn:entry:last-author
  1560. svn:entry:uuid
  1561. svn:entry:committed-date/;
  1562. # some options are read globally, but can be overridden locally
  1563. # per [svn-remote "..."] section. Command-line options will *NOT*
  1564. # override options set in an [svn-remote "..."] section
  1565. no strict 'refs';
  1566. for my $option (qw/follow_parent no_metadata use_svm_props
  1567. use_svnsync_props/) {
  1568. my $key = $option;
  1569. $key =~ tr/_//d;
  1570. my $prop = "-$option";
  1571. *$option = sub {
  1572. my ($self) = @_;
  1573. return $self->{$prop} if exists $self->{$prop};
  1574. my $k = "svn-remote.$self->{repo_id}.$key";
  1575. eval { command_oneline(qw/config --get/, $k) };
  1576. if ($@) {
  1577. $self->{$prop} = ${"Git::SVN::_$option"};
  1578. } else {
  1579. my $v = command_oneline(qw/config --bool/,$k);
  1580. $self->{$prop} = $v eq 'false' ? 0 : 1;
  1581. }
  1582. return $self->{$prop};
  1583. }
  1584. }
  1585. }
  1586. my (%LOCKFILES, %INDEX_FILES);
  1587. END {
  1588. unlink keys %LOCKFILES if %LOCKFILES;
  1589. unlink keys %INDEX_FILES if %INDEX_FILES;
  1590. }
  1591. sub resolve_local_globs {
  1592. my ($url, $fetch, $glob_spec) = @_;
  1593. return unless defined $glob_spec;
  1594. my $ref = $glob_spec->{ref};
  1595. my $path = $glob_spec->{path};
  1596. foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
  1597. next unless m#^$ref->{regex}$#;
  1598. my $p = $1;
  1599. my $pathname = desanitize_refname($path->full_path($p));
  1600. my $refname = desanitize_refname($ref->full_path($p));
  1601. if (my $existing = $fetch->{$pathname}) {
  1602. if ($existing ne $refname) {
  1603. die "Refspec conflict:\n",
  1604. "existing: $existing\n",
  1605. " globbed: $refname\n";
  1606. }
  1607. my $u = (::cmt_metadata("$refname"))[0];
  1608. $u =~ s!^\Q$url\E(/|$)!! or die
  1609. "$refname: '$url' not found in '$u'\n";
  1610. if ($pathname ne $u) {
  1611. warn "W: Refspec glob conflict ",
  1612. "(ref: $refname):\n",
  1613. "expected path: $pathname\n",
  1614. " real path: $u\n",
  1615. "Continuing ahead with $u\n";
  1616. next;
  1617. }
  1618. } else {
  1619. $fetch->{$pathname} = $refname;
  1620. }
  1621. }
  1622. }
  1623. sub parse_revision_argument {
  1624. my ($base, $head) = @_;
  1625. if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
  1626. return ($base, $head);
  1627. }
  1628. return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
  1629. return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
  1630. return ($head, $head) if ($::_revision eq 'HEAD');
  1631. return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
  1632. return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
  1633. die "revision argument: $::_revision not understood by git-svn\n";
  1634. }
  1635. sub fetch_all {
  1636. my ($repo_id, $remotes) = @_;
  1637. if (ref $repo_id) {
  1638. my $gs = $repo_id;
  1639. $repo_id = undef;
  1640. $repo_id = $gs->{repo_id};
  1641. }
  1642. $remotes ||= read_all_remotes();
  1643. my $remote = $remotes->{$repo_id} or
  1644. die "[svn-remote \"$repo_id\"] unknown\n";
  1645. my $fetch = $remote->{fetch};
  1646. my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
  1647. my (@gs, @globs);
  1648. my $ra = Git::SVN::Ra->new($url);
  1649. my $uuid = $ra->get_uuid;
  1650. my $head = $ra->get_latest_revnum;
  1651. # ignore errors, $head revision may not even exist anymore
  1652. eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
  1653. warn "W: $@\n" if $@;
  1654. my $base = defined $fetch ? $head : 0;
  1655. # read the max revs for wildcard expansion (branches/*, tags/*)
  1656. foreach my $t (qw/branches tags/) {
  1657. defined $remote->{$t} or next;
  1658. push @globs, @{$remote->{$t}};
  1659. my $max_rev = eval { tmp_config(qw/--int --get/,
  1660. "svn-remote.$repo_id.${t}-maxRev") };
  1661. if (defined $max_rev && ($max_rev < $base)) {
  1662. $base = $max_rev;
  1663. } elsif (!defined $max_rev) {
  1664. $base = 0;
  1665. }
  1666. }
  1667. if ($fetch) {
  1668. foreach my $p (sort keys %$fetch) {
  1669. my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
  1670. my $lr = $gs->rev_map_max;
  1671. if (defined $lr) {
  1672. $base = $lr if ($lr < $base);
  1673. }
  1674. push @gs, $gs;
  1675. }
  1676. }
  1677. ($base, $head) = parse_revision_argument($base, $head);
  1678. $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
  1679. }
  1680. sub read_all_remotes {
  1681. my $r = {};
  1682. my $use_svm_props = eval { command_oneline(qw/config --bool
  1683. svn.useSvmProps/) };
  1684. $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
  1685. my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
  1686. foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
  1687. if (m!^(.+)\.fetch=$svn_refspec$!) {
  1688. my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
  1689. die("svn-remote.$remote: remote ref '$remote_ref' "
  1690. . "must start with 'refs/'\n")
  1691. unless $remote_ref =~ m{^refs/};
  1692. $local_ref = uri_decode($local_ref);
  1693. $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
  1694. $r->{$remote}->{svm} = {} if $use_svm_props;
  1695. } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
  1696. $r->{$1}->{svm} = {};
  1697. } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
  1698. $r->{$1}->{url} = $2;
  1699. } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
  1700. $r->{$1}->{pushurl} = $2;
  1701. } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
  1702. my ($remote, $t, $local_ref, $remote_ref) =
  1703. ($1, $2, $3, $4);
  1704. die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
  1705. . "must start with 'refs/'\n")
  1706. unless $remote_ref =~ m{^refs/};
  1707. $local_ref = uri_decode($local_ref);
  1708. my $rs = {
  1709. t => $t,
  1710. remote => $remote,
  1711. path => Git::SVN::GlobSpec->new($local_ref, 1),
  1712. ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
  1713. if (length($rs->{ref}->{right}) != 0) {
  1714. die "The '*' glob character must be the last ",
  1715. "character of '$remote_ref'\n";
  1716. }
  1717. push @{ $r->{$remote}->{$t} }, $rs;
  1718. }
  1719. }
  1720. map {
  1721. if (defined $r->{$_}->{svm}) {
  1722. my $svm;
  1723. eval {
  1724. my $section = "svn-remote.$_";
  1725. $svm = {
  1726. source => tmp_config('--get',
  1727. "$section.svm-source"),
  1728. replace => tmp_config('--get',
  1729. "$section.svm-replace"),
  1730. }
  1731. };
  1732. $r->{$_}->{svm} = $svm;
  1733. }
  1734. } keys %$r;
  1735. $r;
  1736. }
  1737. sub init_vars {
  1738. $_gc_nr = $_gc_period = 1000;
  1739. if (defined $_repack || defined $_repack_flags) {
  1740. warn "Repack options are obsolete; they have no effect.\n";
  1741. }
  1742. }
  1743. sub verify_remotes_sanity {
  1744. return unless -d $ENV{GIT_DIR};
  1745. my %seen;
  1746. foreach (command(qw/config -l/)) {
  1747. if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
  1748. if ($seen{$1}) {
  1749. die "Remote ref refs/remote/$1 is tracked by",
  1750. "\n \"$_\"\nand\n \"$seen{$1}\"\n",
  1751. "Please resolve this ambiguity in ",
  1752. "your git configuration file before ",
  1753. "continuing\n";
  1754. }
  1755. $seen{$1} = $_;
  1756. }
  1757. }
  1758. }
  1759. sub find_existing_remote {
  1760. my ($url, $remotes) = @_;
  1761. return undef if $no_reuse_existing;
  1762. my $existing;
  1763. foreach my $repo_id (keys %$remotes) {
  1764. my $u = $remotes->{$repo_id}->{url} or next;
  1765. next if $u ne $url;
  1766. $existing = $repo_id;
  1767. last;
  1768. }
  1769. $existing;
  1770. }
  1771. sub init_remote_config {
  1772. my ($self, $url, $no_write) = @_;
  1773. $url =~ s!/+$!!; # strip trailing slash
  1774. my $r = read_all_remotes();
  1775. my $existing = find_existing_remote($url, $r);
  1776. if ($existing) {
  1777. unless ($no_write) {
  1778. print STDERR "Using existing ",
  1779. "[svn-remote \"$existing\"]\n";
  1780. }
  1781. $self->{repo_id} = $existing;
  1782. } elsif ($_minimize_url) {
  1783. my $min_url = Git::SVN::Ra->new($url)->minimize_url;
  1784. $existing = find_existing_remote($min_url, $r);
  1785. if ($existing) {
  1786. unless ($no_write) {
  1787. print STDERR "Using existing ",
  1788. "[svn-remote \"$existing\"]\n";
  1789. }
  1790. $self->{repo_id} = $existing;
  1791. }
  1792. if ($min_url ne $url) {
  1793. unless ($no_write) {
  1794. print STDERR "Using higher level of URL: ",
  1795. "$url => $min_url\n";
  1796. }
  1797. my $old_path = $self->{path};
  1798. $self->{path} = $url;
  1799. $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
  1800. if (length $old_path) {
  1801. $self->{path} .= "/$old_path";
  1802. }
  1803. $url = $min_url;
  1804. }
  1805. }
  1806. my $orig_url;
  1807. if (!$existing) {
  1808. # verify that we aren't overwriting anything:
  1809. $orig_url = eval {
  1810. command_oneline('config', '--get',
  1811. "svn-remote.$self->{repo_id}.url")
  1812. };
  1813. if ($orig_url && ($orig_url ne $url)) {
  1814. die "svn-remote.$self->{repo_id}.url already set: ",
  1815. "$orig_url\nwanted to set to: $url\n";
  1816. }
  1817. }
  1818. my ($xrepo_id, $xpath) = find_ref($self->refname);
  1819. if (!$no_write && defined $xpath) {
  1820. die "svn-remote.$xrepo_id.fetch already set to track ",
  1821. "$xpath:", $self->refname, "\n";
  1822. }
  1823. unless ($no_write) {
  1824. command_noisy('config',
  1825. "svn-remote.$self->{repo_id}.url", $url);
  1826. $self->{path} =~ s{^/}{};
  1827. $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1828. command_noisy('config', '--add',
  1829. "svn-remote.$self->{repo_id}.fetch",
  1830. "$self->{path}:".$self->refname);
  1831. }
  1832. $self->{url} = $url;
  1833. }
  1834. sub find_by_url { # repos_root and, path are optional
  1835. my ($class, $full_url, $repos_root, $path) = @_;
  1836. return undef unless defined $full_url;
  1837. remove_username($full_url);
  1838. remove_username($repos_root) if defined $repos_root;
  1839. my $remotes = read_all_remotes();
  1840. if (defined $full_url && defined $repos_root && !defined $path) {
  1841. $path = $full_url;
  1842. $path =~ s#^\Q$repos_root\E(?:/|$)##;
  1843. }
  1844. foreach my $repo_id (keys %$remotes) {
  1845. my $u = $remotes->{$repo_id}->{url} or next;
  1846. remove_username($u);
  1847. next if defined $repos_root && $repos_root ne $u;
  1848. my $fetch = $remotes->{$repo_id}->{fetch} || {};
  1849. foreach my $t (qw/branches tags/) {
  1850. foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
  1851. resolve_local_globs($u, $fetch, $globspec);
  1852. }
  1853. }
  1854. my $p = $path;
  1855. my $rwr = rewrite_root({repo_id => $repo_id});
  1856. my $svm = $remotes->{$repo_id}->{svm}
  1857. if defined $remotes->{$repo_id}->{svm};
  1858. unless (defined $p) {
  1859. $p = $full_url;
  1860. my $z = $u;
  1861. my $prefix = '';
  1862. if ($rwr) {
  1863. $z = $rwr;
  1864. remove_username($z);
  1865. } elsif (defined $svm) {
  1866. $z = $svm->{source};
  1867. $prefix = $svm->{replace};
  1868. $prefix =~ s#^\Q$u\E(?:/|$)##;
  1869. $prefix =~ s#/$##;
  1870. }
  1871. $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
  1872. }
  1873. foreach my $f (keys %$fetch) {
  1874. next if $f ne $p;
  1875. return Git::SVN->new($fetch->{$f}, $repo_id, $f);
  1876. }
  1877. }
  1878. undef;
  1879. }
  1880. sub init {
  1881. my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
  1882. my $self = _new($class, $repo_id, $ref_id, $path);
  1883. if (defined $url) {
  1884. $self->init_remote_config($url, $no_write);
  1885. }
  1886. $self;
  1887. }
  1888. sub find_ref {
  1889. my ($ref_id) = @_;
  1890. foreach (command(qw/config -l/)) {
  1891. next unless m!^svn-remote\.(.+)\.fetch=
  1892. \s*(.*?)\s*:\s*(.+?)\s*$!x;
  1893. my ($repo_id, $path, $ref) = ($1, $2, $3);
  1894. if ($ref eq $ref_id) {
  1895. $path = '' if ($path =~ m#^\./?#);
  1896. return ($repo_id, $path);
  1897. }
  1898. }
  1899. (undef, undef, undef);
  1900. }
  1901. sub new {
  1902. my ($class, $ref_id, $repo_id, $path) = @_;
  1903. if (defined $ref_id && !defined $repo_id && !defined $path) {
  1904. ($repo_id, $path) = find_ref($ref_id);
  1905. if (!defined $repo_id) {
  1906. die "Could not find a \"svn-remote.*.fetch\" key ",
  1907. "in the repository configuration matching: ",
  1908. "$ref_id\n";
  1909. }
  1910. }
  1911. my $self = _new($class, $repo_id, $ref_id, $path);
  1912. if (!defined $self->{path} || !length $self->{path}) {
  1913. my $fetch = command_oneline('config', '--get',
  1914. "svn-remote.$repo_id.fetch",
  1915. ":$ref_id\$") or
  1916. die "Failed to read \"svn-remote.$repo_id.fetch\" ",
  1917. "\":$ref_id\$\" in config\n";
  1918. ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
  1919. }
  1920. $self->{path} =~ s{/+}{/}g;
  1921. $self->{path} =~ s{\A/}{};
  1922. $self->{path} =~ s{/\z}{};
  1923. $self->{url} = command_oneline('config', '--get',
  1924. "svn-remote.$repo_id.url") or
  1925. die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
  1926. $self->{pushurl} = eval { command_oneline('config', '--get',
  1927. "svn-remote.$repo_id.pushurl") };
  1928. $self->rebuild;
  1929. $self;
  1930. }
  1931. sub refname {
  1932. my ($refname) = $_[0]->{ref_id} ;
  1933. # It cannot end with a slash /, we'll throw up on this because
  1934. # SVN can't have directories with a slash in their name, either:
  1935. if ($refname =~ m{/$}) {
  1936. die "ref: '$refname' ends with a trailing slash, this is ",
  1937. "not permitted by git nor Subversion\n";
  1938. }
  1939. # It cannot have ASCII control character space, tilde ~, caret ^,
  1940. # colon :, question-mark ?, asterisk *, space, or open bracket [
  1941. # anywhere.
  1942. #
  1943. # Additionally, % must be escaped because it is used for escaping
  1944. # and we want our escaped refname to be reversible
  1945. $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
  1946. # no slash-separated component can begin with a dot .
  1947. # /.* becomes /%2E*
  1948. $refname =~ s{/\.}{/%2E}g;
  1949. # It cannot have two consecutive dots .. anywhere
  1950. # .. becomes %2E%2E
  1951. $refname =~ s{\.\.}{%2E%2E}g;
  1952. # trailing dots and .lock are not allowed
  1953. # .$ becomes %2E and .lock becomes %2Elock
  1954. $refname =~ s{\.(?=$|lock$)}{%2E};
  1955. # the sequence @{ is used to access the reflog
  1956. # @{ becomes %40{
  1957. $refname =~ s{\@\{}{%40\{}g;
  1958. return $refname;
  1959. }
  1960. sub desanitize_refname {
  1961. my ($refname) = @_;
  1962. $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
  1963. return $refname;
  1964. }
  1965. sub svm_uuid {
  1966. my ($self) = @_;
  1967. return $self->{svm}->{uuid} if $self->svm;
  1968. $self->ra;
  1969. unless ($self->{svm}) {
  1970. die "SVM UUID not cached, and reading remotely failed\n";
  1971. }
  1972. $self->{svm}->{uuid};
  1973. }
  1974. sub svm {
  1975. my ($self) = @_;
  1976. return $self->{svm} if $self->{svm};
  1977. my $svm;
  1978. # see if we have it in our config, first:
  1979. eval {
  1980. my $section = "svn-remote.$self->{repo_id}";
  1981. $svm = {
  1982. source => tmp_config('--get', "$section.svm-source"),
  1983. uuid => tmp_config('--get', "$section.svm-uuid"),
  1984. replace => tmp_config('--get', "$section.svm-replace"),
  1985. }
  1986. };
  1987. if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
  1988. $self->{svm} = $svm;
  1989. }
  1990. $self->{svm};
  1991. }
  1992. sub _set_svm_vars {
  1993. my ($self, $ra) = @_;
  1994. return $ra if $self->svm;
  1995. my @err = ( "useSvmProps set, but failed to read SVM properties\n",
  1996. "(svm:source, svm:uuid) ",
  1997. "from the following URLs:\n" );
  1998. sub read_svm_props {
  1999. my ($self, $ra, $path, $r) = @_;
  2000. my $props = ($ra->get_dir($path, $r))[2];
  2001. my $src = $props->{'svm:source'};
  2002. my $uuid = $props->{'svm:uuid'};
  2003. return undef if (!$src || !$uuid);
  2004. chomp($src, $uuid);
  2005. $uuid =~ m{^[0-9a-f\-]{30,}$}i
  2006. or die "doesn't look right - svm:uuid is '$uuid'\n";
  2007. # the '!' is used to mark the repos_root!/relative/path
  2008. $src =~ s{/?!/?}{/};
  2009. $src =~ s{/+$}{}; # no trailing slashes please
  2010. # username is of no interest
  2011. $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
  2012. my $replace = $ra->{url};
  2013. $replace .= "/$path" if length $path;
  2014. my $section = "svn-remote.$self->{repo_id}";
  2015. tmp_config("$section.svm-source", $src);
  2016. tmp_config("$section.svm-replace", $replace);
  2017. tmp_config("$section.svm-uuid", $uuid);
  2018. $self->{svm} = {
  2019. source => $src,
  2020. uuid => $uuid,
  2021. replace => $replace
  2022. };
  2023. }
  2024. my $r = $ra->get_latest_revnum;
  2025. my $path = $self->{path};
  2026. my %tried;
  2027. while (length $path) {
  2028. unless ($tried{"$self->{url}/$path"}) {
  2029. return $ra if $self->read_svm_props($ra, $path, $r);
  2030. $tried{"$self->{url}/$path"} = 1;
  2031. }
  2032. $path =~ s#/?[^/]+$##;
  2033. }
  2034. die "Path: '$path' should be ''\n" if $path ne '';
  2035. return $ra if $self->read_svm_props($ra, $path, $r);
  2036. $tried{"$self->{url}/$path"} = 1;
  2037. if ($ra->{repos_root} eq $self->{url}) {
  2038. die @err, (map { " $_\n" } keys %tried), "\n";
  2039. }
  2040. # nope, make sure we're connected to the repository root:
  2041. my $ok;
  2042. my @tried_b;
  2043. $path = $ra->{svn_path};
  2044. $ra = Git::SVN::Ra->new($ra->{repos_root});
  2045. while (length $path) {
  2046. unless ($tried{"$ra->{url}/$path"}) {
  2047. $ok = $self->read_svm_props($ra, $path, $r);
  2048. last if $ok;
  2049. $tried{"$ra->{url}/$path"} = 1;
  2050. }
  2051. $path =~ s#/?[^/]+$##;
  2052. }
  2053. die "Path: '$path' should be ''\n" if $path ne '';
  2054. $ok ||= $self->read_svm_props($ra, $path, $r);
  2055. $tried{"$ra->{url}/$path"} = 1;
  2056. if (!$ok) {
  2057. die @err, (map { " $_\n" } keys %tried), "\n";
  2058. }
  2059. Git::SVN::Ra->new($self->{url});
  2060. }
  2061. sub svnsync {
  2062. my ($self) = @_;
  2063. return $self->{svnsync} if $self->{svnsync};
  2064. if ($self->no_metadata) {
  2065. die "Can't have both 'noMetadata' and ",
  2066. "'useSvnsyncProps' options set!\n";
  2067. }
  2068. if ($self->rewrite_root) {
  2069. die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
  2070. "options set!\n";
  2071. }
  2072. if ($self->rewrite_uuid) {
  2073. die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
  2074. "options set!\n";
  2075. }
  2076. my $svnsync;
  2077. # see if we have it in our config, first:
  2078. eval {
  2079. my $section = "svn-remote.$self->{repo_id}";
  2080. my $url = tmp_config('--get', "$section.svnsync-url");
  2081. ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
  2082. die "doesn't look right - svn:sync-from-url is '$url'\n";
  2083. my $uuid = tmp_config('--get', "$section.svnsync-uuid");
  2084. ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
  2085. die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
  2086. $svnsync = { url => $url, uuid => $uuid }
  2087. };
  2088. if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
  2089. return $self->{svnsync} = $svnsync;
  2090. }
  2091. my $err = "useSvnsyncProps set, but failed to read " .
  2092. "svnsync property: svn:sync-from-";
  2093. my $rp = $self->ra->rev_proplist(0);
  2094. my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
  2095. ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
  2096. die "doesn't look right - svn:sync-from-url is '$url'\n";
  2097. my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
  2098. ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
  2099. die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
  2100. my $section = "svn-remote.$self->{repo_id}";
  2101. tmp_config('--add', "$section.svnsync-uuid", $uuid);
  2102. tmp_config('--add', "$section.svnsync-url", $url);
  2103. return $self->{svnsync} = { url => $url, uuid => $uuid };
  2104. }
  2105. # this allows us to memoize our SVN::Ra UUID locally and avoid a
  2106. # remote lookup (useful for 'git svn log').
  2107. sub ra_uuid {
  2108. my ($self) = @_;
  2109. unless ($self->{ra_uuid}) {
  2110. my $key = "svn-remote.$self->{repo_id}.uuid";
  2111. my $uuid = eval { tmp_config('--get', $key) };
  2112. if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
  2113. $self->{ra_uuid} = $uuid;
  2114. } else {
  2115. die "ra_uuid called without URL\n" unless $self->{url};
  2116. $self->{ra_uuid} = $self->ra->get_uuid;
  2117. tmp_config('--add', $key, $self->{ra_uuid});
  2118. }
  2119. }
  2120. $self->{ra_uuid};
  2121. }
  2122. sub _set_repos_root {
  2123. my ($self, $repos_root) = @_;
  2124. my $k = "svn-remote.$self->{repo_id}.reposRoot";
  2125. $repos_root ||= $self->ra->{repos_root};
  2126. tmp_config($k, $repos_root);
  2127. $repos_root;
  2128. }
  2129. sub repos_root {
  2130. my ($self) = @_;
  2131. my $k = "svn-remote.$self->{repo_id}.reposRoot";
  2132. eval { tmp_config('--get', $k) } || $self->_set_repos_root;
  2133. }
  2134. sub ra {
  2135. my ($self) = shift;
  2136. my $ra = Git::SVN::Ra->new($self->{url});
  2137. $self->_set_repos_root($ra->{repos_root});
  2138. if ($self->use_svm_props && !$self->{svm}) {
  2139. if ($self->no_metadata) {
  2140. die "Can't have both 'noMetadata' and ",
  2141. "'useSvmProps' options set!\n";
  2142. } elsif ($self->use_svnsync_props) {
  2143. die "Can't have both 'useSvnsyncProps' and ",
  2144. "'useSvmProps' options set!\n";
  2145. }
  2146. $ra = $self->_set_svm_vars($ra);
  2147. $self->{-want_revprops} = 1;
  2148. }
  2149. $ra;
  2150. }
  2151. # prop_walk(PATH, REV, SUB)
  2152. # -------------------------
  2153. # Recursively traverse PATH at revision REV and invoke SUB for each
  2154. # directory that contains a SVN property. SUB will be invoked as
  2155. # follows: &SUB(gs, path, props); where `gs' is this instance of
  2156. # Git::SVN, `path' the path to the directory where the properties
  2157. # `props' were found. The `path' will be relative to point of checkout,
  2158. # that is, if url://repo/trunk is the current Git branch, and that
  2159. # directory contains a sub-directory `d', SUB will be invoked with `/d/'
  2160. # as `path' (note the trailing `/').
  2161. sub prop_walk {
  2162. my ($self, $path, $rev, $sub) = @_;
  2163. $path =~ s#^/##;
  2164. my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
  2165. $path =~ s#^/*#/#g;
  2166. my $p = $path;
  2167. # Strip the irrelevant part of the path.
  2168. $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
  2169. # Ensure the path is terminated by a `/'.
  2170. $p =~ s#/*$#/#;
  2171. # The properties contain all the internal SVN stuff nobody
  2172. # (usually) cares about.
  2173. my $interesting_props = 0;
  2174. foreach (keys %{$props}) {
  2175. # If it doesn't start with `svn:', it must be a
  2176. # user-defined property.
  2177. ++$interesting_props and next if $_ !~ /^svn:/;
  2178. # FIXME: Fragile, if SVN adds new public properties,
  2179. # this needs to be updated.
  2180. ++$interesting_props if /^svn:(?:ignore|keywords|executable
  2181. |eol-style|mime-type
  2182. |externals|needs-lock)$/x;
  2183. }
  2184. &$sub($self, $p, $props) if $interesting_props;
  2185. foreach (sort keys %$dirent) {
  2186. next if $dirent->{$_}->{kind} != $SVN::Node::dir;
  2187. $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
  2188. }
  2189. }
  2190. sub last_rev { ($_[0]->last_rev_commit)[0] }
  2191. sub last_commit { ($_[0]->last_rev_commit)[1] }
  2192. # returns the newest SVN revision number and newest commit SHA1
  2193. sub last_rev_commit {
  2194. my ($self) = @_;
  2195. if (defined $self->{last_rev} && defined $self->{last_commit}) {
  2196. return ($self->{last_rev}, $self->{last_commit});
  2197. }
  2198. my $c = ::verify_ref($self->refname.'^0');
  2199. if ($c && !$self->use_svm_props && !$self->no_metadata) {
  2200. my $rev = (::cmt_metadata($c))[1];
  2201. if (defined $rev) {
  2202. ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
  2203. return ($rev, $c);
  2204. }
  2205. }
  2206. my $map_path = $self->map_path;
  2207. unless (-e $map_path) {
  2208. ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
  2209. return (undef, undef);
  2210. }
  2211. my ($rev, $commit) = $self->rev_map_max(1);
  2212. ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
  2213. return ($rev, $commit);
  2214. }
  2215. sub get_fetch_range {
  2216. my ($self, $min, $max) = @_;
  2217. $max ||= $self->ra->get_latest_revnum;
  2218. $min ||= $self->rev_map_max;
  2219. (++$min, $max);
  2220. }
  2221. sub tmp_config {
  2222. my (@args) = @_;
  2223. my $old_def_config = "$ENV{GIT_DIR}/svn/config";
  2224. my $config = "$ENV{GIT_DIR}/svn/.metadata";
  2225. if (! -f $config && -f $old_def_config) {
  2226. rename $old_def_config, $config or
  2227. die "Failed rename $old_def_config => $config: $!\n";
  2228. }
  2229. my $old_config = $ENV{GIT_CONFIG};
  2230. $ENV{GIT_CONFIG} = $config;
  2231. $@ = undef;
  2232. my @ret = eval {
  2233. unless (-f $config) {
  2234. mkfile($config);
  2235. open my $fh, '>', $config or
  2236. die "Can't open $config: $!\n";
  2237. print $fh "; This file is used internally by ",
  2238. "git-svn\n" or die
  2239. "Couldn't write to $config: $!\n";
  2240. print $fh "; You should not have to edit it\n" or
  2241. die "Couldn't write to $config: $!\n";
  2242. close $fh or die "Couldn't close $config: $!\n";
  2243. }
  2244. command('config', @args);
  2245. };
  2246. my $err = $@;
  2247. if (defined $old_config) {
  2248. $ENV{GIT_CONFIG} = $old_config;
  2249. } else {
  2250. delete $ENV{GIT_CONFIG};
  2251. }
  2252. die $err if $err;
  2253. wantarray ? @ret : $ret[0];
  2254. }
  2255. sub tmp_index_do {
  2256. my ($self, $sub) = @_;
  2257. my $old_index = $ENV{GIT_INDEX_FILE};
  2258. $ENV{GIT_INDEX_FILE} = $self->{index};
  2259. $@ = undef;
  2260. my @ret = eval {
  2261. my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
  2262. mkpath([$dir]) unless -d $dir;
  2263. &$sub;
  2264. };
  2265. my $err = $@;
  2266. if (defined $old_index) {
  2267. $ENV{GIT_INDEX_FILE} = $old_index;
  2268. } else {
  2269. delete $ENV{GIT_INDEX_FILE};
  2270. }
  2271. die $err if $err;
  2272. wantarray ? @ret : $ret[0];
  2273. }
  2274. sub assert_index_clean {
  2275. my ($self, $treeish) = @_;
  2276. $self->tmp_index_do(sub {
  2277. command_noisy('read-tree', $treeish) unless -e $self->{index};
  2278. my $x = command_oneline('write-tree');
  2279. my ($y) = (command(qw/cat-file commit/, $treeish) =~
  2280. /^tree ($::sha1)/mo);
  2281. return if $y eq $x;
  2282. warn "Index mismatch: $y != $x\nrereading $treeish\n";
  2283. unlink $self->{index} or die "unlink $self->{index}: $!\n";
  2284. command_noisy('read-tree', $treeish);
  2285. $x = command_oneline('write-tree');
  2286. if ($y ne $x) {
  2287. ::fatal "trees ($treeish) $y != $x\n",
  2288. "Something is seriously wrong...";
  2289. }
  2290. });
  2291. }
  2292. sub get_commit_parents {
  2293. my ($self, $log_entry) = @_;
  2294. my (%seen, @ret, @tmp);
  2295. # legacy support for 'set-tree'; this is only used by set_tree_cb:
  2296. if (my $ip = $self->{inject_parents}) {
  2297. if (my $commit = delete $ip->{$log_entry->{revision}}) {
  2298. push @tmp, $commit;
  2299. }
  2300. }
  2301. if (my $cur = ::verify_ref($self->refname.'^0')) {
  2302. push @tmp, $cur;
  2303. }
  2304. if (my $ipd = $self->{inject_parents_dcommit}) {
  2305. if (my $commit = delete $ipd->{$log_entry->{revision}}) {
  2306. push @tmp, @$commit;
  2307. }
  2308. }
  2309. push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
  2310. while (my $p = shift @tmp) {
  2311. next if $seen{$p};
  2312. $seen{$p} = 1;
  2313. push @ret, $p;
  2314. }
  2315. @ret;
  2316. }
  2317. sub rewrite_root {
  2318. my ($self) = @_;
  2319. return $self->{-rewrite_root} if exists $self->{-rewrite_root};
  2320. my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
  2321. my $rwr = eval { command_oneline(qw/config --get/, $k) };
  2322. if ($rwr) {
  2323. $rwr =~ s#/+$##;
  2324. if ($rwr !~ m#^[a-z\+]+://#) {
  2325. die "$rwr is not a valid URL (key: $k)\n";
  2326. }
  2327. }
  2328. $self->{-rewrite_root} = $rwr;
  2329. }
  2330. sub rewrite_uuid {
  2331. my ($self) = @_;
  2332. return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
  2333. my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
  2334. my $rwid = eval { command_oneline(qw/config --get/, $k) };
  2335. if ($rwid) {
  2336. $rwid =~ s#/+$##;
  2337. if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
  2338. die "$rwid is not a valid UUID (key: $k)\n";
  2339. }
  2340. }
  2341. $self->{-rewrite_uuid} = $rwid;
  2342. }
  2343. sub metadata_url {
  2344. my ($self) = @_;
  2345. ($self->rewrite_root || $self->{url}) .
  2346. (length $self->{path} ? '/' . $self->{path} : '');
  2347. }
  2348. sub full_url {
  2349. my ($self) = @_;
  2350. $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
  2351. }
  2352. sub full_pushurl {
  2353. my ($self) = @_;
  2354. if ($self->{pushurl}) {
  2355. return $self->{pushurl} . (length $self->{path} ? '/' .
  2356. $self->{path} : '');
  2357. } else {
  2358. return $self->full_url;
  2359. }
  2360. }
  2361. sub set_commit_header_env {
  2362. my ($log_entry) = @_;
  2363. my %env;
  2364. foreach my $ned (qw/NAME EMAIL DATE/) {
  2365. foreach my $ac (qw/AUTHOR COMMITTER/) {
  2366. $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
  2367. }
  2368. }
  2369. $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
  2370. $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
  2371. $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
  2372. $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
  2373. ? $log_entry->{commit_name}
  2374. : $log_entry->{name};
  2375. $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
  2376. ? $log_entry->{commit_email}
  2377. : $log_entry->{email};
  2378. \%env;
  2379. }
  2380. sub restore_commit_header_env {
  2381. my ($env) = @_;
  2382. foreach my $ned (qw/NAME EMAIL DATE/) {
  2383. foreach my $ac (qw/AUTHOR COMMITTER/) {
  2384. my $k = "GIT_${ac}_${ned}";
  2385. if (defined $env->{$k}) {
  2386. $ENV{$k} = $env->{$k};
  2387. } else {
  2388. delete $ENV{$k};
  2389. }
  2390. }
  2391. }
  2392. }
  2393. sub gc {
  2394. command_noisy('gc', '--auto');
  2395. };
  2396. sub do_git_commit {
  2397. my ($self, $log_entry) = @_;
  2398. my $lr = $self->last_rev;
  2399. if (defined $lr && $lr >= $log_entry->{revision}) {
  2400. die "Last fetched revision of ", $self->refname,
  2401. " was r$lr, but we are about to fetch: ",
  2402. "r$log_entry->{revision}!\n";
  2403. }
  2404. if (my $c = $self->rev_map_get($log_entry->{revision})) {
  2405. croak "$log_entry->{revision} = $c already exists! ",
  2406. "Why are we refetching it?\n";
  2407. }
  2408. my $old_env = set_commit_header_env($log_entry);
  2409. my $tree = $log_entry->{tree};
  2410. if (!defined $tree) {
  2411. $tree = $self->tmp_index_do(sub {
  2412. command_oneline('write-tree') });
  2413. }
  2414. die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
  2415. my @exec = ('git', 'commit-tree', $tree);
  2416. foreach ($self->get_commit_parents($log_entry)) {
  2417. push @exec, '-p', $_;
  2418. }
  2419. defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
  2420. or croak $!;
  2421. binmode $msg_fh;
  2422. # we always get UTF-8 from SVN, but we may want our commits in
  2423. # a different encoding.
  2424. if (my $enc = Git::config('i18n.commitencoding')) {
  2425. require Encode;
  2426. Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
  2427. }
  2428. print $msg_fh $log_entry->{log} or croak $!;
  2429. restore_commit_header_env($old_env);
  2430. unless ($self->no_metadata) {
  2431. print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
  2432. or croak $!;
  2433. }
  2434. $msg_fh->flush == 0 or croak $!;
  2435. close $msg_fh or croak $!;
  2436. chomp(my $commit = do { local $/; <$out_fh> });
  2437. close $out_fh or croak $!;
  2438. waitpid $pid, 0;
  2439. croak $? if $?;
  2440. if ($commit !~ /^$::sha1$/o) {
  2441. die "Failed to commit, invalid sha1: $commit\n";
  2442. }
  2443. $self->rev_map_set($log_entry->{revision}, $commit, 1);
  2444. $self->{last_rev} = $log_entry->{revision};
  2445. $self->{last_commit} = $commit;
  2446. print "r$log_entry->{revision}" unless $::_q > 1;
  2447. if (defined $log_entry->{svm_revision}) {
  2448. print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
  2449. $self->rev_map_set($log_entry->{svm_revision}, $commit,
  2450. 0, $self->svm_uuid);
  2451. }
  2452. print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
  2453. if (--$_gc_nr == 0) {
  2454. $_gc_nr = $_gc_period;
  2455. gc();
  2456. }
  2457. return $commit;
  2458. }
  2459. sub match_paths {
  2460. my ($self, $paths, $r) = @_;
  2461. return 1 if $self->{path} eq '';
  2462. if (my $path = $paths->{"/$self->{path}"}) {
  2463. return ($path->{action} eq 'D') ? 0 : 1;
  2464. }
  2465. $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
  2466. if (grep /$self->{path_regex}/, keys %$paths) {
  2467. return 1;
  2468. }
  2469. my $c = '';
  2470. foreach (split m#/#, $self->{path}) {
  2471. $c .= "/$_";
  2472. next unless ($paths->{$c} &&
  2473. ($paths->{$c}->{action} =~ /^[AR]$/));
  2474. if ($self->ra->check_path($self->{path}, $r) ==
  2475. $SVN::Node::dir) {
  2476. return 1;
  2477. }
  2478. }
  2479. return 0;
  2480. }
  2481. sub find_parent_branch {
  2482. my ($self, $paths, $rev) = @_;
  2483. return undef unless $self->follow_parent;
  2484. unless (defined $paths) {
  2485. my $err_handler = $SVN::Error::handler;
  2486. $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
  2487. $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
  2488. sub { $paths = $_[0] });
  2489. $SVN::Error::handler = $err_handler;
  2490. }
  2491. return undef unless defined $paths;
  2492. # look for a parent from another branch:
  2493. my @b_path_components = split m#/#, $self->{path};
  2494. my @a_path_components;
  2495. my $i;
  2496. while (@b_path_components) {
  2497. $i = $paths->{'/'.join('/', @b_path_components)};
  2498. last if $i && defined $i->{copyfrom_path};
  2499. unshift(@a_path_components, pop(@b_path_components));
  2500. }
  2501. return undef unless defined $i && defined $i->{copyfrom_path};
  2502. my $branch_from = $i->{copyfrom_path};
  2503. if (@a_path_components) {
  2504. print STDERR "branch_from: $branch_from => ";
  2505. $branch_from .= '/'.join('/', @a_path_components);
  2506. print STDERR $branch_from, "\n";
  2507. }
  2508. my $r = $i->{copyfrom_rev};
  2509. my $repos_root = $self->ra->{repos_root};
  2510. my $url = $self->ra->{url};
  2511. my $new_url = $url . $branch_from;
  2512. print STDERR "Found possible branch point: ",
  2513. "$new_url => ", $self->full_url, ", $r\n"
  2514. unless $::_q > 1;
  2515. $branch_from =~ s#^/##;
  2516. my $gs = $self->other_gs($new_url, $url,
  2517. $branch_from, $r, $self->{ref_id});
  2518. my ($r0, $parent) = $gs->find_rev_before($r, 1);
  2519. {
  2520. my ($base, $head);
  2521. if (!defined $r0 || !defined $parent) {
  2522. ($base, $head) = parse_revision_argument(0, $r);
  2523. } else {
  2524. if ($r0 < $r) {
  2525. $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
  2526. 0, 1, sub { $base = $_[1] - 1 });
  2527. }
  2528. }
  2529. if (defined $base && $base <= $r) {
  2530. $gs->fetch($base, $r);
  2531. }
  2532. ($r0, $parent) = $gs->find_rev_before($r, 1);
  2533. }
  2534. if (defined $r0 && defined $parent) {
  2535. print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
  2536. unless $::_q > 1;
  2537. my $ed;
  2538. if ($self->ra->can_do_switch) {
  2539. $self->assert_index_clean($parent);
  2540. print STDERR "Following parent with do_switch\n"
  2541. unless $::_q > 1;
  2542. # do_switch works with svn/trunk >= r22312, but that
  2543. # is not included with SVN 1.4.3 (the latest version
  2544. # at the moment), so we can't rely on it
  2545. $self->{last_rev} = $r0;
  2546. $self->{last_commit} = $parent;
  2547. $ed = SVN::Git::Fetcher->new($self, $gs->{path});
  2548. $gs->ra->gs_do_switch($r0, $rev, $gs,
  2549. $self->full_url, $ed)
  2550. or die "SVN connection failed somewhere...\n";
  2551. } elsif ($self->ra->trees_match($new_url, $r0,
  2552. $self->full_url, $rev)) {
  2553. print STDERR "Trees match:\n",
  2554. " $new_url\@$r0\n",
  2555. " ${\$self->full_url}\@$rev\n",
  2556. "Following parent with no changes\n"
  2557. unless $::_q > 1;
  2558. $self->tmp_index_do(sub {
  2559. command_noisy('read-tree', $parent);
  2560. });
  2561. $self->{last_commit} = $parent;
  2562. } else {
  2563. print STDERR "Following parent with do_update\n"
  2564. unless $::_q > 1;
  2565. $ed = SVN::Git::Fetcher->new($self);
  2566. $self->ra->gs_do_update($rev, $rev, $self, $ed)
  2567. or die "SVN connection failed somewhere...\n";
  2568. }
  2569. print STDERR "Successfully followed parent\n" unless $::_q > 1;
  2570. return $self->make_log_entry($rev, [$parent], $ed);
  2571. }
  2572. return undef;
  2573. }
  2574. sub do_fetch {
  2575. my ($self, $paths, $rev) = @_;
  2576. my $ed;
  2577. my ($last_rev, @parents);
  2578. if (my $lc = $self->last_commit) {
  2579. # we can have a branch that was deleted, then re-added
  2580. # under the same name but copied from another path, in
  2581. # which case we'll have multiple parents (we don't
  2582. # want to break the original ref, nor lose copypath info):
  2583. if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
  2584. push @{$log_entry->{parents}}, $lc;
  2585. return $log_entry;
  2586. }
  2587. $ed = SVN::Git::Fetcher->new($self);
  2588. $last_rev = $self->{last_rev};
  2589. $ed->{c} = $lc;
  2590. @parents = ($lc);
  2591. } else {
  2592. $last_rev = $rev;
  2593. if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
  2594. return $log_entry;
  2595. }
  2596. $ed = SVN::Git::Fetcher->new($self);
  2597. }
  2598. unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
  2599. die "SVN connection failed somewhere...\n";
  2600. }
  2601. $self->make_log_entry($rev, \@parents, $ed);
  2602. }
  2603. sub mkemptydirs {
  2604. my ($self, $r) = @_;
  2605. sub scan {
  2606. my ($r, $empty_dirs, $line) = @_;
  2607. if (defined $r && $line =~ /^r(\d+)$/) {
  2608. return 0 if $1 > $r;
  2609. } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
  2610. $empty_dirs->{$1} = 1;
  2611. } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
  2612. my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
  2613. delete @$empty_dirs{@d};
  2614. }
  2615. 1; # continue
  2616. };
  2617. my %empty_dirs = ();
  2618. my $gz_file = "$self->{dir}/unhandled.log.gz";
  2619. if (-f $gz_file) {
  2620. if (!$can_compress) {
  2621. warn "Compress::Zlib could not be found; ",
  2622. "empty directories in $gz_file will not be read\n";
  2623. } else {
  2624. my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
  2625. die "Unable to open $gz_file: $!\n";
  2626. my $line;
  2627. while ($gz->gzreadline($line) > 0) {
  2628. scan($r, \%empty_dirs, $line) or last;
  2629. }
  2630. $gz->gzclose;
  2631. }
  2632. }
  2633. if (open my $fh, '<', "$self->{dir}/unhandled.log") {
  2634. binmode $fh or croak "binmode: $!";
  2635. while (<$fh>) {
  2636. scan($r, \%empty_dirs, $_) or last;
  2637. }
  2638. close $fh;
  2639. }
  2640. my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
  2641. foreach my $d (sort keys %empty_dirs) {
  2642. $d = uri_decode($d);
  2643. $d =~ s/$strip//;
  2644. next unless length($d);
  2645. next if -d $d;
  2646. if (-e $d) {
  2647. warn "$d exists but is not a directory\n";
  2648. } else {
  2649. print "creating empty directory: $d\n";
  2650. mkpath([$d]);
  2651. }
  2652. }
  2653. }
  2654. sub get_untracked {
  2655. my ($self, $ed) = @_;
  2656. my @out;
  2657. my $h = $ed->{empty};
  2658. foreach (sort keys %$h) {
  2659. my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
  2660. push @out, " $act: " . uri_encode($_);
  2661. warn "W: $act: $_\n";
  2662. }
  2663. foreach my $t (qw/dir_prop file_prop/) {
  2664. $h = $ed->{$t} or next;
  2665. foreach my $path (sort keys %$h) {
  2666. my $ppath = $path eq '' ? '.' : $path;
  2667. foreach my $prop (sort keys %{$h->{$path}}) {
  2668. next if $SKIP_PROP{$prop};
  2669. my $v = $h->{$path}->{$prop};
  2670. my $t_ppath_prop = "$t: " .
  2671. uri_encode($ppath) . ' ' .
  2672. uri_encode($prop);
  2673. if (defined $v) {
  2674. push @out, " +$t_ppath_prop " .
  2675. uri_encode($v);
  2676. } else {
  2677. push @out, " -$t_ppath_prop";
  2678. }
  2679. }
  2680. }
  2681. }
  2682. foreach my $t (qw/absent_file absent_directory/) {
  2683. $h = $ed->{$t} or next;
  2684. foreach my $parent (sort keys %$h) {
  2685. foreach my $path (sort @{$h->{$parent}}) {
  2686. push @out, " $t: " .
  2687. uri_encode("$parent/$path");
  2688. warn "W: $t: $parent/$path ",
  2689. "Insufficient permissions?\n";
  2690. }
  2691. }
  2692. }
  2693. \@out;
  2694. }
  2695. # parse_svn_date(DATE)
  2696. # --------------------
  2697. # Given a date (in UTC) from Subversion, return a string in the format
  2698. # "<TZ Offset> <local date/time>" that Git will use.
  2699. #
  2700. # By default the parsed date will be in UTC; if $Git::SVN::_localtime
  2701. # is true we'll convert it to the local timezone instead.
  2702. sub parse_svn_date {
  2703. my $date = shift || return '+0000 1970-01-01 00:00:00';
  2704. my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
  2705. (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
  2706. croak "Unable to parse date: $date\n";
  2707. my $parsed_date; # Set next.
  2708. if ($Git::SVN::_localtime) {
  2709. # Translate the Subversion datetime to an epoch time.
  2710. # Begin by switching ourselves to $date's timezone, UTC.
  2711. my $old_env_TZ = $ENV{TZ};
  2712. $ENV{TZ} = 'UTC';
  2713. my $epoch_in_UTC =
  2714. POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
  2715. # Determine our local timezone (including DST) at the
  2716. # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
  2717. # value of TZ, if any, at the time we were run.
  2718. if (defined $Git::SVN::Log::TZ) {
  2719. $ENV{TZ} = $Git::SVN::Log::TZ;
  2720. } else {
  2721. delete $ENV{TZ};
  2722. }
  2723. my $our_TZ =
  2724. POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
  2725. # This converts $epoch_in_UTC into our local timezone.
  2726. my ($sec, $min, $hour, $mday, $mon, $year,
  2727. $wday, $yday, $isdst) = localtime($epoch_in_UTC);
  2728. $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
  2729. $our_TZ, $year + 1900, $mon + 1,
  2730. $mday, $hour, $min, $sec);
  2731. # Reset us to the timezone in effect when we entered
  2732. # this routine.
  2733. if (defined $old_env_TZ) {
  2734. $ENV{TZ} = $old_env_TZ;
  2735. } else {
  2736. delete $ENV{TZ};
  2737. }
  2738. } else {
  2739. $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
  2740. }
  2741. return $parsed_date;
  2742. }
  2743. sub other_gs {
  2744. my ($self, $new_url, $url,
  2745. $branch_from, $r, $old_ref_id) = @_;
  2746. my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
  2747. unless ($gs) {
  2748. my $ref_id = $old_ref_id;
  2749. $ref_id =~ s/\@\d+-*$//;
  2750. $ref_id .= "\@$r";
  2751. # just grow a tail if we're not unique enough :x
  2752. $ref_id .= '-' while find_ref($ref_id);
  2753. my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
  2754. if ($u =~ s#^\Q$url\E(/|$)##) {
  2755. $p = $u;
  2756. $u = $url;
  2757. $repo_id = $self->{repo_id};
  2758. }
  2759. while (1) {
  2760. # It is possible to tag two different subdirectories at
  2761. # the same revision. If the url for an existing ref
  2762. # does not match, we must either find a ref with a
  2763. # matching url or create a new ref by growing a tail.
  2764. $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
  2765. my (undef, $max_commit) = $gs->rev_map_max(1);
  2766. last if (!$max_commit);
  2767. my ($url) = ::cmt_metadata($max_commit);
  2768. last if ($url eq $gs->full_url);
  2769. $ref_id .= '-';
  2770. }
  2771. print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
  2772. }
  2773. $gs
  2774. }
  2775. sub call_authors_prog {
  2776. my ($orig_author) = @_;
  2777. $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
  2778. my $author = `$::_authors_prog $orig_author`;
  2779. if ($? != 0) {
  2780. die "$::_authors_prog failed with exit code $?\n"
  2781. }
  2782. if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
  2783. my ($name, $email) = ($1, $2);
  2784. $email = undef if length $2 == 0;
  2785. return [$name, $email];
  2786. } else {
  2787. die "Author: $orig_author: $::_authors_prog returned "
  2788. . "invalid author format: $author\n";
  2789. }
  2790. }
  2791. sub check_author {
  2792. my ($author) = @_;
  2793. if (!defined $author || length $author == 0) {
  2794. $author = '(no author)';
  2795. }
  2796. if (!defined $::users{$author}) {
  2797. if (defined $::_authors_prog) {
  2798. $::users{$author} = call_authors_prog($author);
  2799. } elsif (defined $::_authors) {
  2800. die "Author: $author not defined in $::_authors file\n";
  2801. }
  2802. }
  2803. $author;
  2804. }
  2805. sub find_extra_svk_parents {
  2806. my ($self, $ed, $tickets, $parents) = @_;
  2807. # aha! svk:merge property changed...
  2808. my @tickets = split "\n", $tickets;
  2809. my @known_parents;
  2810. for my $ticket ( @tickets ) {
  2811. my ($uuid, $path, $rev) = split /:/, $ticket;
  2812. if ( $uuid eq $self->ra_uuid ) {
  2813. my $url = $self->{url};
  2814. my $repos_root = $url;
  2815. my $branch_from = $path;
  2816. $branch_from =~ s{^/}{};
  2817. my $gs = $self->other_gs($repos_root."/".$branch_from,
  2818. $url,
  2819. $branch_from,
  2820. $rev,
  2821. $self->{ref_id});
  2822. if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
  2823. # wahey! we found it, but it might be
  2824. # an old one (!)
  2825. push @known_parents, [ $rev, $commit ];
  2826. }
  2827. }
  2828. }
  2829. # Ordering matters; highest-numbered commit merge tickets
  2830. # first, as they may account for later merge ticket additions
  2831. # or changes.
  2832. @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
  2833. for my $parent ( @known_parents ) {
  2834. my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
  2835. my ($msg_fh, $ctx) = command_output_pipe(@cmd);
  2836. my $new;
  2837. while ( <$msg_fh> ) {
  2838. $new=1;last;
  2839. }
  2840. command_close_pipe($msg_fh, $ctx);
  2841. if ( $new ) {
  2842. print STDERR
  2843. "Found merge parent (svk:merge ticket): $parent\n";
  2844. push @$parents, $parent;
  2845. }
  2846. }
  2847. }
  2848. sub lookup_svn_merge {
  2849. my $uuid = shift;
  2850. my $url = shift;
  2851. my $merge = shift;
  2852. my ($source, $revs) = split ":", $merge;
  2853. my $path = $source;
  2854. $path =~ s{^/}{};
  2855. my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
  2856. if ( !$gs ) {
  2857. warn "Couldn't find revmap for $url$source\n";
  2858. return;
  2859. }
  2860. my @ranges = split ",", $revs;
  2861. my ($tip, $tip_commit);
  2862. my @merged_commit_ranges;
  2863. # find the tip
  2864. for my $range ( @ranges ) {
  2865. my ($bottom, $top) = split "-", $range;
  2866. $top ||= $bottom;
  2867. my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
  2868. my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
  2869. unless ($top_commit and $bottom_commit) {
  2870. warn "W:unknown path/rev in svn:mergeinfo "
  2871. ."dirprop: $source:$range\n";
  2872. next;
  2873. }
  2874. if (scalar(command('rev-parse', "$bottom_commit^@"))) {
  2875. push @merged_commit_ranges,
  2876. "$bottom_commit^..$top_commit";
  2877. } else {
  2878. push @merged_commit_ranges, "$top_commit";
  2879. }
  2880. if ( !defined $tip or $top > $tip ) {
  2881. $tip = $top;
  2882. $tip_commit = $top_commit;
  2883. }
  2884. }
  2885. return ($tip_commit, @merged_commit_ranges);
  2886. }
  2887. sub _rev_list {
  2888. my ($msg_fh, $ctx) = command_output_pipe(
  2889. "rev-list", @_,
  2890. );
  2891. my @rv;
  2892. while ( <$msg_fh> ) {
  2893. chomp;
  2894. push @rv, $_;
  2895. }
  2896. command_close_pipe($msg_fh, $ctx);
  2897. @rv;
  2898. }
  2899. sub check_cherry_pick {
  2900. my $base = shift;
  2901. my $tip = shift;
  2902. my $parents = shift;
  2903. my @ranges = @_;
  2904. my %commits = map { $_ => 1 }
  2905. _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
  2906. for my $range ( @ranges ) {
  2907. delete @commits{_rev_list($range, "--")};
  2908. }
  2909. for my $commit (keys %commits) {
  2910. if (has_no_changes($commit)) {
  2911. delete $commits{$commit};
  2912. }
  2913. }
  2914. return (keys %commits);
  2915. }
  2916. sub has_no_changes {
  2917. my $commit = shift;
  2918. my @revs = split / /, command_oneline(
  2919. qw(rev-list --parents -1 -m), $commit);
  2920. # Commits with no parents, e.g. the start of a partial branch,
  2921. # have changes by definition.
  2922. return 1 if (@revs < 2);
  2923. # Commits with multiple parents, e.g a merge, have no changes
  2924. # by definition.
  2925. return 0 if (@revs > 2);
  2926. return (command_oneline("rev-parse", "$commit^{tree}") eq
  2927. command_oneline("rev-parse", "$commit~1^{tree}"));
  2928. }
  2929. # The GIT_DIR environment variable is not always set until after the command
  2930. # line arguments are processed, so we can't memoize in a BEGIN block.
  2931. {
  2932. my $memoized = 0;
  2933. sub memoize_svn_mergeinfo_functions {
  2934. return if $memoized;
  2935. $memoized = 1;
  2936. my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
  2937. mkpath([$cache_path]) unless -d $cache_path;
  2938. tie my %lookup_svn_merge_cache => 'Memoize::Storable',
  2939. "$cache_path/lookup_svn_merge.db", 'nstore';
  2940. memoize 'lookup_svn_merge',
  2941. SCALAR_CACHE => 'FAULT',
  2942. LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
  2943. ;
  2944. tie my %check_cherry_pick_cache => 'Memoize::Storable',
  2945. "$cache_path/check_cherry_pick.db", 'nstore';
  2946. memoize 'check_cherry_pick',
  2947. SCALAR_CACHE => 'FAULT',
  2948. LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
  2949. ;
  2950. tie my %has_no_changes_cache => 'Memoize::Storable',
  2951. "$cache_path/has_no_changes.db", 'nstore';
  2952. memoize 'has_no_changes',
  2953. SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
  2954. LIST_CACHE => 'FAULT',
  2955. ;
  2956. }
  2957. sub unmemoize_svn_mergeinfo_functions {
  2958. return if not $memoized;
  2959. $memoized = 0;
  2960. Memoize::unmemoize 'lookup_svn_merge';
  2961. Memoize::unmemoize 'check_cherry_pick';
  2962. Memoize::unmemoize 'has_no_changes';
  2963. }
  2964. Memoize::memoize 'Git::SVN::repos_root';
  2965. }
  2966. END {
  2967. # Force cache writeout explicitly instead of waiting for
  2968. # global destruction to avoid segfault in Storable:
  2969. # http://rt.cpan.org/Public/Bug/Display.html?id=36087
  2970. unmemoize_svn_mergeinfo_functions();
  2971. }
  2972. sub parents_exclude {
  2973. my $parents = shift;
  2974. my @commits = @_;
  2975. return unless @commits;
  2976. my @excluded;
  2977. my $excluded;
  2978. do {
  2979. my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
  2980. $excluded = command_oneline(@cmd);
  2981. if ( $excluded ) {
  2982. my @new;
  2983. my $found;
  2984. for my $commit ( @commits ) {
  2985. if ( $commit eq $excluded ) {
  2986. push @excluded, $commit;
  2987. $found++;
  2988. last;
  2989. }
  2990. else {
  2991. push @new, $commit;
  2992. }
  2993. }
  2994. die "saw commit '$excluded' in rev-list output, "
  2995. ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
  2996. unless $found;
  2997. @commits = @new;
  2998. }
  2999. }
  3000. while ($excluded and @commits);
  3001. return @excluded;
  3002. }
  3003. # note: this function should only be called if the various dirprops
  3004. # have actually changed
  3005. sub find_extra_svn_parents {
  3006. my ($self, $ed, $mergeinfo, $parents) = @_;
  3007. # aha! svk:merge property changed...
  3008. memoize_svn_mergeinfo_functions();
  3009. # We first search for merged tips which are not in our
  3010. # history. Then, we figure out which git revisions are in
  3011. # that tip, but not this revision. If all of those revisions
  3012. # are now marked as merge, we can add the tip as a parent.
  3013. my @merges = split "\n", $mergeinfo;
  3014. my @merge_tips;
  3015. my $url = $self->{url};
  3016. my $uuid = $self->ra_uuid;
  3017. my %ranges;
  3018. for my $merge ( @merges ) {
  3019. my ($tip_commit, @ranges) =
  3020. lookup_svn_merge( $uuid, $url, $merge );
  3021. unless (!$tip_commit or
  3022. grep { $_ eq $tip_commit } @$parents ) {
  3023. push @merge_tips, $tip_commit;
  3024. $ranges{$tip_commit} = \@ranges;
  3025. } else {
  3026. push @merge_tips, undef;
  3027. }
  3028. }
  3029. my %excluded = map { $_ => 1 }
  3030. parents_exclude($parents, grep { defined } @merge_tips);
  3031. # check merge tips for new parents
  3032. my @new_parents;
  3033. for my $merge_tip ( @merge_tips ) {
  3034. my $spec = shift @merges;
  3035. next unless $merge_tip and $excluded{$merge_tip};
  3036. my $ranges = $ranges{$merge_tip};
  3037. # check out 'new' tips
  3038. my $merge_base;
  3039. eval {
  3040. $merge_base = command_oneline(
  3041. "merge-base",
  3042. @$parents, $merge_tip,
  3043. );
  3044. };
  3045. if ($@) {
  3046. die "An error occurred during merge-base"
  3047. unless $@->isa("Git::Error::Command");
  3048. warn "W: Cannot find common ancestor between ".
  3049. "@$parents and $merge_tip. Ignoring merge info.\n";
  3050. next;
  3051. }
  3052. # double check that there are no missing non-merge commits
  3053. my (@incomplete) = check_cherry_pick(
  3054. $merge_base, $merge_tip,
  3055. $parents,
  3056. @$ranges,
  3057. );
  3058. if ( @incomplete ) {
  3059. warn "W:svn cherry-pick ignored ($spec) - missing "
  3060. .@incomplete." commit(s) (eg $incomplete[0])\n";
  3061. } else {
  3062. warn
  3063. "Found merge parent (svn:mergeinfo prop): ",
  3064. $merge_tip, "\n";
  3065. push @new_parents, $merge_tip;
  3066. }
  3067. }
  3068. # cater for merges which merge commits from multiple branches
  3069. if ( @new_parents > 1 ) {
  3070. for ( my $i = 0; $i <= $#new_parents; $i++ ) {
  3071. for ( my $j = 0; $j <= $#new_parents; $j++ ) {
  3072. next if $i == $j;
  3073. next unless $new_parents[$i];
  3074. next unless $new_parents[$j];
  3075. my $revs = command_oneline(
  3076. "rev-list", "-1",
  3077. "$new_parents[$i]..$new_parents[$j]",
  3078. );
  3079. if ( !$revs ) {
  3080. undef($new_parents[$j]);
  3081. }
  3082. }
  3083. }
  3084. }
  3085. push @$parents, grep { defined } @new_parents;
  3086. }
  3087. sub make_log_entry {
  3088. my ($self, $rev, $parents, $ed) = @_;
  3089. my $untracked = $self->get_untracked($ed);
  3090. my @parents = @$parents;
  3091. my $ps = $ed->{path_strip} || "";
  3092. for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
  3093. my $props = $ed->{dir_prop}{$path};
  3094. if ( $props->{"svk:merge"} ) {
  3095. $self->find_extra_svk_parents
  3096. ($ed, $props->{"svk:merge"}, \@parents);
  3097. }
  3098. if ( $props->{"svn:mergeinfo"} ) {
  3099. $self->find_extra_svn_parents
  3100. ($ed,
  3101. $props->{"svn:mergeinfo"},
  3102. \@parents);
  3103. }
  3104. }
  3105. open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
  3106. print $un "r$rev\n" or croak $!;
  3107. print $un $_, "\n" foreach @$untracked;
  3108. my %log_entry = ( parents => \@parents, revision => $rev,
  3109. log => '');
  3110. my $headrev;
  3111. my $logged = delete $self->{logged_rev_props};
  3112. if (!$logged || $self->{-want_revprops}) {
  3113. my $rp = $self->ra->rev_proplist($rev);
  3114. foreach (sort keys %$rp) {
  3115. my $v = $rp->{$_};
  3116. if (/^svn:(author|date|log)$/) {
  3117. $log_entry{$1} = $v;
  3118. } elsif ($_ eq 'svm:headrev') {
  3119. $headrev = $v;
  3120. } else {
  3121. print $un " rev_prop: ", uri_encode($_), ' ',
  3122. uri_encode($v), "\n";
  3123. }
  3124. }
  3125. } else {
  3126. map { $log_entry{$_} = $logged->{$_} } keys %$logged;
  3127. }
  3128. close $un or croak $!;
  3129. $log_entry{date} = parse_svn_date($log_entry{date});
  3130. $log_entry{log} .= "\n";
  3131. my $author = $log_entry{author} = check_author($log_entry{author});
  3132. my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
  3133. : ($author, undef);
  3134. my ($commit_name, $commit_email) = ($name, $email);
  3135. if ($_use_log_author) {
  3136. my $name_field;
  3137. if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
  3138. $name_field = $1;
  3139. } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
  3140. $name_field = $1;
  3141. }
  3142. if (!defined $name_field) {
  3143. if (!defined $email) {
  3144. $email = $name;
  3145. }
  3146. } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
  3147. ($name, $email) = ($1, $2);
  3148. } elsif ($name_field =~ /(.*)@/) {
  3149. ($name, $email) = ($1, $name_field);
  3150. } else {
  3151. ($name, $email) = ($name_field, $name_field);
  3152. }
  3153. }
  3154. if (defined $headrev && $self->use_svm_props) {
  3155. if ($self->rewrite_root) {
  3156. die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
  3157. "options set!\n";
  3158. }
  3159. if ($self->rewrite_uuid) {
  3160. die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
  3161. "options set!\n";
  3162. }
  3163. my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
  3164. # we don't want "SVM: initializing mirror for junk" ...
  3165. return undef if $r == 0;
  3166. my $svm = $self->svm;
  3167. if ($uuid ne $svm->{uuid}) {
  3168. die "UUID mismatch on SVM path:\n",
  3169. "expected: $svm->{uuid}\n",
  3170. " got: $uuid\n";
  3171. }
  3172. my $full_url = $self->full_url;
  3173. $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
  3174. die "Failed to replace '$svm->{replace}' with ",
  3175. "'$svm->{source}' in $full_url\n";
  3176. # throw away username for storing in records
  3177. remove_username($full_url);
  3178. $log_entry{metadata} = "$full_url\@$r $uuid";
  3179. $log_entry{svm_revision} = $r;
  3180. $email ||= "$author\@$uuid";
  3181. $commit_email ||= "$author\@$uuid";
  3182. } elsif ($self->use_svnsync_props) {
  3183. my $full_url = $self->svnsync->{url};
  3184. $full_url .= "/$self->{path}" if length $self->{path};
  3185. remove_username($full_url);
  3186. my $uuid = $self->svnsync->{uuid};
  3187. $log_entry{metadata} = "$full_url\@$rev $uuid";
  3188. $email ||= "$author\@$uuid";
  3189. $commit_email ||= "$author\@$uuid";
  3190. } else {
  3191. my $url = $self->metadata_url;
  3192. remove_username($url);
  3193. my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
  3194. $log_entry{metadata} = "$url\@$rev " . $uuid;
  3195. $email ||= "$author\@" . $uuid;
  3196. $commit_email ||= "$author\@" . $uuid;
  3197. }
  3198. $log_entry{name} = $name;
  3199. $log_entry{email} = $email;
  3200. $log_entry{commit_name} = $commit_name;
  3201. $log_entry{commit_email} = $commit_email;
  3202. \%log_entry;
  3203. }
  3204. sub fetch {
  3205. my ($self, $min_rev, $max_rev, @parents) = @_;
  3206. my ($last_rev, $last_commit) = $self->last_rev_commit;
  3207. my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
  3208. $self->ra->gs_fetch_loop_common($base, $head, [$self]);
  3209. }
  3210. sub set_tree_cb {
  3211. my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
  3212. $self->{inject_parents} = { $rev => $tree };
  3213. $self->fetch(undef, undef);
  3214. }
  3215. sub set_tree {
  3216. my ($self, $tree) = (shift, shift);
  3217. my $log_entry = ::get_commit_entry($tree);
  3218. unless ($self->{last_rev}) {
  3219. ::fatal("Must have an existing revision to commit");
  3220. }
  3221. my %ed_opts = ( r => $self->{last_rev},
  3222. log => $log_entry->{log},
  3223. ra => $self->ra,
  3224. tree_a => $self->{last_commit},
  3225. tree_b => $tree,
  3226. editor_cb => sub {
  3227. $self->set_tree_cb($log_entry, $tree, @_) },
  3228. svn_path => $self->{path} );
  3229. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  3230. print "No changes\nr$self->{last_rev} = $tree\n";
  3231. }
  3232. }
  3233. sub rebuild_from_rev_db {
  3234. my ($self, $path) = @_;
  3235. my $r = -1;
  3236. open my $fh, '<', $path or croak "open: $!";
  3237. binmode $fh or croak "binmode: $!";
  3238. while (<$fh>) {
  3239. length($_) == 41 or croak "inconsistent size in ($_) != 41";
  3240. chomp($_);
  3241. ++$r;
  3242. next if $_ eq ('0' x 40);
  3243. $self->rev_map_set($r, $_);
  3244. print "r$r = $_\n";
  3245. }
  3246. close $fh or croak "close: $!";
  3247. unlink $path or croak "unlink: $!";
  3248. }
  3249. sub rebuild {
  3250. my ($self) = @_;
  3251. my $map_path = $self->map_path;
  3252. my $partial = (-e $map_path && ! -z $map_path);
  3253. return unless ::verify_ref($self->refname.'^0');
  3254. if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
  3255. my $rev_db = $self->rev_db_path;
  3256. $self->rebuild_from_rev_db($rev_db);
  3257. if ($self->use_svm_props) {
  3258. my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
  3259. $self->rebuild_from_rev_db($svm_rev_db);
  3260. }
  3261. $self->unlink_rev_db_symlink;
  3262. return;
  3263. }
  3264. print "Rebuilding $map_path ...\n" if (!$partial);
  3265. my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
  3266. (undef, undef));
  3267. my ($log, $ctx) =
  3268. command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
  3269. ($head ? "$head.." : "") . $self->refname,
  3270. '--');
  3271. my $metadata_url = $self->metadata_url;
  3272. remove_username($metadata_url);
  3273. my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
  3274. my $c;
  3275. while (<$log>) {
  3276. if ( m{^commit ($::sha1)$} ) {
  3277. $c = $1;
  3278. next;
  3279. }
  3280. next unless s{^\s*(git-svn-id:)}{$1};
  3281. my ($url, $rev, $uuid) = ::extract_metadata($_);
  3282. remove_username($url);
  3283. # ignore merges (from set-tree)
  3284. next if (!defined $rev || !$uuid);
  3285. # if we merged or otherwise started elsewhere, this is
  3286. # how we break out of it
  3287. if (($uuid ne $svn_uuid) ||
  3288. ($metadata_url && $url && ($url ne $metadata_url))) {
  3289. next;
  3290. }
  3291. if ($partial && $head) {
  3292. print "Partial-rebuilding $map_path ...\n";
  3293. print "Currently at $base_rev = $head\n";
  3294. $head = undef;
  3295. }
  3296. $self->rev_map_set($rev, $c);
  3297. print "r$rev = $c\n";
  3298. }
  3299. command_close_pipe($log, $ctx);
  3300. print "Done rebuilding $map_path\n" if (!$partial || !$head);
  3301. my $rev_db_path = $self->rev_db_path;
  3302. if (-f $self->rev_db_path) {
  3303. unlink $self->rev_db_path or croak "unlink: $!";
  3304. }
  3305. $self->unlink_rev_db_symlink;
  3306. }
  3307. # rev_map:
  3308. # Tie::File seems to be prone to offset errors if revisions get sparse,
  3309. # it's not that fast, either. Tie::File is also not in Perl 5.6. So
  3310. # one of my favorite modules is out :< Next up would be one of the DBM
  3311. # modules, but I'm not sure which is most portable...
  3312. #
  3313. # This is the replacement for the rev_db format, which was too big
  3314. # and inefficient for large repositories with a lot of sparse history
  3315. # (mainly tags)
  3316. #
  3317. # The format is this:
  3318. # - 24 bytes for every record,
  3319. # * 4 bytes for the integer representing an SVN revision number
  3320. # * 20 bytes representing the sha1 of a git commit
  3321. # - No empty padding records like the old format
  3322. # (except the last record, which can be overwritten)
  3323. # - new records are written append-only since SVN revision numbers
  3324. # increase monotonically
  3325. # - lookups on SVN revision number are done via a binary search
  3326. # - Piping the file to xxd -c24 is a good way of dumping it for
  3327. # viewing or editing (piped back through xxd -r), should the need
  3328. # ever arise.
  3329. # - The last record can be padding revision with an all-zero sha1
  3330. # This is used to optimize fetch performance when using multiple
  3331. # "fetch" directives in .git/config
  3332. #
  3333. # These files are disposable unless noMetadata or useSvmProps is set
  3334. sub _rev_map_set {
  3335. my ($fh, $rev, $commit) = @_;
  3336. binmode $fh or croak "binmode: $!";
  3337. my $size = (stat($fh))[7];
  3338. ($size % 24) == 0 or croak "inconsistent size: $size";
  3339. my $wr_offset = 0;
  3340. if ($size > 0) {
  3341. sysseek($fh, -24, SEEK_END) or croak "seek: $!";
  3342. my $read = sysread($fh, my $buf, 24) or croak "read: $!";
  3343. $read == 24 or croak "read only $read bytes (!= 24)";
  3344. my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
  3345. if ($last_commit eq ('0' x40)) {
  3346. if ($size >= 48) {
  3347. sysseek($fh, -48, SEEK_END) or croak "seek: $!";
  3348. $read = sysread($fh, $buf, 24) or
  3349. croak "read: $!";
  3350. $read == 24 or
  3351. croak "read only $read bytes (!= 24)";
  3352. ($last_rev, $last_commit) =
  3353. unpack(rev_map_fmt, $buf);
  3354. if ($last_commit eq ('0' x40)) {
  3355. croak "inconsistent .rev_map\n";
  3356. }
  3357. }
  3358. if ($last_rev >= $rev) {
  3359. croak "last_rev is higher!: $last_rev >= $rev";
  3360. }
  3361. $wr_offset = -24;
  3362. }
  3363. }
  3364. sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
  3365. syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
  3366. croak "write: $!";
  3367. }
  3368. sub _rev_map_reset {
  3369. my ($fh, $rev, $commit) = @_;
  3370. my $c = _rev_map_get($fh, $rev);
  3371. $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
  3372. my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
  3373. truncate $fh, $offset or croak "truncate: $!";
  3374. }
  3375. sub mkfile {
  3376. my ($path) = @_;
  3377. unless (-e $path) {
  3378. my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
  3379. mkpath([$dir]) unless -d $dir;
  3380. open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
  3381. close $fh or die "Couldn't close (create) $path: $!\n";
  3382. }
  3383. }
  3384. sub rev_map_set {
  3385. my ($self, $rev, $commit, $update_ref, $uuid) = @_;
  3386. defined $commit or die "missing arg3\n";
  3387. length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
  3388. my $db = $self->map_path($uuid);
  3389. my $db_lock = "$db.lock";
  3390. my $sig;
  3391. $update_ref ||= 0;
  3392. if ($update_ref) {
  3393. $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
  3394. $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
  3395. }
  3396. mkfile($db);
  3397. $LOCKFILES{$db_lock} = 1;
  3398. my $sync;
  3399. # both of these options make our .rev_db file very, very important
  3400. # and we can't afford to lose it because rebuild() won't work
  3401. if ($self->use_svm_props || $self->no_metadata) {
  3402. $sync = 1;
  3403. copy($db, $db_lock) or die "rev_map_set(@_): ",
  3404. "Failed to copy: ",
  3405. "$db => $db_lock ($!)\n";
  3406. } else {
  3407. rename $db, $db_lock or die "rev_map_set(@_): ",
  3408. "Failed to rename: ",
  3409. "$db => $db_lock ($!)\n";
  3410. }
  3411. sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
  3412. or croak "Couldn't open $db_lock: $!\n";
  3413. $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
  3414. _rev_map_set($fh, $rev, $commit);
  3415. if ($sync) {
  3416. $fh->flush or die "Couldn't flush $db_lock: $!\n";
  3417. $fh->sync or die "Couldn't sync $db_lock: $!\n";
  3418. }
  3419. close $fh or croak $!;
  3420. if ($update_ref) {
  3421. $_head = $self;
  3422. my $note = "";
  3423. $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
  3424. command_noisy('update-ref', '-m', "r$rev$note",
  3425. $self->refname, $commit);
  3426. }
  3427. rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
  3428. "$db_lock => $db ($!)\n";
  3429. delete $LOCKFILES{$db_lock};
  3430. if ($update_ref) {
  3431. $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
  3432. $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
  3433. kill $sig, $$ if defined $sig;
  3434. }
  3435. }
  3436. # If want_commit, this will return an array of (rev, commit) where
  3437. # commit _must_ be a valid commit in the archive.
  3438. # Otherwise, it'll return the max revision (whether or not the
  3439. # commit is valid or just a 0x40 placeholder).
  3440. sub rev_map_max {
  3441. my ($self, $want_commit) = @_;
  3442. $self->rebuild;
  3443. my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
  3444. $want_commit ? ($r, $c) : $r;
  3445. }
  3446. sub rev_map_max_norebuild {
  3447. my ($self, $want_commit) = @_;
  3448. my $map_path = $self->map_path;
  3449. stat $map_path or return $want_commit ? (0, undef) : 0;
  3450. sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
  3451. binmode $fh or croak "binmode: $!";
  3452. my $size = (stat($fh))[7];
  3453. ($size % 24) == 0 or croak "inconsistent size: $size";
  3454. if ($size == 0) {
  3455. close $fh or croak "close: $!";
  3456. return $want_commit ? (0, undef) : 0;
  3457. }
  3458. sysseek($fh, -24, SEEK_END) or croak "seek: $!";
  3459. sysread($fh, my $buf, 24) == 24 or croak "read: $!";
  3460. my ($r, $c) = unpack(rev_map_fmt, $buf);
  3461. if ($want_commit && $c eq ('0' x40)) {
  3462. if ($size < 48) {
  3463. return $want_commit ? (0, undef) : 0;
  3464. }
  3465. sysseek($fh, -48, SEEK_END) or croak "seek: $!";
  3466. sysread($fh, $buf, 24) == 24 or croak "read: $!";
  3467. ($r, $c) = unpack(rev_map_fmt, $buf);
  3468. if ($c eq ('0'x40)) {
  3469. croak "Penultimate record is all-zeroes in $map_path";
  3470. }
  3471. }
  3472. close $fh or croak "close: $!";
  3473. $want_commit ? ($r, $c) : $r;
  3474. }
  3475. sub rev_map_get {
  3476. my ($self, $rev, $uuid) = @_;
  3477. my $map_path = $self->map_path($uuid);
  3478. return undef unless -e $map_path;
  3479. sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
  3480. my $c = _rev_map_get($fh, $rev);
  3481. close($fh) or croak "close: $!";
  3482. $c
  3483. }
  3484. sub _rev_map_get {
  3485. my ($fh, $rev) = @_;
  3486. binmode $fh or croak "binmode: $!";
  3487. my $size = (stat($fh))[7];
  3488. ($size % 24) == 0 or croak "inconsistent size: $size";
  3489. if ($size == 0) {
  3490. return undef;
  3491. }
  3492. my ($l, $u) = (0, $size - 24);
  3493. my ($r, $c, $buf);
  3494. while ($l <= $u) {
  3495. my $i = int(($l/24 + $u/24) / 2) * 24;
  3496. sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
  3497. sysread($fh, my $buf, 24) == 24 or croak "read: $!";
  3498. my ($r, $c) = unpack(rev_map_fmt, $buf);
  3499. if ($r < $rev) {
  3500. $l = $i + 24;
  3501. } elsif ($r > $rev) {
  3502. $u = $i - 24;
  3503. } else { # $r == $rev
  3504. return $c eq ('0' x 40) ? undef : $c;
  3505. }
  3506. }
  3507. undef;
  3508. }
  3509. # Finds the first svn revision that exists on (if $eq_ok is true) or
  3510. # before $rev for the current branch. It will not search any lower
  3511. # than $min_rev. Returns the git commit hash and svn revision number
  3512. # if found, else (undef, undef).
  3513. sub find_rev_before {
  3514. my ($self, $rev, $eq_ok, $min_rev) = @_;
  3515. --$rev unless $eq_ok;
  3516. $min_rev ||= 1;
  3517. my $max_rev = $self->rev_map_max;
  3518. $rev = $max_rev if ($rev > $max_rev);
  3519. while ($rev >= $min_rev) {
  3520. if (my $c = $self->rev_map_get($rev)) {
  3521. return ($rev, $c);
  3522. }
  3523. --$rev;
  3524. }
  3525. return (undef, undef);
  3526. }
  3527. # Finds the first svn revision that exists on (if $eq_ok is true) or
  3528. # after $rev for the current branch. It will not search any higher
  3529. # than $max_rev. Returns the git commit hash and svn revision number
  3530. # if found, else (undef, undef).
  3531. sub find_rev_after {
  3532. my ($self, $rev, $eq_ok, $max_rev) = @_;
  3533. ++$rev unless $eq_ok;
  3534. $max_rev ||= $self->rev_map_max;
  3535. while ($rev <= $max_rev) {
  3536. if (my $c = $self->rev_map_get($rev)) {
  3537. return ($rev, $c);
  3538. }
  3539. ++$rev;
  3540. }
  3541. return (undef, undef);
  3542. }
  3543. sub _new {
  3544. my ($class, $repo_id, $ref_id, $path) = @_;
  3545. unless (defined $repo_id && length $repo_id) {
  3546. $repo_id = $Git::SVN::default_repo_id;
  3547. }
  3548. unless (defined $ref_id && length $ref_id) {
  3549. $_prefix = '' unless defined($_prefix);
  3550. $_[2] = $ref_id =
  3551. "refs/remotes/$_prefix$Git::SVN::default_ref_id";
  3552. }
  3553. $_[1] = $repo_id;
  3554. my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
  3555. # Older repos imported by us used $GIT_DIR/svn/foo instead of
  3556. # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
  3557. if ($ref_id =~ m{^refs/remotes/(.*)}) {
  3558. my $old_dir = "$ENV{GIT_DIR}/svn/$1";
  3559. if (-d $old_dir && ! -d $dir) {
  3560. $dir = $old_dir;
  3561. }
  3562. }
  3563. $_[3] = $path = '' unless (defined $path);
  3564. mkpath([$dir]);
  3565. bless {
  3566. ref_id => $ref_id, dir => $dir, index => "$dir/index",
  3567. path => $path, config => "$ENV{GIT_DIR}/svn/config",
  3568. map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
  3569. }
  3570. # for read-only access of old .rev_db formats
  3571. sub unlink_rev_db_symlink {
  3572. my ($self) = @_;
  3573. my $link = $self->rev_db_path;
  3574. $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
  3575. if (-l $link) {
  3576. unlink $link or croak "unlink: $link failed!";
  3577. }
  3578. }
  3579. sub rev_db_path {
  3580. my ($self, $uuid) = @_;
  3581. my $db_path = $self->map_path($uuid);
  3582. $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
  3583. or croak "map_path: $db_path does not contain '/.rev_map.' !";
  3584. $db_path;
  3585. }
  3586. # the new replacement for .rev_db
  3587. sub map_path {
  3588. my ($self, $uuid) = @_;
  3589. $uuid ||= $self->ra_uuid;
  3590. "$self->{map_root}.$uuid";
  3591. }
  3592. sub uri_encode {
  3593. my ($f) = @_;
  3594. $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
  3595. $f
  3596. }
  3597. sub uri_decode {
  3598. my ($f) = @_;
  3599. $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
  3600. $f
  3601. }
  3602. sub remove_username {
  3603. $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
  3604. }
  3605. package Git::SVN::Prompt;
  3606. use strict;
  3607. use warnings;
  3608. require SVN::Core;
  3609. use vars qw/$_no_auth_cache $_username/;
  3610. sub simple {
  3611. my ($cred, $realm, $default_username, $may_save, $pool) = @_;
  3612. $may_save = undef if $_no_auth_cache;
  3613. $default_username = $_username if defined $_username;
  3614. if (defined $default_username && length $default_username) {
  3615. if (defined $realm && length $realm) {
  3616. print STDERR "Authentication realm: $realm\n";
  3617. STDERR->flush;
  3618. }
  3619. $cred->username($default_username);
  3620. } else {
  3621. username($cred, $realm, $may_save, $pool);
  3622. }
  3623. $cred->password(_read_password("Password for '" .
  3624. $cred->username . "': ", $realm));
  3625. $cred->may_save($may_save);
  3626. $SVN::_Core::SVN_NO_ERROR;
  3627. }
  3628. sub ssl_server_trust {
  3629. my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
  3630. $may_save = undef if $_no_auth_cache;
  3631. print STDERR "Error validating server certificate for '$realm':\n";
  3632. {
  3633. no warnings 'once';
  3634. # All variables SVN::Auth::SSL::* are used only once,
  3635. # so we're shutting up Perl warnings about this.
  3636. if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
  3637. print STDERR " - The certificate is not issued ",
  3638. "by a trusted authority. Use the\n",
  3639. " fingerprint to validate ",
  3640. "the certificate manually!\n";
  3641. }
  3642. if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
  3643. print STDERR " - The certificate hostname ",
  3644. "does not match.\n";
  3645. }
  3646. if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
  3647. print STDERR " - The certificate is not yet valid.\n";
  3648. }
  3649. if ($failures & $SVN::Auth::SSL::EXPIRED) {
  3650. print STDERR " - The certificate has expired.\n";
  3651. }
  3652. if ($failures & $SVN::Auth::SSL::OTHER) {
  3653. print STDERR " - The certificate has ",
  3654. "an unknown error.\n";
  3655. }
  3656. } # no warnings 'once'
  3657. printf STDERR
  3658. "Certificate information:\n".
  3659. " - Hostname: %s\n".
  3660. " - Valid: from %s until %s\n".
  3661. " - Issuer: %s\n".
  3662. " - Fingerprint: %s\n",
  3663. map $cert_info->$_, qw(hostname valid_from valid_until
  3664. issuer_dname fingerprint);
  3665. my $choice;
  3666. prompt:
  3667. print STDERR $may_save ?
  3668. "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
  3669. "(R)eject or accept (t)emporarily? ";
  3670. STDERR->flush;
  3671. $choice = lc(substr(<STDIN> || 'R', 0, 1));
  3672. if ($choice =~ /^t$/i) {
  3673. $cred->may_save(undef);
  3674. } elsif ($choice =~ /^r$/i) {
  3675. return -1;
  3676. } elsif ($may_save && $choice =~ /^p$/i) {
  3677. $cred->may_save($may_save);
  3678. } else {
  3679. goto prompt;
  3680. }
  3681. $cred->accepted_failures($failures);
  3682. $SVN::_Core::SVN_NO_ERROR;
  3683. }
  3684. sub ssl_client_cert {
  3685. my ($cred, $realm, $may_save, $pool) = @_;
  3686. $may_save = undef if $_no_auth_cache;
  3687. print STDERR "Client certificate filename: ";
  3688. STDERR->flush;
  3689. chomp(my $filename = <STDIN>);
  3690. $cred->cert_file($filename);
  3691. $cred->may_save($may_save);
  3692. $SVN::_Core::SVN_NO_ERROR;
  3693. }
  3694. sub ssl_client_cert_pw {
  3695. my ($cred, $realm, $may_save, $pool) = @_;
  3696. $may_save = undef if $_no_auth_cache;
  3697. $cred->password(_read_password("Password: ", $realm));
  3698. $cred->may_save($may_save);
  3699. $SVN::_Core::SVN_NO_ERROR;
  3700. }
  3701. sub username {
  3702. my ($cred, $realm, $may_save, $pool) = @_;
  3703. $may_save = undef if $_no_auth_cache;
  3704. if (defined $realm && length $realm) {
  3705. print STDERR "Authentication realm: $realm\n";
  3706. }
  3707. my $username;
  3708. if (defined $_username) {
  3709. $username = $_username;
  3710. } else {
  3711. print STDERR "Username: ";
  3712. STDERR->flush;
  3713. chomp($username = <STDIN>);
  3714. }
  3715. $cred->username($username);
  3716. $cred->may_save($may_save);
  3717. $SVN::_Core::SVN_NO_ERROR;
  3718. }
  3719. sub _read_password {
  3720. my ($prompt, $realm) = @_;
  3721. my $password = '';
  3722. if (exists $ENV{GIT_ASKPASS}) {
  3723. open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
  3724. $password = <PH>;
  3725. $password =~ s/[\012\015]//; # \n\r
  3726. close(PH);
  3727. } else {
  3728. print STDERR $prompt;
  3729. STDERR->flush;
  3730. require Term::ReadKey;
  3731. Term::ReadKey::ReadMode('noecho');
  3732. while (defined(my $key = Term::ReadKey::ReadKey(0))) {
  3733. last if $key =~ /[\012\015]/; # \n\r
  3734. $password .= $key;
  3735. }
  3736. Term::ReadKey::ReadMode('restore');
  3737. print STDERR "\n";
  3738. STDERR->flush;
  3739. }
  3740. $password;
  3741. }
  3742. package SVN::Git::Fetcher;
  3743. use vars qw/@ISA/;
  3744. use strict;
  3745. use warnings;
  3746. use Carp qw/croak/;
  3747. use IO::File qw//;
  3748. use vars qw/$_ignore_regex/;
  3749. # file baton members: path, mode_a, mode_b, pool, fh, blob, base
  3750. sub new {
  3751. my ($class, $git_svn, $switch_path) = @_;
  3752. my $self = SVN::Delta::Editor->new;
  3753. bless $self, $class;
  3754. if (exists $git_svn->{last_commit}) {
  3755. $self->{c} = $git_svn->{last_commit};
  3756. $self->{empty_symlinks} =
  3757. _mark_empty_symlinks($git_svn, $switch_path);
  3758. }
  3759. $self->{ignore_regex} = eval { command_oneline('config', '--get',
  3760. "svn-remote.$git_svn->{repo_id}.ignore-paths") };
  3761. $self->{empty} = {};
  3762. $self->{dir_prop} = {};
  3763. $self->{file_prop} = {};
  3764. $self->{absent_dir} = {};
  3765. $self->{absent_file} = {};
  3766. $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
  3767. $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
  3768. $self;
  3769. }
  3770. # this uses the Ra object, so it must be called before do_{switch,update},
  3771. # not inside them (when the Git::SVN::Fetcher object is passed) to
  3772. # do_{switch,update}
  3773. sub _mark_empty_symlinks {
  3774. my ($git_svn, $switch_path) = @_;
  3775. my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
  3776. return {} if (!defined($bool)) || (defined($bool) && ! $bool);
  3777. my %ret;
  3778. my ($rev, $cmt) = $git_svn->last_rev_commit;
  3779. return {} unless ($rev && $cmt);
  3780. # allow the warning to be printed for each revision we fetch to
  3781. # ensure the user sees it. The user can also disable the workaround
  3782. # on the repository even while git svn is running and the next
  3783. # revision fetched will skip this expensive function.
  3784. my $printed_warning;
  3785. chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
  3786. my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
  3787. local $/ = "\0";
  3788. my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
  3789. $pfx .= '/' if length($pfx);
  3790. while (<$ls>) {
  3791. chomp;
  3792. s/\A100644 blob $empty_blob\t//o or next;
  3793. unless ($printed_warning) {
  3794. print STDERR "Scanning for empty symlinks, ",
  3795. "this may take a while if you have ",
  3796. "many empty files\n",
  3797. "You may disable this with `",
  3798. "git config svn.brokenSymlinkWorkaround ",
  3799. "false'.\n",
  3800. "This may be done in a different ",
  3801. "terminal without restarting ",
  3802. "git svn\n";
  3803. $printed_warning = 1;
  3804. }
  3805. my $path = $_;
  3806. my (undef, $props) =
  3807. $git_svn->ra->get_file($pfx.$path, $rev, undef);
  3808. if ($props->{'svn:special'}) {
  3809. $ret{$path} = 1;
  3810. }
  3811. }
  3812. command_close_pipe($ls, $ctx);
  3813. \%ret;
  3814. }
  3815. # returns true if a given path is inside a ".git" directory
  3816. sub in_dot_git {
  3817. $_[0] =~ m{(?:^|/)\.git(?:/|$)};
  3818. }
  3819. # return value: 0 -- don't ignore, 1 -- ignore
  3820. sub is_path_ignored {
  3821. my ($self, $path) = @_;
  3822. return 1 if in_dot_git($path);
  3823. return 1 if defined($self->{ignore_regex}) &&
  3824. $path =~ m!$self->{ignore_regex}!;
  3825. return 0 unless defined($_ignore_regex);
  3826. return 1 if $path =~ m!$_ignore_regex!o;
  3827. return 0;
  3828. }
  3829. sub set_path_strip {
  3830. my ($self, $path) = @_;
  3831. $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
  3832. }
  3833. sub open_root {
  3834. { path => '' };
  3835. }
  3836. sub open_directory {
  3837. my ($self, $path, $pb, $rev) = @_;
  3838. { path => $path };
  3839. }
  3840. sub git_path {
  3841. my ($self, $path) = @_;
  3842. if (my $enc = $self->{pathnameencoding}) {
  3843. require Encode;
  3844. Encode::from_to($path, 'UTF-8', $enc);
  3845. }
  3846. if ($self->{path_strip}) {
  3847. $path =~ s!$self->{path_strip}!! or
  3848. die "Failed to strip path '$path' ($self->{path_strip})\n";
  3849. }
  3850. $path;
  3851. }
  3852. sub delete_entry {
  3853. my ($self, $path, $rev, $pb) = @_;
  3854. return undef if $self->is_path_ignored($path);
  3855. my $gpath = $self->git_path($path);
  3856. return undef if ($gpath eq '');
  3857. # remove entire directories.
  3858. my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
  3859. =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
  3860. if ($tree) {
  3861. my ($ls, $ctx) = command_output_pipe(qw/ls-tree
  3862. -r --name-only -z/,
  3863. $tree);
  3864. local $/ = "\0";
  3865. while (<$ls>) {
  3866. chomp;
  3867. my $rmpath = "$gpath/$_";
  3868. $self->{gii}->remove($rmpath);
  3869. print "\tD\t$rmpath\n" unless $::_q;
  3870. }
  3871. print "\tD\t$gpath/\n" unless $::_q;
  3872. command_close_pipe($ls, $ctx);
  3873. } else {
  3874. $self->{gii}->remove($gpath);
  3875. print "\tD\t$gpath\n" unless $::_q;
  3876. }
  3877. $self->{empty}->{$path} = 0;
  3878. undef;
  3879. }
  3880. sub open_file {
  3881. my ($self, $path, $pb, $rev) = @_;
  3882. my ($mode, $blob);
  3883. goto out if $self->is_path_ignored($path);
  3884. my $gpath = $self->git_path($path);
  3885. ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
  3886. =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
  3887. unless (defined $mode && defined $blob) {
  3888. die "$path was not found in commit $self->{c} (r$rev)\n";
  3889. }
  3890. if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
  3891. $mode = '120000';
  3892. }
  3893. out:
  3894. { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
  3895. pool => SVN::Pool->new, action => 'M' };
  3896. }
  3897. sub add_file {
  3898. my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
  3899. my $mode;
  3900. if (!$self->is_path_ignored($path)) {
  3901. my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
  3902. delete $self->{empty}->{$dir};
  3903. $mode = '100644';
  3904. }
  3905. { path => $path, mode_a => $mode, mode_b => $mode,
  3906. pool => SVN::Pool->new, action => 'A' };
  3907. }
  3908. sub add_directory {
  3909. my ($self, $path, $cp_path, $cp_rev) = @_;
  3910. goto out if $self->is_path_ignored($path);
  3911. my $gpath = $self->git_path($path);
  3912. if ($gpath eq '') {
  3913. my ($ls, $ctx) = command_output_pipe(qw/ls-tree
  3914. -r --name-only -z/,
  3915. $self->{c});
  3916. local $/ = "\0";
  3917. while (<$ls>) {
  3918. chomp;
  3919. $self->{gii}->remove($_);
  3920. print "\tD\t$_\n" unless $::_q;
  3921. }
  3922. command_close_pipe($ls, $ctx);
  3923. $self->{empty}->{$path} = 0;
  3924. }
  3925. my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
  3926. delete $self->{empty}->{$dir};
  3927. $self->{empty}->{$path} = 1;
  3928. out:
  3929. { path => $path };
  3930. }
  3931. sub change_dir_prop {
  3932. my ($self, $db, $prop, $value) = @_;
  3933. return undef if $self->is_path_ignored($db->{path});
  3934. $self->{dir_prop}->{$db->{path}} ||= {};
  3935. $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
  3936. undef;
  3937. }
  3938. sub absent_directory {
  3939. my ($self, $path, $pb) = @_;
  3940. return undef if $self->is_path_ignored($path);
  3941. $self->{absent_dir}->{$pb->{path}} ||= [];
  3942. push @{$self->{absent_dir}->{$pb->{path}}}, $path;
  3943. undef;
  3944. }
  3945. sub absent_file {
  3946. my ($self, $path, $pb) = @_;
  3947. return undef if $self->is_path_ignored($path);
  3948. $self->{absent_file}->{$pb->{path}} ||= [];
  3949. push @{$self->{absent_file}->{$pb->{path}}}, $path;
  3950. undef;
  3951. }
  3952. sub change_file_prop {
  3953. my ($self, $fb, $prop, $value) = @_;
  3954. return undef if $self->is_path_ignored($fb->{path});
  3955. if ($prop eq 'svn:executable') {
  3956. if ($fb->{mode_b} != 120000) {
  3957. $fb->{mode_b} = defined $value ? 100755 : 100644;
  3958. }
  3959. } elsif ($prop eq 'svn:special') {
  3960. $fb->{mode_b} = defined $value ? 120000 : 100644;
  3961. } else {
  3962. $self->{file_prop}->{$fb->{path}} ||= {};
  3963. $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
  3964. }
  3965. undef;
  3966. }
  3967. sub apply_textdelta {
  3968. my ($self, $fb, $exp) = @_;
  3969. return undef if $self->is_path_ignored($fb->{path});
  3970. my $fh = $::_repository->temp_acquire('svn_delta');
  3971. # $fh gets auto-closed() by SVN::TxDelta::apply(),
  3972. # (but $base does not,) so dup() it for reading in close_file
  3973. open my $dup, '<&', $fh or croak $!;
  3974. my $base = $::_repository->temp_acquire('git_blob');
  3975. if ($fb->{blob}) {
  3976. my ($base_is_link, $size);
  3977. if ($fb->{mode_a} eq '120000' &&
  3978. ! $self->{empty_symlinks}->{$fb->{path}}) {
  3979. print $base 'link ' or die "print $!\n";
  3980. $base_is_link = 1;
  3981. }
  3982. retry:
  3983. $size = $::_repository->cat_blob($fb->{blob}, $base);
  3984. die "Failed to read object $fb->{blob}" if ($size < 0);
  3985. if (defined $exp) {
  3986. seek $base, 0, 0 or croak $!;
  3987. my $got = ::md5sum($base);
  3988. if ($got ne $exp) {
  3989. my $err = "Checksum mismatch: ".
  3990. "$fb->{path} $fb->{blob}\n" .
  3991. "expected: $exp\n" .
  3992. " got: $got\n";
  3993. if ($base_is_link) {
  3994. warn $err,
  3995. "Retrying... (possibly ",
  3996. "a bad symlink from SVN)\n";
  3997. $::_repository->temp_reset($base);
  3998. $base_is_link = 0;
  3999. goto retry;
  4000. }
  4001. die $err;
  4002. }
  4003. }
  4004. }
  4005. seek $base, 0, 0 or croak $!;
  4006. $fb->{fh} = $fh;
  4007. $fb->{base} = $base;
  4008. [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
  4009. }
  4010. sub close_file {
  4011. my ($self, $fb, $exp) = @_;
  4012. return undef if $self->is_path_ignored($fb->{path});
  4013. my $hash;
  4014. my $path = $self->git_path($fb->{path});
  4015. if (my $fh = $fb->{fh}) {
  4016. if (defined $exp) {
  4017. seek($fh, 0, 0) or croak $!;
  4018. my $got = ::md5sum($fh);
  4019. if ($got ne $exp) {
  4020. die "Checksum mismatch: $path\n",
  4021. "expected: $exp\n got: $got\n";
  4022. }
  4023. }
  4024. if ($fb->{mode_b} == 120000) {
  4025. sysseek($fh, 0, 0) or croak $!;
  4026. my $rd = sysread($fh, my $buf, 5);
  4027. if (!defined $rd) {
  4028. croak "sysread: $!\n";
  4029. } elsif ($rd == 0) {
  4030. warn "$path has mode 120000",
  4031. " but it points to nothing\n",
  4032. "converting to an empty file with mode",
  4033. " 100644\n";
  4034. $fb->{mode_b} = '100644';
  4035. } elsif ($buf ne 'link ') {
  4036. warn "$path has mode 120000",
  4037. " but is not a link\n";
  4038. } else {
  4039. my $tmp_fh = $::_repository->temp_acquire(
  4040. 'svn_hash');
  4041. my $res;
  4042. while ($res = sysread($fh, my $str, 1024)) {
  4043. my $out = syswrite($tmp_fh, $str, $res);
  4044. defined($out) && $out == $res
  4045. or croak("write ",
  4046. Git::temp_path($tmp_fh),
  4047. ": $!\n");
  4048. }
  4049. defined $res or croak $!;
  4050. ($fh, $tmp_fh) = ($tmp_fh, $fh);
  4051. Git::temp_release($tmp_fh, 1);
  4052. }
  4053. }
  4054. $hash = $::_repository->hash_and_insert_object(
  4055. Git::temp_path($fh));
  4056. $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
  4057. Git::temp_release($fb->{base}, 1);
  4058. Git::temp_release($fh, 1);
  4059. } else {
  4060. $hash = $fb->{blob} or die "no blob information\n";
  4061. }
  4062. $fb->{pool}->clear;
  4063. $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
  4064. print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
  4065. undef;
  4066. }
  4067. sub abort_edit {
  4068. my $self = shift;
  4069. $self->{nr} = $self->{gii}->{nr};
  4070. delete $self->{gii};
  4071. $self->SUPER::abort_edit(@_);
  4072. }
  4073. sub close_edit {
  4074. my $self = shift;
  4075. $self->{git_commit_ok} = 1;
  4076. $self->{nr} = $self->{gii}->{nr};
  4077. delete $self->{gii};
  4078. $self->SUPER::close_edit(@_);
  4079. }
  4080. package SVN::Git::Editor;
  4081. use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
  4082. use strict;
  4083. use warnings;
  4084. use Carp qw/croak/;
  4085. use IO::File;
  4086. sub new {
  4087. my ($class, $opts) = @_;
  4088. foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
  4089. die "$_ required!\n" unless (defined $opts->{$_});
  4090. }
  4091. my $pool = SVN::Pool->new;
  4092. my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
  4093. my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
  4094. $opts->{r}, $mods);
  4095. # $opts->{ra} functions should not be used after this:
  4096. my @ce = $opts->{ra}->get_commit_editor($opts->{log},
  4097. $opts->{editor_cb}, $pool);
  4098. my $self = SVN::Delta::Editor->new(@ce, $pool);
  4099. bless $self, $class;
  4100. foreach (qw/svn_path r tree_a tree_b/) {
  4101. $self->{$_} = $opts->{$_};
  4102. }
  4103. $self->{url} = $opts->{ra}->{url};
  4104. $self->{mods} = $mods;
  4105. $self->{types} = $types;
  4106. $self->{pool} = $pool;
  4107. $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
  4108. $self->{rm} = { };
  4109. $self->{path_prefix} = length $self->{svn_path} ?
  4110. "$self->{svn_path}/" : '';
  4111. $self->{config} = $opts->{config};
  4112. $self->{mergeinfo} = $opts->{mergeinfo};
  4113. return $self;
  4114. }
  4115. sub generate_diff {
  4116. my ($tree_a, $tree_b) = @_;
  4117. my @diff_tree = qw(diff-tree -z -r);
  4118. if ($_cp_similarity) {
  4119. push @diff_tree, "-C$_cp_similarity";
  4120. } else {
  4121. push @diff_tree, '-C';
  4122. }
  4123. push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
  4124. push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
  4125. push @diff_tree, $tree_a, $tree_b;
  4126. my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
  4127. local $/ = "\0";
  4128. my $state = 'meta';
  4129. my @mods;
  4130. while (<$diff_fh>) {
  4131. chomp $_; # this gets rid of the trailing "\0"
  4132. if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
  4133. ($::sha1)\s($::sha1)\s
  4134. ([MTCRAD])\d*$/xo) {
  4135. push @mods, { mode_a => $1, mode_b => $2,
  4136. sha1_a => $3, sha1_b => $4,
  4137. chg => $5 };
  4138. if ($5 =~ /^(?:C|R)$/) {
  4139. $state = 'file_a';
  4140. } else {
  4141. $state = 'file_b';
  4142. }
  4143. } elsif ($state eq 'file_a') {
  4144. my $x = $mods[$#mods] or croak "Empty array\n";
  4145. if ($x->{chg} !~ /^(?:C|R)$/) {
  4146. croak "Error parsing $_, $x->{chg}\n";
  4147. }
  4148. $x->{file_a} = $_;
  4149. $state = 'file_b';
  4150. } elsif ($state eq 'file_b') {
  4151. my $x = $mods[$#mods] or croak "Empty array\n";
  4152. if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
  4153. croak "Error parsing $_, $x->{chg}\n";
  4154. }
  4155. if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
  4156. croak "Error parsing $_, $x->{chg}\n";
  4157. }
  4158. $x->{file_b} = $_;
  4159. $state = 'meta';
  4160. } else {
  4161. croak "Error parsing $_\n";
  4162. }
  4163. }
  4164. command_close_pipe($diff_fh, $ctx);
  4165. \@mods;
  4166. }
  4167. sub check_diff_paths {
  4168. my ($ra, $pfx, $rev, $mods) = @_;
  4169. my %types;
  4170. $pfx .= '/' if length $pfx;
  4171. sub type_diff_paths {
  4172. my ($ra, $types, $path, $rev) = @_;
  4173. my @p = split m#/+#, $path;
  4174. my $c = shift @p;
  4175. unless (defined $types->{$c}) {
  4176. $types->{$c} = $ra->check_path($c, $rev);
  4177. }
  4178. while (@p) {
  4179. $c .= '/' . shift @p;
  4180. next if defined $types->{$c};
  4181. $types->{$c} = $ra->check_path($c, $rev);
  4182. }
  4183. }
  4184. foreach my $m (@$mods) {
  4185. foreach my $f (qw/file_a file_b/) {
  4186. next unless defined $m->{$f};
  4187. my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
  4188. if (length $pfx.$dir && ! defined $types{$dir}) {
  4189. type_diff_paths($ra, \%types, $pfx.$dir, $rev);
  4190. }
  4191. }
  4192. }
  4193. \%types;
  4194. }
  4195. sub split_path {
  4196. return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
  4197. }
  4198. sub repo_path {
  4199. my ($self, $path) = @_;
  4200. if (my $enc = $self->{pathnameencoding}) {
  4201. require Encode;
  4202. Encode::from_to($path, $enc, 'UTF-8');
  4203. }
  4204. $self->{path_prefix}.(defined $path ? $path : '');
  4205. }
  4206. sub url_path {
  4207. my ($self, $path) = @_;
  4208. if ($self->{url} =~ m#^https?://#) {
  4209. $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
  4210. }
  4211. $self->{url} . '/' . $self->repo_path($path);
  4212. }
  4213. sub rmdirs {
  4214. my ($self) = @_;
  4215. my $rm = $self->{rm};
  4216. delete $rm->{''}; # we never delete the url we're tracking
  4217. return unless %$rm;
  4218. foreach (keys %$rm) {
  4219. my @d = split m#/#, $_;
  4220. my $c = shift @d;
  4221. $rm->{$c} = 1;
  4222. while (@d) {
  4223. $c .= '/' . shift @d;
  4224. $rm->{$c} = 1;
  4225. }
  4226. }
  4227. delete $rm->{$self->{svn_path}};
  4228. delete $rm->{''}; # we never delete the url we're tracking
  4229. return unless %$rm;
  4230. my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
  4231. $self->{tree_b});
  4232. local $/ = "\0";
  4233. while (<$fh>) {
  4234. chomp;
  4235. my @dn = split m#/#, $_;
  4236. while (pop @dn) {
  4237. delete $rm->{join '/', @dn};
  4238. }
  4239. unless (%$rm) {
  4240. close $fh;
  4241. return;
  4242. }
  4243. }
  4244. command_close_pipe($fh, $ctx);
  4245. my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
  4246. foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
  4247. $self->close_directory($bat->{$d}, $p);
  4248. my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
  4249. print "\tD+\t$d/\n" unless $::_q;
  4250. $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
  4251. delete $bat->{$d};
  4252. }
  4253. }
  4254. sub open_or_add_dir {
  4255. my ($self, $full_path, $baton) = @_;
  4256. my $t = $self->{types}->{$full_path};
  4257. if (!defined $t) {
  4258. die "$full_path not known in r$self->{r} or we have a bug!\n";
  4259. }
  4260. {
  4261. no warnings 'once';
  4262. # SVN::Node::none and SVN::Node::file are used only once,
  4263. # so we're shutting up Perl's warnings about them.
  4264. if ($t == $SVN::Node::none) {
  4265. return $self->add_directory($full_path, $baton,
  4266. undef, -1, $self->{pool});
  4267. } elsif ($t == $SVN::Node::dir) {
  4268. return $self->open_directory($full_path, $baton,
  4269. $self->{r}, $self->{pool});
  4270. } # no warnings 'once'
  4271. print STDERR "$full_path already exists in repository at ",
  4272. "r$self->{r} and it is not a directory (",
  4273. ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
  4274. } # no warnings 'once'
  4275. exit 1;
  4276. }
  4277. sub ensure_path {
  4278. my ($self, $path) = @_;
  4279. my $bat = $self->{bat};
  4280. my $repo_path = $self->repo_path($path);
  4281. return $bat->{''} unless (length $repo_path);
  4282. my @p = split m#/+#, $repo_path;
  4283. my $c = shift @p;
  4284. $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
  4285. while (@p) {
  4286. my $c0 = $c;
  4287. $c .= '/' . shift @p;
  4288. $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
  4289. }
  4290. return $bat->{$c};
  4291. }
  4292. # Subroutine to convert a globbing pattern to a regular expression.
  4293. # From perl cookbook.
  4294. sub glob2pat {
  4295. my $globstr = shift;
  4296. my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
  4297. $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
  4298. return '^' . $globstr . '$';
  4299. }
  4300. sub check_autoprop {
  4301. my ($self, $pattern, $properties, $file, $fbat) = @_;
  4302. # Convert the globbing pattern to a regular expression.
  4303. my $regex = glob2pat($pattern);
  4304. # Check if the pattern matches the file name.
  4305. if($file =~ m/($regex)/) {
  4306. # Parse the list of properties to set.
  4307. my @props = split(/;/, $properties);
  4308. foreach my $prop (@props) {
  4309. # Parse 'name=value' syntax and set the property.
  4310. if ($prop =~ /([^=]+)=(.*)/) {
  4311. my ($n,$v) = ($1,$2);
  4312. for ($n, $v) {
  4313. s/^\s+//; s/\s+$//;
  4314. }
  4315. $self->change_file_prop($fbat, $n, $v);
  4316. }
  4317. }
  4318. }
  4319. }
  4320. sub apply_autoprops {
  4321. my ($self, $file, $fbat) = @_;
  4322. my $conf_t = ${$self->{config}}{'config'};
  4323. no warnings 'once';
  4324. # Check [miscellany]/enable-auto-props in svn configuration.
  4325. if (SVN::_Core::svn_config_get_bool(
  4326. $conf_t,
  4327. $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
  4328. $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
  4329. 0)) {
  4330. # Auto-props are enabled. Enumerate them to look for matches.
  4331. my $callback = sub {
  4332. $self->check_autoprop($_[0], $_[1], $file, $fbat);
  4333. };
  4334. SVN::_Core::svn_config_enumerate(
  4335. $conf_t,
  4336. $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
  4337. $callback);
  4338. }
  4339. }
  4340. sub A {
  4341. my ($self, $m) = @_;
  4342. my ($dir, $file) = split_path($m->{file_b});
  4343. my $pbat = $self->ensure_path($dir);
  4344. my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
  4345. undef, -1);
  4346. print "\tA\t$m->{file_b}\n" unless $::_q;
  4347. $self->apply_autoprops($file, $fbat);
  4348. $self->chg_file($fbat, $m);
  4349. $self->close_file($fbat,undef,$self->{pool});
  4350. }
  4351. sub C {
  4352. my ($self, $m) = @_;
  4353. my ($dir, $file) = split_path($m->{file_b});
  4354. my $pbat = $self->ensure_path($dir);
  4355. my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
  4356. $self->url_path($m->{file_a}), $self->{r});
  4357. print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
  4358. $self->chg_file($fbat, $m);
  4359. $self->close_file($fbat,undef,$self->{pool});
  4360. }
  4361. sub delete_entry {
  4362. my ($self, $path, $pbat) = @_;
  4363. my $rpath = $self->repo_path($path);
  4364. my ($dir, $file) = split_path($rpath);
  4365. $self->{rm}->{$dir} = 1;
  4366. $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
  4367. }
  4368. sub R {
  4369. my ($self, $m) = @_;
  4370. my ($dir, $file) = split_path($m->{file_b});
  4371. my $pbat = $self->ensure_path($dir);
  4372. my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
  4373. $self->url_path($m->{file_a}), $self->{r});
  4374. print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
  4375. $self->apply_autoprops($file, $fbat);
  4376. $self->chg_file($fbat, $m);
  4377. $self->close_file($fbat,undef,$self->{pool});
  4378. ($dir, $file) = split_path($m->{file_a});
  4379. $pbat = $self->ensure_path($dir);
  4380. $self->delete_entry($m->{file_a}, $pbat);
  4381. }
  4382. sub M {
  4383. my ($self, $m) = @_;
  4384. my ($dir, $file) = split_path($m->{file_b});
  4385. my $pbat = $self->ensure_path($dir);
  4386. my $fbat = $self->open_file($self->repo_path($m->{file_b}),
  4387. $pbat,$self->{r},$self->{pool});
  4388. print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
  4389. $self->chg_file($fbat, $m);
  4390. $self->close_file($fbat,undef,$self->{pool});
  4391. }
  4392. sub T { shift->M(@_) }
  4393. sub change_file_prop {
  4394. my ($self, $fbat, $pname, $pval) = @_;
  4395. $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
  4396. }
  4397. sub change_dir_prop {
  4398. my ($self, $pbat, $pname, $pval) = @_;
  4399. $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
  4400. }
  4401. sub _chg_file_get_blob ($$$$) {
  4402. my ($self, $fbat, $m, $which) = @_;
  4403. my $fh = $::_repository->temp_acquire("git_blob_$which");
  4404. if ($m->{"mode_$which"} =~ /^120/) {
  4405. print $fh 'link ' or croak $!;
  4406. $self->change_file_prop($fbat,'svn:special','*');
  4407. } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
  4408. $self->change_file_prop($fbat,'svn:special',undef);
  4409. }
  4410. my $blob = $m->{"sha1_$which"};
  4411. return ($fh,) if ($blob =~ /^0{40}$/);
  4412. my $size = $::_repository->cat_blob($blob, $fh);
  4413. croak "Failed to read object $blob" if ($size < 0);
  4414. $fh->flush == 0 or croak $!;
  4415. seek $fh, 0, 0 or croak $!;
  4416. my $exp = ::md5sum($fh);
  4417. seek $fh, 0, 0 or croak $!;
  4418. return ($fh, $exp);
  4419. }
  4420. sub chg_file {
  4421. my ($self, $fbat, $m) = @_;
  4422. if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
  4423. $self->change_file_prop($fbat,'svn:executable','*');
  4424. } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
  4425. $self->change_file_prop($fbat,'svn:executable',undef);
  4426. }
  4427. my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
  4428. my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
  4429. my $pool = SVN::Pool->new;
  4430. my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
  4431. if (-s $fh_a) {
  4432. my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
  4433. my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
  4434. if (defined $res) {
  4435. die "Unexpected result from send_txstream: $res\n",
  4436. "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
  4437. }
  4438. } else {
  4439. my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
  4440. die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
  4441. if ($got ne $exp_b);
  4442. }
  4443. Git::temp_release($fh_b, 1);
  4444. Git::temp_release($fh_a, 1);
  4445. $pool->clear;
  4446. }
  4447. sub D {
  4448. my ($self, $m) = @_;
  4449. my ($dir, $file) = split_path($m->{file_b});
  4450. my $pbat = $self->ensure_path($dir);
  4451. print "\tD\t$m->{file_b}\n" unless $::_q;
  4452. $self->delete_entry($m->{file_b}, $pbat);
  4453. }
  4454. sub close_edit {
  4455. my ($self) = @_;
  4456. my ($p,$bat) = ($self->{pool}, $self->{bat});
  4457. foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
  4458. next if $_ eq '';
  4459. $self->close_directory($bat->{$_}, $p);
  4460. }
  4461. $self->close_directory($bat->{''}, $p);
  4462. $self->SUPER::close_edit($p);
  4463. $p->clear;
  4464. }
  4465. sub abort_edit {
  4466. my ($self) = @_;
  4467. $self->SUPER::abort_edit($self->{pool});
  4468. }
  4469. sub DESTROY {
  4470. my $self = shift;
  4471. $self->SUPER::DESTROY(@_);
  4472. $self->{pool}->clear;
  4473. }
  4474. # this drives the editor
  4475. sub apply_diff {
  4476. my ($self) = @_;
  4477. my $mods = $self->{mods};
  4478. my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
  4479. foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
  4480. my $f = $m->{chg};
  4481. if (defined $o{$f}) {
  4482. $self->$f($m);
  4483. } else {
  4484. fatal("Invalid change type: $f");
  4485. }
  4486. }
  4487. if (defined($self->{mergeinfo})) {
  4488. $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
  4489. $self->{mergeinfo});
  4490. }
  4491. $self->rmdirs if $_rmdir;
  4492. if (@$mods == 0) {
  4493. $self->abort_edit;
  4494. } else {
  4495. $self->close_edit;
  4496. }
  4497. return scalar @$mods;
  4498. }
  4499. package Git::SVN::Ra;
  4500. use vars qw/@ISA $config_dir $_log_window_size/;
  4501. use strict;
  4502. use warnings;
  4503. my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
  4504. BEGIN {
  4505. # enforce temporary pool usage for some simple functions
  4506. no strict 'refs';
  4507. for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
  4508. get_file/) {
  4509. my $SUPER = "SUPER::$f";
  4510. *$f = sub {
  4511. my $self = shift;
  4512. my $pool = SVN::Pool->new;
  4513. my @ret = $self->$SUPER(@_,$pool);
  4514. $pool->clear;
  4515. wantarray ? @ret : $ret[0];
  4516. };
  4517. }
  4518. }
  4519. sub _auth_providers () {
  4520. [
  4521. SVN::Client::get_simple_provider(),
  4522. SVN::Client::get_ssl_server_trust_file_provider(),
  4523. SVN::Client::get_simple_prompt_provider(
  4524. \&Git::SVN::Prompt::simple, 2),
  4525. SVN::Client::get_ssl_client_cert_file_provider(),
  4526. SVN::Client::get_ssl_client_cert_prompt_provider(
  4527. \&Git::SVN::Prompt::ssl_client_cert, 2),
  4528. SVN::Client::get_ssl_client_cert_pw_file_provider(),
  4529. SVN::Client::get_ssl_client_cert_pw_prompt_provider(
  4530. \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
  4531. SVN::Client::get_username_provider(),
  4532. SVN::Client::get_ssl_server_trust_prompt_provider(
  4533. \&Git::SVN::Prompt::ssl_server_trust),
  4534. SVN::Client::get_username_prompt_provider(
  4535. \&Git::SVN::Prompt::username, 2)
  4536. ]
  4537. }
  4538. sub escape_uri_only {
  4539. my ($uri) = @_;
  4540. my @tmp;
  4541. foreach (split m{/}, $uri) {
  4542. s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
  4543. push @tmp, $_;
  4544. }
  4545. join('/', @tmp);
  4546. }
  4547. sub escape_url {
  4548. my ($url) = @_;
  4549. if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
  4550. my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
  4551. $url = "$scheme://$domain$uri";
  4552. }
  4553. $url;
  4554. }
  4555. sub new {
  4556. my ($class, $url) = @_;
  4557. $url =~ s!/+$!!;
  4558. return $RA if ($RA && $RA->{url} eq $url);
  4559. ::_req_svn();
  4560. SVN::_Core::svn_config_ensure($config_dir, undef);
  4561. my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
  4562. my $config = SVN::Core::config_get_config($config_dir);
  4563. $RA = undef;
  4564. my $dont_store_passwords = 1;
  4565. my $conf_t = ${$config}{'config'};
  4566. {
  4567. no warnings 'once';
  4568. # The usage of $SVN::_Core::SVN_CONFIG_* variables
  4569. # produces warnings that variables are used only once.
  4570. # I had not found the better way to shut them up, so
  4571. # the warnings of type 'once' are disabled in this block.
  4572. if (SVN::_Core::svn_config_get_bool($conf_t,
  4573. $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
  4574. $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
  4575. 1) == 0) {
  4576. SVN::_Core::svn_auth_set_parameter($baton,
  4577. $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
  4578. bless (\$dont_store_passwords, "_p_void"));
  4579. }
  4580. if (SVN::_Core::svn_config_get_bool($conf_t,
  4581. $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
  4582. $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
  4583. 1) == 0) {
  4584. $Git::SVN::Prompt::_no_auth_cache = 1;
  4585. }
  4586. } # no warnings 'once'
  4587. my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
  4588. config => $config,
  4589. pool => SVN::Pool->new,
  4590. auth_provider_callbacks => $callbacks);
  4591. $self->{url} = $url;
  4592. $self->{svn_path} = $url;
  4593. $self->{repos_root} = $self->get_repos_root;
  4594. $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
  4595. $self->{cache} = { check_path => { r => 0, data => {} },
  4596. get_dir => { r => 0, data => {} } };
  4597. $RA = bless $self, $class;
  4598. }
  4599. sub check_path {
  4600. my ($self, $path, $r) = @_;
  4601. my $cache = $self->{cache}->{check_path};
  4602. if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
  4603. return $cache->{data}->{$path};
  4604. }
  4605. my $pool = SVN::Pool->new;
  4606. my $t = $self->SUPER::check_path($path, $r, $pool);
  4607. $pool->clear;
  4608. if ($r != $cache->{r}) {
  4609. %{$cache->{data}} = ();
  4610. $cache->{r} = $r;
  4611. }
  4612. $cache->{data}->{$path} = $t;
  4613. }
  4614. sub get_dir {
  4615. my ($self, $dir, $r) = @_;
  4616. my $cache = $self->{cache}->{get_dir};
  4617. if ($r == $cache->{r}) {
  4618. if (my $x = $cache->{data}->{$dir}) {
  4619. return wantarray ? @$x : $x->[0];
  4620. }
  4621. }
  4622. my $pool = SVN::Pool->new;
  4623. my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
  4624. my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
  4625. $pool->clear;
  4626. if ($r != $cache->{r}) {
  4627. %{$cache->{data}} = ();
  4628. $cache->{r} = $r;
  4629. }
  4630. $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
  4631. wantarray ? (\%dirents, $r, $props) : \%dirents;
  4632. }
  4633. sub DESTROY {
  4634. # do not call the real DESTROY since we store ourselves in $RA
  4635. }
  4636. # get_log(paths, start, end, limit,
  4637. # discover_changed_paths, strict_node_history, receiver)
  4638. sub get_log {
  4639. my ($self, @args) = @_;
  4640. my $pool = SVN::Pool->new;
  4641. # svn_log_changed_path_t objects passed to get_log are likely to be
  4642. # overwritten even if only the refs are copied to an external variable,
  4643. # so we should dup the structures in their entirety. Using an
  4644. # externally passed pool (instead of our temporary and quickly cleared
  4645. # pool in Git::SVN::Ra) does not help matters at all...
  4646. my $receiver = pop @args;
  4647. my $prefix = "/".$self->{svn_path};
  4648. $prefix =~ s#/+($)##;
  4649. my $prefix_regex = qr#^\Q$prefix\E#;
  4650. push(@args, sub {
  4651. my ($paths) = $_[0];
  4652. return &$receiver(@_) unless $paths;
  4653. $_[0] = ();
  4654. foreach my $p (keys %$paths) {
  4655. my $i = $paths->{$p};
  4656. # Make path relative to our url, not repos_root
  4657. $p =~ s/$prefix_regex//;
  4658. my %s = map { $_ => $i->$_; }
  4659. qw/copyfrom_path copyfrom_rev action/;
  4660. if ($s{'copyfrom_path'}) {
  4661. $s{'copyfrom_path'} =~ s/$prefix_regex//;
  4662. }
  4663. $_[0]{$p} = \%s;
  4664. }
  4665. &$receiver(@_);
  4666. });
  4667. # the limit parameter was not supported in SVN 1.1.x, so we
  4668. # drop it. Therefore, the receiver callback passed to it
  4669. # is made aware of this limitation by being wrapped if
  4670. # the limit passed to is being wrapped.
  4671. if ($SVN::Core::VERSION le '1.2.0') {
  4672. my $limit = splice(@args, 3, 1);
  4673. if ($limit > 0) {
  4674. my $receiver = pop @args;
  4675. push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
  4676. }
  4677. }
  4678. my $ret = $self->SUPER::get_log(@args, $pool);
  4679. $pool->clear;
  4680. $ret;
  4681. }
  4682. sub trees_match {
  4683. my ($self, $url1, $rev1, $url2, $rev2) = @_;
  4684. my $ctx = SVN::Client->new(auth => _auth_providers);
  4685. my $out = IO::File->new_tmpfile;
  4686. # older SVN (1.1.x) doesn't take $pool as the last parameter for
  4687. # $ctx->diff(), so we'll create a default one
  4688. my $pool = SVN::Pool->new_default_sub;
  4689. $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
  4690. $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
  4691. $out->flush;
  4692. my $ret = (($out->stat)[7] == 0);
  4693. close $out or croak $!;
  4694. $ret;
  4695. }
  4696. sub get_commit_editor {
  4697. my ($self, $log, $cb, $pool) = @_;
  4698. my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
  4699. $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
  4700. }
  4701. sub gs_do_update {
  4702. my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
  4703. my $new = ($rev_a == $rev_b);
  4704. my $path = $gs->{path};
  4705. if ($new && -e $gs->{index}) {
  4706. unlink $gs->{index} or die
  4707. "Couldn't unlink index: $gs->{index}: $!\n";
  4708. }
  4709. my $pool = SVN::Pool->new;
  4710. $editor->set_path_strip($path);
  4711. my (@pc) = split m#/#, $path;
  4712. my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
  4713. 1, $editor, $pool);
  4714. my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
  4715. # Since we can't rely on svn_ra_reparent being available, we'll
  4716. # just have to do some magic with set_path to make it so
  4717. # we only want a partial path.
  4718. my $sp = '';
  4719. my $final = join('/', @pc);
  4720. while (@pc) {
  4721. $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
  4722. $sp .= '/' if length $sp;
  4723. $sp .= shift @pc;
  4724. }
  4725. die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
  4726. $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
  4727. $reporter->finish_report($pool);
  4728. $pool->clear;
  4729. $editor->{git_commit_ok};
  4730. }
  4731. # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
  4732. # svn_ra_reparent didn't work before 1.4)
  4733. sub gs_do_switch {
  4734. my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
  4735. my $path = $gs->{path};
  4736. my $pool = SVN::Pool->new;
  4737. my $full_url = $self->{url};
  4738. my $old_url = $full_url;
  4739. $full_url .= '/' . $path if length $path;
  4740. my ($ra, $reparented);
  4741. if ($old_url =~ m#^svn(\+ssh)?://# ||
  4742. ($full_url =~ m#^https?://# &&
  4743. escape_url($full_url) ne $full_url)) {
  4744. $_[0] = undef;
  4745. $self = undef;
  4746. $RA = undef;
  4747. $ra = Git::SVN::Ra->new($full_url);
  4748. $ra_invalid = 1;
  4749. } elsif ($old_url ne $full_url) {
  4750. SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
  4751. $self->{url} = $full_url;
  4752. $reparented = 1;
  4753. }
  4754. $ra ||= $self;
  4755. $url_b = escape_url($url_b);
  4756. my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
  4757. my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
  4758. $reporter->set_path('', $rev_a, 0, @lock, $pool);
  4759. $reporter->finish_report($pool);
  4760. if ($reparented) {
  4761. SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
  4762. $self->{url} = $old_url;
  4763. }
  4764. $pool->clear;
  4765. $editor->{git_commit_ok};
  4766. }
  4767. sub longest_common_path {
  4768. my ($gsv, $globs) = @_;
  4769. my %common;
  4770. my $common_max = scalar @$gsv;
  4771. foreach my $gs (@$gsv) {
  4772. my @tmp = split m#/#, $gs->{path};
  4773. my $p = '';
  4774. foreach (@tmp) {
  4775. $p .= length($p) ? "/$_" : $_;
  4776. $common{$p} ||= 0;
  4777. $common{$p}++;
  4778. }
  4779. }
  4780. $globs ||= [];
  4781. $common_max += scalar @$globs;
  4782. foreach my $glob (@$globs) {
  4783. my @tmp = split m#/#, $glob->{path}->{left};
  4784. my $p = '';
  4785. foreach (@tmp) {
  4786. $p .= length($p) ? "/$_" : $_;
  4787. $common{$p} ||= 0;
  4788. $common{$p}++;
  4789. }
  4790. }
  4791. my $longest_path = '';
  4792. foreach (sort {length $b <=> length $a} keys %common) {
  4793. if ($common{$_} == $common_max) {
  4794. $longest_path = $_;
  4795. last;
  4796. }
  4797. }
  4798. $longest_path;
  4799. }
  4800. sub gs_fetch_loop_common {
  4801. my ($self, $base, $head, $gsv, $globs) = @_;
  4802. return if ($base > $head);
  4803. my $inc = $_log_window_size;
  4804. my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
  4805. my $longest_path = longest_common_path($gsv, $globs);
  4806. my $ra_url = $self->{url};
  4807. my $find_trailing_edge;
  4808. while (1) {
  4809. my %revs;
  4810. my $err;
  4811. my $err_handler = $SVN::Error::handler;
  4812. $SVN::Error::handler = sub {
  4813. ($err) = @_;
  4814. skip_unknown_revs($err);
  4815. };
  4816. sub _cb {
  4817. my ($paths, $r, $author, $date, $log) = @_;
  4818. [ $paths,
  4819. { author => $author, date => $date, log => $log } ];
  4820. }
  4821. $self->get_log([$longest_path], $min, $max, 0, 1, 1,
  4822. sub { $revs{$_[1]} = _cb(@_) });
  4823. if ($err) {
  4824. print "Checked through r$max\r";
  4825. } else {
  4826. $find_trailing_edge = 1;
  4827. }
  4828. if ($err and $find_trailing_edge) {
  4829. print STDERR "Path '$longest_path' ",
  4830. "was probably deleted:\n",
  4831. $err->expanded_message,
  4832. "\nWill attempt to follow ",
  4833. "revisions r$min .. r$max ",
  4834. "committed before the deletion\n";
  4835. my $hi = $max;
  4836. while (--$hi >= $min) {
  4837. my $ok;
  4838. $self->get_log([$longest_path], $min, $hi,
  4839. 0, 1, 1, sub {
  4840. $ok = $_[1];
  4841. $revs{$_[1]} = _cb(@_) });
  4842. if ($ok) {
  4843. print STDERR "r$min .. r$ok OK\n";
  4844. last;
  4845. }
  4846. }
  4847. $find_trailing_edge = 0;
  4848. }
  4849. $SVN::Error::handler = $err_handler;
  4850. my %exists = map { $_->{path} => $_ } @$gsv;
  4851. foreach my $r (sort {$a <=> $b} keys %revs) {
  4852. my ($paths, $logged) = @{$revs{$r}};
  4853. foreach my $gs ($self->match_globs(\%exists, $paths,
  4854. $globs, $r)) {
  4855. if ($gs->rev_map_max >= $r) {
  4856. next;
  4857. }
  4858. next unless $gs->match_paths($paths, $r);
  4859. $gs->{logged_rev_props} = $logged;
  4860. if (my $last_commit = $gs->last_commit) {
  4861. $gs->assert_index_clean($last_commit);
  4862. }
  4863. my $log_entry = $gs->do_fetch($paths, $r);
  4864. if ($log_entry) {
  4865. $gs->do_git_commit($log_entry);
  4866. }
  4867. $INDEX_FILES{$gs->{index}} = 1;
  4868. }
  4869. foreach my $g (@$globs) {
  4870. my $k = "svn-remote.$g->{remote}." .
  4871. "$g->{t}-maxRev";
  4872. Git::SVN::tmp_config($k, $r);
  4873. }
  4874. if ($ra_invalid) {
  4875. $_[0] = undef;
  4876. $self = undef;
  4877. $RA = undef;
  4878. $self = Git::SVN::Ra->new($ra_url);
  4879. $ra_invalid = undef;
  4880. }
  4881. }
  4882. # pre-fill the .rev_db since it'll eventually get filled in
  4883. # with '0' x40 if something new gets committed
  4884. foreach my $gs (@$gsv) {
  4885. next if $gs->rev_map_max >= $max;
  4886. next if defined $gs->rev_map_get($max);
  4887. $gs->rev_map_set($max, 0 x40);
  4888. }
  4889. foreach my $g (@$globs) {
  4890. my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
  4891. Git::SVN::tmp_config($k, $max);
  4892. }
  4893. last if $max >= $head;
  4894. $min = $max + 1;
  4895. $max += $inc;
  4896. $max = $head if ($max > $head);
  4897. }
  4898. Git::SVN::gc();
  4899. }
  4900. sub get_dir_globbed {
  4901. my ($self, $left, $depth, $r) = @_;
  4902. my @x = eval { $self->get_dir($left, $r) };
  4903. return unless scalar @x == 3;
  4904. my $dirents = $x[0];
  4905. my @finalents;
  4906. foreach my $de (keys %$dirents) {
  4907. next if $dirents->{$de}->{kind} != $SVN::Node::dir;
  4908. if ($depth > 1) {
  4909. my @args = ("$left/$de", $depth - 1, $r);
  4910. foreach my $dir ($self->get_dir_globbed(@args)) {
  4911. push @finalents, "$de/$dir";
  4912. }
  4913. } else {
  4914. push @finalents, $de;
  4915. }
  4916. }
  4917. @finalents;
  4918. }
  4919. sub match_globs {
  4920. my ($self, $exists, $paths, $globs, $r) = @_;
  4921. sub get_dir_check {
  4922. my ($self, $exists, $g, $r) = @_;
  4923. my @dirs = $self->get_dir_globbed($g->{path}->{left},
  4924. $g->{path}->{depth},
  4925. $r);
  4926. foreach my $de (@dirs) {
  4927. my $p = $g->{path}->full_path($de);
  4928. next if $exists->{$p};
  4929. next if (length $g->{path}->{right} &&
  4930. ($self->check_path($p, $r) !=
  4931. $SVN::Node::dir));
  4932. next unless $p =~ /$g->{path}->{regex}/;
  4933. $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
  4934. $g->{ref}->full_path($de), 1);
  4935. }
  4936. }
  4937. foreach my $g (@$globs) {
  4938. if (my $path = $paths->{"/$g->{path}->{left}"}) {
  4939. if ($path->{action} =~ /^[AR]$/) {
  4940. get_dir_check($self, $exists, $g, $r);
  4941. }
  4942. }
  4943. foreach (keys %$paths) {
  4944. if (/$g->{path}->{left_regex}/ &&
  4945. !/$g->{path}->{regex}/) {
  4946. next if $paths->{$_}->{action} !~ /^[AR]$/;
  4947. get_dir_check($self, $exists, $g, $r);
  4948. }
  4949. next unless /$g->{path}->{regex}/;
  4950. my $p = $1;
  4951. my $pathname = $g->{path}->full_path($p);
  4952. next if $exists->{$pathname};
  4953. next if ($self->check_path($pathname, $r) !=
  4954. $SVN::Node::dir);
  4955. $exists->{$pathname} = Git::SVN->init(
  4956. $self->{url}, $pathname, undef,
  4957. $g->{ref}->full_path($p), 1);
  4958. }
  4959. my $c = '';
  4960. foreach (split m#/#, $g->{path}->{left}) {
  4961. $c .= "/$_";
  4962. next unless ($paths->{$c} &&
  4963. ($paths->{$c}->{action} =~ /^[AR]$/));
  4964. get_dir_check($self, $exists, $g, $r);
  4965. }
  4966. }
  4967. values %$exists;
  4968. }
  4969. sub minimize_url {
  4970. my ($self) = @_;
  4971. return $self->{url} if ($self->{url} eq $self->{repos_root});
  4972. my $url = $self->{repos_root};
  4973. my @components = split(m!/!, $self->{svn_path});
  4974. my $c = '';
  4975. do {
  4976. $url .= "/$c" if length $c;
  4977. eval {
  4978. my $ra = (ref $self)->new($url);
  4979. my $latest = $ra->get_latest_revnum;
  4980. $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
  4981. };
  4982. } while ($@ && ($c = shift @components));
  4983. $url;
  4984. }
  4985. sub can_do_switch {
  4986. my $self = shift;
  4987. unless (defined $can_do_switch) {
  4988. my $pool = SVN::Pool->new;
  4989. my $rep = eval {
  4990. $self->do_switch(1, '', 0, $self->{url},
  4991. SVN::Delta::Editor->new, $pool);
  4992. };
  4993. if ($@) {
  4994. $can_do_switch = 0;
  4995. } else {
  4996. $rep->abort_report($pool);
  4997. $can_do_switch = 1;
  4998. }
  4999. $pool->clear;
  5000. }
  5001. $can_do_switch;
  5002. }
  5003. sub skip_unknown_revs {
  5004. my ($err) = @_;
  5005. my $errno = $err->apr_err();
  5006. # Maybe the branch we're tracking didn't
  5007. # exist when the repo started, so it's
  5008. # not an error if it doesn't, just continue
  5009. #
  5010. # Wonderfully consistent library, eh?
  5011. # 160013 - svn:// and file://
  5012. # 175002 - http(s)://
  5013. # 175007 - http(s):// (this repo required authorization, too...)
  5014. # More codes may be discovered later...
  5015. if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
  5016. my $err_key = $err->expanded_message;
  5017. # revision numbers change every time, filter them out
  5018. $err_key =~ s/\d+/\0/g;
  5019. $err_key = "$errno\0$err_key";
  5020. unless ($ignored_err{$err_key}) {
  5021. warn "W: Ignoring error from SVN, path probably ",
  5022. "does not exist: ($errno): ",
  5023. $err->expanded_message,"\n";
  5024. warn "W: Do not be alarmed at the above message ",
  5025. "git-svn is just searching aggressively for ",
  5026. "old history.\n",
  5027. "This may take a while on large repositories\n";
  5028. $ignored_err{$err_key} = 1;
  5029. }
  5030. return;
  5031. }
  5032. die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
  5033. }
  5034. package Git::SVN::Log;
  5035. use strict;
  5036. use warnings;
  5037. use POSIX qw/strftime/;
  5038. use Time::Local;
  5039. use constant commit_log_separator => ('-' x 72) . "\n";
  5040. use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
  5041. %rusers $show_commit $incremental/;
  5042. my $l_fmt;
  5043. sub cmt_showable {
  5044. my ($c) = @_;
  5045. return 1 if defined $c->{r};
  5046. # big commit message got truncated by the 16k pretty buffer in rev-list
  5047. if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
  5048. $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
  5049. @{$c->{l}} = ();
  5050. my @log = command(qw/cat-file commit/, $c->{c});
  5051. # shift off the headers
  5052. shift @log while ($log[0] ne '');
  5053. shift @log;
  5054. # TODO: make $c->{l} not have a trailing newline in the future
  5055. @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
  5056. (undef, $c->{r}, undef) = ::extract_metadata(
  5057. (grep(/^git-svn-id: /, @log))[-1]);
  5058. }
  5059. return defined $c->{r};
  5060. }
  5061. sub log_use_color {
  5062. return $color || Git->repository->get_colorbool('color.diff');
  5063. }
  5064. sub git_svn_log_cmd {
  5065. my ($r_min, $r_max, @args) = @_;
  5066. my $head = 'HEAD';
  5067. my (@files, @log_opts);
  5068. foreach my $x (@args) {
  5069. if ($x eq '--' || @files) {
  5070. push @files, $x;
  5071. } else {
  5072. if (::verify_ref("$x^0")) {
  5073. $head = $x;
  5074. } else {
  5075. push @log_opts, $x;
  5076. }
  5077. }
  5078. }
  5079. my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
  5080. $gs ||= Git::SVN->_new;
  5081. my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
  5082. $gs->refname);
  5083. push @cmd, '-r' unless $non_recursive;
  5084. push @cmd, qw/--raw --name-status/ if $verbose;
  5085. push @cmd, '--color' if log_use_color();
  5086. push @cmd, @log_opts;
  5087. if (defined $r_max && $r_max == $r_min) {
  5088. push @cmd, '--max-count=1';
  5089. if (my $c = $gs->rev_map_get($r_max)) {
  5090. push @cmd, $c;
  5091. }
  5092. } elsif (defined $r_max) {
  5093. if ($r_max < $r_min) {
  5094. ($r_min, $r_max) = ($r_max, $r_min);
  5095. }
  5096. my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
  5097. my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
  5098. # If there are no commits in the range, both $c_max and $c_min
  5099. # will be undefined. If there is at least 1 commit in the
  5100. # range, both will be defined.
  5101. return () if !defined $c_min || !defined $c_max;
  5102. if ($c_min eq $c_max) {
  5103. push @cmd, '--max-count=1', $c_min;
  5104. } else {
  5105. push @cmd, '--boundary', "$c_min..$c_max";
  5106. }
  5107. }
  5108. return (@cmd, @files);
  5109. }
  5110. # adapted from pager.c
  5111. sub config_pager {
  5112. if (! -t *STDOUT) {
  5113. $ENV{GIT_PAGER_IN_USE} = 'false';
  5114. $pager = undef;
  5115. return;
  5116. }
  5117. chomp($pager = command_oneline(qw(var GIT_PAGER)));
  5118. if ($pager eq 'cat') {
  5119. $pager = undef;
  5120. }
  5121. $ENV{GIT_PAGER_IN_USE} = defined($pager);
  5122. }
  5123. sub run_pager {
  5124. return unless defined $pager;
  5125. pipe my ($rfd, $wfd) or return;
  5126. defined(my $pid = fork) or ::fatal "Can't fork: $!";
  5127. if (!$pid) {
  5128. open STDOUT, '>&', $wfd or
  5129. ::fatal "Can't redirect to stdout: $!";
  5130. return;
  5131. }
  5132. open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
  5133. $ENV{LESS} ||= 'FRSX';
  5134. exec $pager or ::fatal "Can't run pager: $! ($pager)";
  5135. }
  5136. sub format_svn_date {
  5137. # some systmes don't handle or mishandle %z, so be creative.
  5138. my $t = shift || time;
  5139. my $gm = timelocal(gmtime($t));
  5140. my $sign = qw( + + - )[ $t <=> $gm ];
  5141. my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
  5142. return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
  5143. }
  5144. sub parse_git_date {
  5145. my ($t, $tz) = @_;
  5146. # Date::Parse isn't in the standard Perl distro :(
  5147. if ($tz =~ s/^\+//) {
  5148. $t += tz_to_s_offset($tz);
  5149. } elsif ($tz =~ s/^\-//) {
  5150. $t -= tz_to_s_offset($tz);
  5151. }
  5152. return $t;
  5153. }
  5154. sub set_local_timezone {
  5155. if (defined $TZ) {
  5156. $ENV{TZ} = $TZ;
  5157. } else {
  5158. delete $ENV{TZ};
  5159. }
  5160. }
  5161. sub tz_to_s_offset {
  5162. my ($tz) = @_;
  5163. $tz =~ s/(\d\d)$//;
  5164. return ($1 * 60) + ($tz * 3600);
  5165. }
  5166. sub get_author_info {
  5167. my ($dest, $author, $t, $tz) = @_;
  5168. $author =~ s/(?:^\s*|\s*$)//g;
  5169. $dest->{a_raw} = $author;
  5170. my $au;
  5171. if ($::_authors) {
  5172. $au = $rusers{$author} || undef;
  5173. }
  5174. if (!$au) {
  5175. ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
  5176. }
  5177. $dest->{t} = $t;
  5178. $dest->{tz} = $tz;
  5179. $dest->{a} = $au;
  5180. $dest->{t_utc} = parse_git_date($t, $tz);
  5181. }
  5182. sub process_commit {
  5183. my ($c, $r_min, $r_max, $defer) = @_;
  5184. if (defined $r_min && defined $r_max) {
  5185. if ($r_min == $c->{r} && $r_min == $r_max) {
  5186. show_commit($c);
  5187. return 0;
  5188. }
  5189. return 1 if $r_min == $r_max;
  5190. if ($r_min < $r_max) {
  5191. # we need to reverse the print order
  5192. return 0 if (defined $limit && --$limit < 0);
  5193. push @$defer, $c;
  5194. return 1;
  5195. }
  5196. if ($r_min != $r_max) {
  5197. return 1 if ($r_min < $c->{r});
  5198. return 1 if ($r_max > $c->{r});
  5199. }
  5200. }
  5201. return 0 if (defined $limit && --$limit < 0);
  5202. show_commit($c);
  5203. return 1;
  5204. }
  5205. sub show_commit {
  5206. my $c = shift;
  5207. if ($oneline) {
  5208. my $x = "\n";
  5209. if (my $l = $c->{l}) {
  5210. while ($l->[0] =~ /^\s*$/) { shift @$l }
  5211. $x = $l->[0];
  5212. }
  5213. $l_fmt ||= 'A' . length($c->{r});
  5214. print 'r',pack($l_fmt, $c->{r}),' | ';
  5215. print "$c->{c} | " if $show_commit;
  5216. print $x;
  5217. } else {
  5218. show_commit_normal($c);
  5219. }
  5220. }
  5221. sub show_commit_changed_paths {
  5222. my ($c) = @_;
  5223. return unless $c->{changed};
  5224. print "Changed paths:\n", @{$c->{changed}};
  5225. }
  5226. sub show_commit_normal {
  5227. my ($c) = @_;
  5228. print commit_log_separator, "r$c->{r} | ";
  5229. print "$c->{c} | " if $show_commit;
  5230. print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
  5231. my $nr_line = 0;
  5232. if (my $l = $c->{l}) {
  5233. while ($l->[$#$l] eq "\n" && $#$l > 0
  5234. && $l->[($#$l - 1)] eq "\n") {
  5235. pop @$l;
  5236. }
  5237. $nr_line = scalar @$l;
  5238. if (!$nr_line) {
  5239. print "1 line\n\n\n";
  5240. } else {
  5241. if ($nr_line == 1) {
  5242. $nr_line = '1 line';
  5243. } else {
  5244. $nr_line .= ' lines';
  5245. }
  5246. print $nr_line, "\n";
  5247. show_commit_changed_paths($c);
  5248. print "\n";
  5249. print $_ foreach @$l;
  5250. }
  5251. } else {
  5252. print "1 line\n";
  5253. show_commit_changed_paths($c);
  5254. print "\n";
  5255. }
  5256. foreach my $x (qw/raw stat diff/) {
  5257. if ($c->{$x}) {
  5258. print "\n";
  5259. print $_ foreach @{$c->{$x}}
  5260. }
  5261. }
  5262. }
  5263. sub cmd_show_log {
  5264. my (@args) = @_;
  5265. my ($r_min, $r_max);
  5266. my $r_last = -1; # prevent dupes
  5267. set_local_timezone();
  5268. if (defined $::_revision) {
  5269. if ($::_revision =~ /^(\d+):(\d+)$/) {
  5270. ($r_min, $r_max) = ($1, $2);
  5271. } elsif ($::_revision =~ /^\d+$/) {
  5272. $r_min = $r_max = $::_revision;
  5273. } else {
  5274. ::fatal "-r$::_revision is not supported, use ",
  5275. "standard 'git log' arguments instead";
  5276. }
  5277. }
  5278. config_pager();
  5279. @args = git_svn_log_cmd($r_min, $r_max, @args);
  5280. if (!@args) {
  5281. print commit_log_separator unless $incremental || $oneline;
  5282. return;
  5283. }
  5284. my $log = command_output_pipe(@args);
  5285. run_pager();
  5286. my (@k, $c, $d, $stat);
  5287. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  5288. while (<$log>) {
  5289. if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
  5290. my $cmt = $1;
  5291. if ($c && cmt_showable($c) && $c->{r} != $r_last) {
  5292. $r_last = $c->{r};
  5293. process_commit($c, $r_min, $r_max, \@k) or
  5294. goto out;
  5295. }
  5296. $d = undef;
  5297. $c = { c => $cmt };
  5298. } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
  5299. get_author_info($c, $1, $2, $3);
  5300. } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
  5301. # ignore
  5302. } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
  5303. push @{$c->{raw}}, $_;
  5304. } elsif (/^${esc_color}[ACRMDT]\t/) {
  5305. # we could add $SVN->{svn_path} here, but that requires
  5306. # remote access at the moment (repo_path_split)...
  5307. s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
  5308. push @{$c->{changed}}, $_;
  5309. } elsif (/^${esc_color}diff /o) {
  5310. $d = 1;
  5311. push @{$c->{diff}}, $_;
  5312. } elsif ($d) {
  5313. push @{$c->{diff}}, $_;
  5314. } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
  5315. $esc_color*[\+\-]*$esc_color$/x) {
  5316. $stat = 1;
  5317. push @{$c->{stat}}, $_;
  5318. } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
  5319. push @{$c->{stat}}, $_;
  5320. $stat = undef;
  5321. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  5322. ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
  5323. } elsif (s/^${esc_color} //o) {
  5324. push @{$c->{l}}, $_;
  5325. }
  5326. }
  5327. if ($c && defined $c->{r} && $c->{r} != $r_last) {
  5328. $r_last = $c->{r};
  5329. process_commit($c, $r_min, $r_max, \@k);
  5330. }
  5331. if (@k) {
  5332. ($r_min, $r_max) = ($r_max, $r_min);
  5333. process_commit($_, $r_min, $r_max) foreach reverse @k;
  5334. }
  5335. out:
  5336. close $log;
  5337. print commit_log_separator unless $incremental || $oneline;
  5338. }
  5339. sub cmd_blame {
  5340. my $path = pop;
  5341. config_pager();
  5342. run_pager();
  5343. my ($fh, $ctx, $rev);
  5344. if ($_git_format) {
  5345. ($fh, $ctx) = command_output_pipe('blame', @_, $path);
  5346. while (my $line = <$fh>) {
  5347. if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
  5348. # Uncommitted edits show up as a rev ID of
  5349. # all zeros, which we can't look up with
  5350. # cmt_metadata
  5351. if ($1 !~ /^0+$/) {
  5352. (undef, $rev, undef) =
  5353. ::cmt_metadata($1);
  5354. $rev = '0' if (!$rev);
  5355. } else {
  5356. $rev = '0';
  5357. }
  5358. $rev = sprintf('%-10s', $rev);
  5359. $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
  5360. }
  5361. print $line;
  5362. }
  5363. } else {
  5364. ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
  5365. '--', $path);
  5366. my ($sha1);
  5367. my %authors;
  5368. my @buffer;
  5369. my %dsha; #distinct sha keys
  5370. while (my $line = <$fh>) {
  5371. push @buffer, $line;
  5372. if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
  5373. $dsha{$1} = 1;
  5374. }
  5375. }
  5376. my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
  5377. foreach my $line (@buffer) {
  5378. if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
  5379. $rev = $s2r->{$1};
  5380. $rev = '0' if (!$rev)
  5381. }
  5382. elsif ($line =~ /^author (.*)/) {
  5383. $authors{$rev} = $1;
  5384. $authors{$rev} =~ s/\s/_/g;
  5385. }
  5386. elsif ($line =~ /^\t(.*)$/) {
  5387. printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
  5388. }
  5389. }
  5390. }
  5391. command_close_pipe($fh, $ctx);
  5392. }
  5393. package Git::SVN::Migration;
  5394. # these version numbers do NOT correspond to actual version numbers
  5395. # of git nor git-svn. They are just relative.
  5396. #
  5397. # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
  5398. #
  5399. # v1 layout: .git/$id/info/url, refs/remotes/$id
  5400. #
  5401. # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
  5402. #
  5403. # v3 layout: .git/svn/$id, refs/remotes/$id
  5404. # - info/url may remain for backwards compatibility
  5405. # - this is what we migrate up to this layout automatically,
  5406. # - this will be used by git svn init on single branches
  5407. # v3.1 layout (auto migrated):
  5408. # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
  5409. # for backwards compatibility
  5410. #
  5411. # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
  5412. # - this is only created for newly multi-init-ed
  5413. # repositories. Similar in spirit to the
  5414. # --use-separate-remotes option in git-clone (now default)
  5415. # - we do not automatically migrate to this (following
  5416. # the example set by core git)
  5417. #
  5418. # v5 layout: .rev_db.$UUID => .rev_map.$UUID
  5419. # - newer, more-efficient format that uses 24-bytes per record
  5420. # with no filler space.
  5421. # - use xxd -c24 < .rev_map.$UUID to view and debug
  5422. # - This is a one-way migration, repositories updated to the
  5423. # new format will not be able to use old git-svn without
  5424. # rebuilding the .rev_db. Rebuilding the rev_db is not
  5425. # possible if noMetadata or useSvmProps are set; but should
  5426. # be no problem for users that use the (sensible) defaults.
  5427. use strict;
  5428. use warnings;
  5429. use Carp qw/croak/;
  5430. use File::Path qw/mkpath/;
  5431. use File::Basename qw/dirname basename/;
  5432. use vars qw/$_minimize/;
  5433. sub migrate_from_v0 {
  5434. my $git_dir = $ENV{GIT_DIR};
  5435. return undef unless -d $git_dir;
  5436. my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
  5437. my $migrated = 0;
  5438. while (<$fh>) {
  5439. chomp;
  5440. my ($id, $orig_ref) = ($_, $_);
  5441. next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
  5442. next unless -f "$git_dir/$id/info/url";
  5443. my $new_ref = "refs/remotes/$id";
  5444. if (::verify_ref("$new_ref^0")) {
  5445. print STDERR "W: $orig_ref is probably an old ",
  5446. "branch used by an ancient version of ",
  5447. "git-svn.\n",
  5448. "However, $new_ref also exists.\n",
  5449. "We will not be able ",
  5450. "to use this branch until this ",
  5451. "ambiguity is resolved.\n";
  5452. next;
  5453. }
  5454. print STDERR "Migrating from v0 layout...\n" if !$migrated;
  5455. print STDERR "Renaming ref: $orig_ref => $new_ref\n";
  5456. command_noisy('update-ref', $new_ref, $orig_ref);
  5457. command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
  5458. $migrated++;
  5459. }
  5460. command_close_pipe($fh, $ctx);
  5461. print STDERR "Done migrating from v0 layout...\n" if $migrated;
  5462. $migrated;
  5463. }
  5464. sub migrate_from_v1 {
  5465. my $git_dir = $ENV{GIT_DIR};
  5466. my $migrated = 0;
  5467. return $migrated unless -d $git_dir;
  5468. my $svn_dir = "$git_dir/svn";
  5469. # just in case somebody used 'svn' as their $id at some point...
  5470. return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
  5471. print STDERR "Migrating from a git-svn v1 layout...\n";
  5472. mkpath([$svn_dir]);
  5473. print STDERR "Data from a previous version of git-svn exists, but\n\t",
  5474. "$svn_dir\n\t(required for this version ",
  5475. "($::VERSION) of git-svn) does not exist.\n";
  5476. my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
  5477. while (<$fh>) {
  5478. my $x = $_;
  5479. next unless $x =~ s#^refs/remotes/##;
  5480. chomp $x;
  5481. next unless -f "$git_dir/$x/info/url";
  5482. my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
  5483. next unless $u;
  5484. my $dn = dirname("$git_dir/svn/$x");
  5485. mkpath([$dn]) unless -d $dn;
  5486. if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
  5487. mkpath(["$git_dir/svn/svn"]);
  5488. print STDERR " - $git_dir/$x/info => ",
  5489. "$git_dir/svn/$x/info\n";
  5490. rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
  5491. croak "$!: $x";
  5492. # don't worry too much about these, they probably
  5493. # don't exist with repos this old (save for index,
  5494. # and we can easily regenerate that)
  5495. foreach my $f (qw/unhandled.log index .rev_db/) {
  5496. rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
  5497. }
  5498. } else {
  5499. print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
  5500. rename "$git_dir/$x", "$git_dir/svn/$x" or
  5501. croak "$!: $x";
  5502. }
  5503. $migrated++;
  5504. }
  5505. command_close_pipe($fh, $ctx);
  5506. print STDERR "Done migrating from a git-svn v1 layout\n";
  5507. $migrated;
  5508. }
  5509. sub read_old_urls {
  5510. my ($l_map, $pfx, $path) = @_;
  5511. my @dir;
  5512. foreach (<$path/*>) {
  5513. if (-r "$_/info/url") {
  5514. $pfx .= '/' if $pfx && $pfx !~ m!/$!;
  5515. my $ref_id = $pfx . basename $_;
  5516. my $url = ::file_to_s("$_/info/url");
  5517. $l_map->{$ref_id} = $url;
  5518. } elsif (-d $_) {
  5519. push @dir, $_;
  5520. }
  5521. }
  5522. foreach (@dir) {
  5523. my $x = $_;
  5524. $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
  5525. read_old_urls($l_map, $x, $_);
  5526. }
  5527. }
  5528. sub migrate_from_v2 {
  5529. my @cfg = command(qw/config -l/);
  5530. return if grep /^svn-remote\..+\.url=/, @cfg;
  5531. my %l_map;
  5532. read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
  5533. my $migrated = 0;
  5534. foreach my $ref_id (sort keys %l_map) {
  5535. eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
  5536. if ($@) {
  5537. Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
  5538. }
  5539. $migrated++;
  5540. }
  5541. $migrated;
  5542. }
  5543. sub minimize_connections {
  5544. my $r = Git::SVN::read_all_remotes();
  5545. my $new_urls = {};
  5546. my $root_repos = {};
  5547. foreach my $repo_id (keys %$r) {
  5548. my $url = $r->{$repo_id}->{url} or next;
  5549. my $fetch = $r->{$repo_id}->{fetch} or next;
  5550. my $ra = Git::SVN::Ra->new($url);
  5551. # skip existing cases where we already connect to the root
  5552. if (($ra->{url} eq $ra->{repos_root}) ||
  5553. ($ra->{repos_root} eq $repo_id)) {
  5554. $root_repos->{$ra->{url}} = $repo_id;
  5555. next;
  5556. }
  5557. my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
  5558. my $root_path = $ra->{url};
  5559. $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
  5560. foreach my $path (keys %$fetch) {
  5561. my $ref_id = $fetch->{$path};
  5562. my $gs = Git::SVN->new($ref_id, $repo_id, $path);
  5563. # make sure we can read when connecting to
  5564. # a higher level of a repository
  5565. my ($last_rev, undef) = $gs->last_rev_commit;
  5566. if (!defined $last_rev) {
  5567. $last_rev = eval {
  5568. $root_ra->get_latest_revnum;
  5569. };
  5570. next if $@;
  5571. }
  5572. my $new = $root_path;
  5573. $new .= length $path ? "/$path" : '';
  5574. eval {
  5575. $root_ra->get_log([$new], $last_rev, $last_rev,
  5576. 0, 0, 1, sub { });
  5577. };
  5578. next if $@;
  5579. $new_urls->{$ra->{repos_root}}->{$new} =
  5580. { ref_id => $ref_id,
  5581. old_repo_id => $repo_id,
  5582. old_path => $path };
  5583. }
  5584. }
  5585. my @emptied;
  5586. foreach my $url (keys %$new_urls) {
  5587. # see if we can re-use an existing [svn-remote "repo_id"]
  5588. # instead of creating a(n ugly) new section:
  5589. my $repo_id = $root_repos->{$url} || $url;
  5590. my $fetch = $new_urls->{$url};
  5591. foreach my $path (keys %$fetch) {
  5592. my $x = $fetch->{$path};
  5593. Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
  5594. my $pfx = "svn-remote.$x->{old_repo_id}";
  5595. my $old_fetch = quotemeta("$x->{old_path}:".
  5596. "$x->{ref_id}");
  5597. command_noisy(qw/config --unset/,
  5598. "$pfx.fetch", '^'. $old_fetch . '$');
  5599. delete $r->{$x->{old_repo_id}}->
  5600. {fetch}->{$x->{old_path}};
  5601. if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
  5602. command_noisy(qw/config --unset/,
  5603. "$pfx.url");
  5604. push @emptied, $x->{old_repo_id}
  5605. }
  5606. }
  5607. }
  5608. if (@emptied) {
  5609. my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
  5610. print STDERR <<EOF;
  5611. The following [svn-remote] sections in your config file ($file) are empty
  5612. and can be safely removed:
  5613. EOF
  5614. print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
  5615. }
  5616. }
  5617. sub migration_check {
  5618. migrate_from_v0();
  5619. migrate_from_v1();
  5620. migrate_from_v2();
  5621. minimize_connections() if $_minimize;
  5622. }
  5623. package Git::IndexInfo;
  5624. use strict;
  5625. use warnings;
  5626. use Git qw/command_input_pipe command_close_pipe/;
  5627. sub new {
  5628. my ($class) = @_;
  5629. my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
  5630. bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
  5631. }
  5632. sub remove {
  5633. my ($self, $path) = @_;
  5634. if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
  5635. return ++$self->{nr};
  5636. }
  5637. undef;
  5638. }
  5639. sub update {
  5640. my ($self, $mode, $hash, $path) = @_;
  5641. if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
  5642. return ++$self->{nr};
  5643. }
  5644. undef;
  5645. }
  5646. sub DESTROY {
  5647. my ($self) = @_;
  5648. command_close_pipe($self->{gui}, $self->{ctx});
  5649. }
  5650. package Git::SVN::GlobSpec;
  5651. use strict;
  5652. use warnings;
  5653. sub new {
  5654. my ($class, $glob, $pattern_ok) = @_;
  5655. my $re = $glob;
  5656. $re =~ s!/+$!!g; # no need for trailing slashes
  5657. my (@left, @right, @patterns);
  5658. my $state = "left";
  5659. my $die_msg = "Only one set of wildcard directories " .
  5660. "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
  5661. for my $part (split(m|/|, $glob)) {
  5662. if ($part =~ /\*/ && $part ne "*") {
  5663. die "Invalid pattern in '$glob': $part\n";
  5664. } elsif ($pattern_ok && $part =~ /[{}]/ &&
  5665. $part !~ /^\{[^{}]+\}/) {
  5666. die "Invalid pattern in '$glob': $part\n";
  5667. }
  5668. if ($part eq "*") {
  5669. die $die_msg if $state eq "right";
  5670. $state = "pattern";
  5671. push(@patterns, "[^/]*");
  5672. } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
  5673. die $die_msg if $state eq "right";
  5674. $state = "pattern";
  5675. my $p = quotemeta($1);
  5676. $p =~ s/\\,/|/g;
  5677. push(@patterns, "(?:$p)");
  5678. } else {
  5679. if ($state eq "left") {
  5680. push(@left, $part);
  5681. } else {
  5682. push(@right, $part);
  5683. $state = "right";
  5684. }
  5685. }
  5686. }
  5687. my $depth = @patterns;
  5688. if ($depth == 0) {
  5689. die "One '*' is needed in glob: '$glob'\n";
  5690. }
  5691. my $left = join('/', @left);
  5692. my $right = join('/', @right);
  5693. $re = join('/', @patterns);
  5694. $re = join('\/',
  5695. grep(length, quotemeta($left), "($re)", quotemeta($right)));
  5696. my $left_re = qr/^\/\Q$left\E(\/|$)/;
  5697. bless { left => $left, right => $right, left_regex => $left_re,
  5698. regex => qr/$re/, glob => $glob, depth => $depth }, $class;
  5699. }
  5700. sub full_path {
  5701. my ($self, $path) = @_;
  5702. return (length $self->{left} ? "$self->{left}/" : '') .
  5703. $path . (length $self->{right} ? "/$self->{right}" : '');
  5704. }
  5705. __END__
  5706. Data structures:
  5707. $remotes = { # returned by read_all_remotes()
  5708. 'svn' => {
  5709. # svn-remote.svn.url=https://svn.musicpd.org
  5710. url => 'https://svn.musicpd.org',
  5711. # svn-remote.svn.fetch=mpd/trunk:trunk
  5712. fetch => {
  5713. 'mpd/trunk' => 'trunk',
  5714. },
  5715. # svn-remote.svn.tags=mpd/tags/*:tags/*
  5716. tags => {
  5717. path => {
  5718. left => 'mpd/tags',
  5719. right => '',
  5720. regex => qr!mpd/tags/([^/]+)$!,
  5721. glob => 'tags/*',
  5722. },
  5723. ref => {
  5724. left => 'tags',
  5725. right => '',
  5726. regex => qr!tags/([^/]+)$!,
  5727. glob => 'tags/*',
  5728. },
  5729. }
  5730. }
  5731. };
  5732. $log_entry hashref as returned by libsvn_log_entry()
  5733. {
  5734. log => 'whitespace-formatted log entry
  5735. ', # trailing newline is preserved
  5736. revision => '8', # integer
  5737. date => '2004-02-24T17:01:44.108345Z', # commit date
  5738. author => 'committer name'
  5739. };
  5740. # this is generated by generate_diff();
  5741. @mods = array of diff-index line hashes, each element represents one line
  5742. of diff-index output
  5743. diff-index line ($m hash)
  5744. {
  5745. mode_a => first column of diff-index output, no leading ':',
  5746. mode_b => second column of diff-index output,
  5747. sha1_b => sha1sum of the final blob,
  5748. chg => change type [MCRADT],
  5749. file_a => original file name of a file (iff chg is 'C' or 'R')
  5750. file_b => new/current file name of a file (any chg)
  5751. }
  5752. ;
  5753. # retval of read_url_paths{,_all}();
  5754. $l_map = {
  5755. # repository root url
  5756. 'https://svn.musicpd.org' => {
  5757. # repository path # GIT_SVN_ID
  5758. 'mpd/trunk' => 'trunk',
  5759. 'mpd/tags/0.11.5' => 'tags/0.11.5',
  5760. },
  5761. }
  5762. Notes:
  5763. I don't trust the each() function on unless I created %hash myself
  5764. because the internal iterator may not have started at base.