PageRenderTime 43ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/git-1.7.11.2/git-svn.perl

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