THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2241 lines
63KB

  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. use Carp qw/croak/;
  13. use File::Basename qw/dirname basename/;
  14. use File::Path qw/mkpath/;
  15. use File::Spec;
  16. use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  17. use Memoize;
  18. use Git::SVN;
  19. use Git::SVN::Editor;
  20. use Git::SVN::Fetcher;
  21. use Git::SVN::Ra;
  22. use Git::SVN::Prompt;
  23. use Git::SVN::Log;
  24. use Git::SVN::Migration;
  25. use Git::SVN::Utils qw(
  26. fatal
  27. can_compress
  28. canonicalize_path
  29. canonicalize_url
  30. join_paths
  31. add_path_to_url
  32. join_paths
  33. );
  34. use Git qw(
  35. git_cmd_try
  36. command
  37. command_oneline
  38. command_noisy
  39. command_output_pipe
  40. command_close_pipe
  41. command_bidi_pipe
  42. command_close_bidi_pipe
  43. get_record
  44. );
  45. BEGIN {
  46. Memoize::memoize 'Git::config';
  47. Memoize::memoize 'Git::config_bool';
  48. }
  49. # From which subdir have we been invoked?
  50. my $cmd_dir_prefix = eval {
  51. command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  52. } || '';
  53. $Git::SVN::Ra::_log_window_size = 100;
  54. if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
  55. $ENV{SVN_SSH} = $ENV{GIT_SSH};
  56. }
  57. if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
  58. $ENV{SVN_SSH} =~ s/\\/\\\\/g;
  59. $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
  60. }
  61. $Git::SVN::Log::TZ = $ENV{TZ};
  62. $ENV{TZ} = 'UTC';
  63. $| = 1; # unbuffer STDOUT
  64. # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
  65. # repository decides to close the connection which we expect to be kept alive.
  66. $SIG{PIPE} = 'IGNORE';
  67. # Given a dot separated version number, "subtract" it from
  68. # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
  69. # is at least at the version the caller asked for.
  70. sub compare_svn_version {
  71. my (@ours) = split(/\./, $SVN::Core::VERSION);
  72. my (@theirs) = split(/\./, $_[0]);
  73. my ($i, $diff);
  74. for ($i = 0; $i < @ours && $i < @theirs; $i++) {
  75. $diff = $ours[$i] - $theirs[$i];
  76. return $diff if ($diff);
  77. }
  78. return 1 if ($i < @ours);
  79. return -1 if ($i < @theirs);
  80. return 0;
  81. }
  82. sub _req_svn {
  83. require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  84. require SVN::Ra;
  85. require SVN::Delta;
  86. if (::compare_svn_version('1.1.0') < 0) {
  87. fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  88. }
  89. }
  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. $_before, $_after,
  97. $_merge, $_strategy, $_preserve_merges, $_dry_run, $_parents, $_local,
  98. $_prefix, $_no_checkout, $_url, $_verbose,
  99. $_commit_url, $_tag, $_merge_info, $_interactive, $_set_svn_props);
  100. # This is a refactoring artifact so Git::SVN can get at this git-svn switch.
  101. sub opt_prefix { return $_prefix || '' }
  102. $Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
  103. $_q ||= 0;
  104. my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  105. 'config-dir=s' => \$Git::SVN::Ra::config_dir,
  106. 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
  107. 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
  108. 'include-paths=s' => \$Git::SVN::Fetcher::_include_regex,
  109. 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
  110. my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  111. 'authors-file|A=s' => \$_authors,
  112. 'authors-prog=s' => \$_authors_prog,
  113. 'repack:i' => \$Git::SVN::_repack,
  114. 'noMetadata' => \$Git::SVN::_no_metadata,
  115. 'useSvmProps' => \$Git::SVN::_use_svm_props,
  116. 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  117. 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  118. 'no-checkout' => \$_no_checkout,
  119. 'quiet|q+' => \$_q,
  120. 'repack-flags|repack-args|repack-opts=s' =>
  121. \$Git::SVN::_repack_flags,
  122. 'use-log-author' => \$Git::SVN::_use_log_author,
  123. 'add-author-from' => \$Git::SVN::_add_author_from,
  124. 'localtime' => \$Git::SVN::_localtime,
  125. %remote_opts );
  126. my ($_trunk, @_tags, @_branches, $_stdlayout);
  127. my %icv;
  128. my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  129. 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
  130. 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
  131. 'stdlayout|s' => \$_stdlayout,
  132. 'minimize-url|m!' => \$Git::SVN::_minimize_url,
  133. 'no-metadata' => sub { $icv{noMetadata} = 1 },
  134. 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  135. 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  136. 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  137. 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
  138. %remote_opts );
  139. my %cmt_opts = ( 'edit|e' => \$_edit,
  140. 'rmdir' => \$Git::SVN::Editor::_rmdir,
  141. 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
  142. 'l=i' => \$Git::SVN::Editor::_rename_limit,
  143. 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
  144. );
  145. my %cmd = (
  146. fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  147. { 'revision|r=s' => \$_revision,
  148. 'fetch-all|all' => \$_fetch_all,
  149. 'parent|p' => \$_fetch_parent,
  150. %fc_opts } ],
  151. clone => [ \&cmd_clone, "Initialize and fetch revisions",
  152. { 'revision|r=s' => \$_revision,
  153. 'preserve-empty-dirs' =>
  154. \$Git::SVN::Fetcher::_preserve_empty_dirs,
  155. 'placeholder-filename=s' =>
  156. \$Git::SVN::Fetcher::_placeholder_filename,
  157. %fc_opts, %init_opts } ],
  158. init => [ \&cmd_init, "Initialize a repo for tracking" .
  159. " (requires URL argument)",
  160. \%init_opts ],
  161. 'multi-init' => [ \&cmd_multi_init,
  162. "Deprecated alias for ".
  163. "'$0 init -T<trunk> -b<branches> -t<tags>'",
  164. \%init_opts ],
  165. dcommit => [ \&cmd_dcommit,
  166. 'Commit several diffs to merge with upstream',
  167. { 'merge|m|M' => \$_merge,
  168. 'strategy|s=s' => \$_strategy,
  169. 'verbose|v' => \$_verbose,
  170. 'dry-run|n' => \$_dry_run,
  171. 'fetch-all|all' => \$_fetch_all,
  172. 'commit-url=s' => \$_commit_url,
  173. 'set-svn-props=s' => \$_set_svn_props,
  174. 'revision|r=i' => \$_revision,
  175. 'no-rebase' => \$_no_rebase,
  176. 'mergeinfo=s' => \$_merge_info,
  177. 'interactive|i' => \$_interactive,
  178. %cmt_opts, %fc_opts } ],
  179. branch => [ \&cmd_branch,
  180. 'Create a branch in the SVN repository',
  181. { 'message|m=s' => \$_message,
  182. 'destination|d=s' => \$_branch_dest,
  183. 'dry-run|n' => \$_dry_run,
  184. 'parents' => \$_parents,
  185. 'tag|t' => \$_tag,
  186. 'username=s' => \$Git::SVN::Prompt::_username,
  187. 'commit-url=s' => \$_commit_url } ],
  188. tag => [ sub { $_tag = 1; cmd_branch(@_) },
  189. 'Create a tag in the SVN repository',
  190. { 'message|m=s' => \$_message,
  191. 'destination|d=s' => \$_branch_dest,
  192. 'dry-run|n' => \$_dry_run,
  193. 'parents' => \$_parents,
  194. 'username=s' => \$Git::SVN::Prompt::_username,
  195. 'commit-url=s' => \$_commit_url } ],
  196. 'set-tree' => [ \&cmd_set_tree,
  197. "Set an SVN repository to a git tree-ish",
  198. { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
  199. 'create-ignore' => [ \&cmd_create_ignore,
  200. 'Create a .gitignore per svn:ignore',
  201. { 'revision|r=i' => \$_revision
  202. } ],
  203. 'mkdirs' => [ \&cmd_mkdirs ,
  204. "recreate empty directories after a checkout",
  205. { 'revision|r=i' => \$_revision } ],
  206. 'propget' => [ \&cmd_propget,
  207. 'Print the value of a property on a file or directory',
  208. { 'revision|r=i' => \$_revision } ],
  209. 'propset' => [ \&cmd_propset,
  210. 'Set the value of a property on a file or directory - will be set on commit',
  211. {} ],
  212. 'proplist' => [ \&cmd_proplist,
  213. 'List all properties of a file or directory',
  214. { 'revision|r=i' => \$_revision } ],
  215. 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
  216. { 'revision|r=i' => \$_revision
  217. } ],
  218. 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
  219. { 'revision|r=i' => \$_revision
  220. } ],
  221. 'multi-fetch' => [ \&cmd_multi_fetch,
  222. "Deprecated alias for $0 fetch --all",
  223. { 'revision|r=s' => \$_revision, %fc_opts } ],
  224. 'migrate' => [ sub { },
  225. # no-op, we automatically run this anyways,
  226. 'Migrate configuration/metadata/layout from
  227. previous versions of git-svn',
  228. { 'minimize' => \$Git::SVN::Migration::_minimize,
  229. %remote_opts } ],
  230. 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
  231. { 'limit=i' => \$Git::SVN::Log::limit,
  232. 'revision|r=s' => \$_revision,
  233. 'verbose|v' => \$Git::SVN::Log::verbose,
  234. 'incremental' => \$Git::SVN::Log::incremental,
  235. 'oneline' => \$Git::SVN::Log::oneline,
  236. 'show-commit' => \$Git::SVN::Log::show_commit,
  237. 'non-recursive' => \$Git::SVN::Log::non_recursive,
  238. 'authors-file|A=s' => \$_authors,
  239. 'color' => \$Git::SVN::Log::color,
  240. 'pager=s' => \$Git::SVN::Log::pager
  241. } ],
  242. 'find-rev' => [ \&cmd_find_rev,
  243. "Translate between SVN revision numbers and tree-ish",
  244. { 'B|before' => \$_before,
  245. 'A|after' => \$_after } ],
  246. 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
  247. { 'merge|m|M' => \$_merge,
  248. 'verbose|v' => \$_verbose,
  249. 'strategy|s=s' => \$_strategy,
  250. 'local|l' => \$_local,
  251. 'fetch-all|all' => \$_fetch_all,
  252. 'dry-run|n' => \$_dry_run,
  253. 'preserve-merges|p' => \$_preserve_merges,
  254. %fc_opts } ],
  255. 'commit-diff' => [ \&cmd_commit_diff,
  256. 'Commit a diff between two trees',
  257. { 'message|m=s' => \$_message,
  258. 'file|F=s' => \$_file,
  259. 'revision|r=s' => \$_revision,
  260. %cmt_opts } ],
  261. 'info' => [ \&cmd_info,
  262. "Show info about the latest SVN revision
  263. on the current branch",
  264. { 'url' => \$_url, } ],
  265. 'blame' => [ \&Git::SVN::Log::cmd_blame,
  266. "Show what revision and author last modified each line of a file",
  267. { 'git-format' => \$Git::SVN::Log::_git_format } ],
  268. 'reset' => [ \&cmd_reset,
  269. "Undo fetches back to the specified SVN revision",
  270. { 'revision|r=s' => \$_revision,
  271. 'parent|p' => \$_fetch_parent } ],
  272. 'gc' => [ \&cmd_gc,
  273. "Compress unhandled.log files in .git/svn and remove " .
  274. "index files in .git/svn",
  275. {} ],
  276. );
  277. package FakeTerm;
  278. sub new {
  279. my ($class, $reason) = @_;
  280. return bless \$reason, shift;
  281. }
  282. sub readline {
  283. my $self = shift;
  284. die "Cannot use readline on FakeTerm: $$self";
  285. }
  286. package main;
  287. my $term;
  288. sub term_init {
  289. $term = eval {
  290. require Term::ReadLine;
  291. $ENV{"GIT_SVN_NOTTY"}
  292. ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
  293. : new Term::ReadLine 'git-svn';
  294. };
  295. if ($@) {
  296. $term = new FakeTerm "$@: going non-interactive";
  297. }
  298. }
  299. my $cmd;
  300. for (my $i = 0; $i < @ARGV; $i++) {
  301. if (defined $cmd{$ARGV[$i]}) {
  302. $cmd = $ARGV[$i];
  303. splice @ARGV, $i, 1;
  304. last;
  305. } elsif ($ARGV[$i] eq 'help') {
  306. $cmd = $ARGV[$i+1];
  307. usage(0);
  308. }
  309. };
  310. # make sure we're always running at the top-level working directory
  311. if ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
  312. $ENV{GIT_DIR} ||= ".git";
  313. # catch the submodule case
  314. if (-f $ENV{GIT_DIR}) {
  315. open(my $fh, '<', $ENV{GIT_DIR}) or
  316. die "failed to open $ENV{GIT_DIR}: $!\n";
  317. $ENV{GIT_DIR} = $1 if <$fh> =~ /^gitdir: (.+)$/;
  318. }
  319. } elsif ($cmd) {
  320. my ($git_dir, $cdup);
  321. git_cmd_try {
  322. $git_dir = command_oneline([qw/rev-parse --git-dir/]);
  323. } "Unable to find .git directory\n";
  324. git_cmd_try {
  325. $cdup = command_oneline(qw/rev-parse --show-cdup/);
  326. chomp $cdup if ($cdup);
  327. $cdup = "." unless ($cdup && length $cdup);
  328. } "Already at toplevel, but $git_dir not found\n";
  329. $ENV{GIT_DIR} = $git_dir;
  330. chdir $cdup or die "Unable to chdir up to '$cdup'\n";
  331. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  332. }
  333. my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  334. read_git_config(\%opts) if $ENV{GIT_DIR};
  335. if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
  336. Getopt::Long::Configure('pass_through');
  337. }
  338. my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
  339. 'minimize-connections' => \$Git::SVN::Migration::_minimize,
  340. 'id|i=s' => \$Git::SVN::default_ref_id,
  341. 'svn-remote|remote|R=s' => sub {
  342. $Git::SVN::no_reuse_existing = 1;
  343. $Git::SVN::default_repo_id = $_[1] });
  344. exit 1 if (!$rv && $cmd && $cmd ne 'log');
  345. usage(0) if $_help;
  346. version() if $_version;
  347. usage(1) unless defined $cmd;
  348. load_authors() if $_authors;
  349. if (defined $_authors_prog) {
  350. my $abs_file = File::Spec->rel2abs($_authors_prog);
  351. $_authors_prog = "'" . $abs_file . "'" if -x $abs_file;
  352. }
  353. unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
  354. Git::SVN::Migration::migration_check();
  355. }
  356. Git::SVN::init_vars();
  357. eval {
  358. Git::SVN::verify_remotes_sanity();
  359. $cmd{$cmd}->[0]->(@ARGV);
  360. post_fetch_checkout();
  361. };
  362. fatal $@ if $@;
  363. exit 0;
  364. ####################### primary functions ######################
  365. sub usage {
  366. my $exit = shift || 0;
  367. my $fd = $exit ? \*STDERR : \*STDOUT;
  368. print $fd <<"";
  369. git-svn - bidirectional operations between a single Subversion tree and git
  370. usage: git svn <command> [options] [arguments]\n
  371. print $fd "Available commands:\n" unless $cmd;
  372. foreach (sort keys %cmd) {
  373. next if $cmd && $cmd ne $_;
  374. next if /^multi-/; # don't show deprecated commands
  375. print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
  376. foreach (sort keys %{$cmd{$_}->[2]}) {
  377. # mixed-case options are for .git/config only
  378. next if /[A-Z]/ && /^[a-z]+$/i;
  379. # prints out arguments as they should be passed:
  380. my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
  381. print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
  382. "--$_" : "-$_" }
  383. split /\|/,$_)," $x\n";
  384. }
  385. }
  386. print $fd <<"";
  387. \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
  388. arbitrary identifier if you're tracking multiple SVN branches/repositories in
  389. one git repository and want to keep them separate. See git-svn(1) for more
  390. information.
  391. exit $exit;
  392. }
  393. sub version {
  394. ::_req_svn();
  395. print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
  396. exit 0;
  397. }
  398. sub ask {
  399. my ($prompt, %arg) = @_;
  400. my $valid_re = $arg{valid_re};
  401. my $default = $arg{default};
  402. my $resp;
  403. my $i = 0;
  404. term_init() unless $term;
  405. if ( !( defined($term->IN)
  406. && defined( fileno($term->IN) )
  407. && defined( $term->OUT )
  408. && defined( fileno($term->OUT) ) ) ){
  409. return defined($default) ? $default : undef;
  410. }
  411. while ($i++ < 10) {
  412. $resp = $term->readline($prompt);
  413. if (!defined $resp) { # EOF
  414. print "\n";
  415. return defined $default ? $default : undef;
  416. }
  417. if ($resp eq '' and defined $default) {
  418. return $default;
  419. }
  420. if (!defined $valid_re or $resp =~ /$valid_re/) {
  421. return $resp;
  422. }
  423. }
  424. return undef;
  425. }
  426. sub do_git_init_db {
  427. unless (-d $ENV{GIT_DIR}) {
  428. my @init_db = ('init');
  429. push @init_db, "--template=$_template" if defined $_template;
  430. if (defined $_shared) {
  431. if ($_shared =~ /[a-z]/) {
  432. push @init_db, "--shared=$_shared";
  433. } else {
  434. push @init_db, "--shared";
  435. }
  436. }
  437. command_noisy(@init_db);
  438. $_repository = Git->repository(Repository => ".git");
  439. }
  440. my $set;
  441. my $pfx = "svn-remote.$Git::SVN::default_repo_id";
  442. foreach my $i (keys %icv) {
  443. die "'$set' and '$i' cannot both be set\n" if $set;
  444. next unless defined $icv{$i};
  445. command_noisy('config', "$pfx.$i", $icv{$i});
  446. $set = $i;
  447. }
  448. my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
  449. command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
  450. if defined $$ignore_paths_regex;
  451. my $include_paths_regex = \$Git::SVN::Fetcher::_include_regex;
  452. command_noisy('config', "$pfx.include-paths", $$include_paths_regex)
  453. if defined $$include_paths_regex;
  454. my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
  455. command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
  456. if defined $$ignore_refs_regex;
  457. if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
  458. my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
  459. command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
  460. command_noisy('config', "$pfx.placeholder-filename", $$fname);
  461. }
  462. }
  463. sub init_subdir {
  464. my $repo_path = shift or return;
  465. mkpath([$repo_path]) unless -d $repo_path;
  466. chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
  467. $ENV{GIT_DIR} = '.git';
  468. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  469. }
  470. sub cmd_clone {
  471. my ($url, $path) = @_;
  472. if (!$url) {
  473. die "SVN repository location required ",
  474. "as a command-line argument\n";
  475. } elsif (!defined $path &&
  476. (defined $_trunk || @_branches || @_tags ||
  477. defined $_stdlayout) &&
  478. $url !~ m#^[a-z\+]+://#) {
  479. $path = $url;
  480. }
  481. $path = basename($url) if !defined $path || !length $path;
  482. my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
  483. cmd_init($url, $path);
  484. command_oneline('config', 'svn.authorsfile', $authors_absolute)
  485. if $_authors;
  486. Git::SVN::fetch_all($Git::SVN::default_repo_id);
  487. }
  488. sub cmd_init {
  489. if (defined $_stdlayout) {
  490. $_trunk = 'trunk' if (!defined $_trunk);
  491. @_tags = 'tags' if (! @_tags);
  492. @_branches = 'branches' if (! @_branches);
  493. }
  494. if (defined $_trunk || @_branches || @_tags) {
  495. return cmd_multi_init(@_);
  496. }
  497. my $url = shift or die "SVN repository location required ",
  498. "as a command-line argument\n";
  499. $url = canonicalize_url($url);
  500. init_subdir(@_);
  501. do_git_init_db();
  502. if ($Git::SVN::_minimize_url eq 'unset') {
  503. $Git::SVN::_minimize_url = 0;
  504. }
  505. Git::SVN->init($url);
  506. }
  507. sub cmd_fetch {
  508. if (grep /^\d+=./, @_) {
  509. die "'<rev>=<commit>' fetch arguments are ",
  510. "no longer supported.\n";
  511. }
  512. my ($remote) = @_;
  513. if (@_ > 1) {
  514. die "usage: $0 fetch [--all] [--parent] [svn-remote]\n";
  515. }
  516. $Git::SVN::no_reuse_existing = undef;
  517. if ($_fetch_parent) {
  518. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  519. unless ($gs) {
  520. die "Unable to determine upstream SVN information from ",
  521. "working tree history\n";
  522. }
  523. # just fetch, don't checkout.
  524. $_no_checkout = 'true';
  525. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  526. } elsif ($_fetch_all) {
  527. cmd_multi_fetch();
  528. } else {
  529. $remote ||= $Git::SVN::default_repo_id;
  530. Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
  531. }
  532. }
  533. sub cmd_set_tree {
  534. my (@commits) = @_;
  535. if ($_stdin || !@commits) {
  536. print "Reading from stdin...\n";
  537. @commits = ();
  538. while (<STDIN>) {
  539. if (/\b($sha1_short)\b/o) {
  540. unshift @commits, $1;
  541. }
  542. }
  543. }
  544. my @revs;
  545. foreach my $c (@commits) {
  546. my @tmp = command('rev-parse',$c);
  547. if (scalar @tmp == 1) {
  548. push @revs, $tmp[0];
  549. } elsif (scalar @tmp > 1) {
  550. push @revs, reverse(command('rev-list',@tmp));
  551. } else {
  552. fatal "Failed to rev-parse $c";
  553. }
  554. }
  555. my $gs = Git::SVN->new;
  556. my ($r_last, $cmt_last) = $gs->last_rev_commit;
  557. $gs->fetch;
  558. if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
  559. fatal "There are new revisions that were fetched ",
  560. "and need to be merged (or acknowledged) ",
  561. "before committing.\nlast rev: $r_last\n",
  562. " current: $gs->{last_rev}";
  563. }
  564. $gs->set_tree($_) foreach @revs;
  565. print "Done committing ",scalar @revs," revisions to SVN\n";
  566. unlink $gs->{index};
  567. }
  568. sub split_merge_info_range {
  569. my ($range) = @_;
  570. if ($range =~ /(\d+)-(\d+)/) {
  571. return (int($1), int($2));
  572. } else {
  573. return (int($range), int($range));
  574. }
  575. }
  576. sub combine_ranges {
  577. my ($in) = @_;
  578. my @fnums = ();
  579. my @arr = split(/,/, $in);
  580. for my $element (@arr) {
  581. my ($start, $end) = split_merge_info_range($element);
  582. push @fnums, $start;
  583. }
  584. my @sorted = @arr [ sort {
  585. $fnums[$a] <=> $fnums[$b]
  586. } 0..$#arr ];
  587. my @return = ();
  588. my $last = -1;
  589. my $first = -1;
  590. for my $element (@sorted) {
  591. my ($start, $end) = split_merge_info_range($element);
  592. if ($last == -1) {
  593. $first = $start;
  594. $last = $end;
  595. next;
  596. }
  597. if ($start <= $last+1) {
  598. if ($end > $last) {
  599. $last = $end;
  600. }
  601. next;
  602. }
  603. if ($first == $last) {
  604. push @return, "$first";
  605. } else {
  606. push @return, "$first-$last";
  607. }
  608. $first = $start;
  609. $last = $end;
  610. }
  611. if ($first != -1) {
  612. if ($first == $last) {
  613. push @return, "$first";
  614. } else {
  615. push @return, "$first-$last";
  616. }
  617. }
  618. return join(',', @return);
  619. }
  620. sub merge_revs_into_hash {
  621. my ($hash, $minfo) = @_;
  622. my @lines = split(' ', $minfo);
  623. for my $line (@lines) {
  624. my ($branchpath, $revs) = split(/:/, $line);
  625. if (exists($hash->{$branchpath})) {
  626. # Merge the two revision sets
  627. my $combined = "$hash->{$branchpath},$revs";
  628. $hash->{$branchpath} = combine_ranges($combined);
  629. } else {
  630. # Just do range combining for consolidation
  631. $hash->{$branchpath} = combine_ranges($revs);
  632. }
  633. }
  634. }
  635. sub merge_merge_info {
  636. my ($mergeinfo_one, $mergeinfo_two, $ignore_branch) = @_;
  637. my %result_hash = ();
  638. merge_revs_into_hash(\%result_hash, $mergeinfo_one);
  639. merge_revs_into_hash(\%result_hash, $mergeinfo_two);
  640. delete $result_hash{$ignore_branch} if $ignore_branch;
  641. my $result = '';
  642. # Sort below is for consistency's sake
  643. for my $branchname (sort keys(%result_hash)) {
  644. my $revlist = $result_hash{$branchname};
  645. $result .= "$branchname:$revlist\n"
  646. }
  647. return $result;
  648. }
  649. sub populate_merge_info {
  650. my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
  651. my %parentshash;
  652. read_commit_parents(\%parentshash, $d);
  653. my @parents = @{$parentshash{$d}};
  654. if ($#parents > 0) {
  655. # Merge commit
  656. my $all_parents_ok = 1;
  657. my $aggregate_mergeinfo = '';
  658. my $rooturl = $gs->repos_root;
  659. my ($target_branch) = $gs->full_pushurl =~ /^\Q$rooturl\E(.*)/;
  660. if (defined($rewritten_parent)) {
  661. # Replace first parent with newly-rewritten version
  662. shift @parents;
  663. unshift @parents, $rewritten_parent;
  664. }
  665. foreach my $parent (@parents) {
  666. my ($branchurl, $svnrev, $paruuid) =
  667. cmt_metadata($parent);
  668. unless (defined($svnrev)) {
  669. # Should have been caught be preflight check
  670. fatal "merge commit $d has ancestor $parent, but that change "
  671. ."does not have git-svn metadata!";
  672. }
  673. unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
  674. fatal "commit $parent git-svn metadata changed mid-run!";
  675. }
  676. my $branchpath = $1;
  677. my $ra = Git::SVN::Ra->new($branchurl);
  678. my (undef, undef, $props) =
  679. $ra->get_dir(canonicalize_path("."), $svnrev);
  680. my $par_mergeinfo = $props->{'svn:mergeinfo'};
  681. unless (defined $par_mergeinfo) {
  682. $par_mergeinfo = '';
  683. }
  684. # Merge previous mergeinfo values
  685. $aggregate_mergeinfo =
  686. merge_merge_info($aggregate_mergeinfo,
  687. $par_mergeinfo,
  688. $target_branch);
  689. next if $parent eq $parents[0]; # Skip first parent
  690. # Add new changes being placed in tree by merge
  691. my @cmd = (qw/rev-list --reverse/,
  692. $parent, qw/--not/);
  693. foreach my $par (@parents) {
  694. unless ($par eq $parent) {
  695. push @cmd, $par;
  696. }
  697. }
  698. my @revsin = ();
  699. my ($revlist, $ctx) = command_output_pipe(@cmd);
  700. while (<$revlist>) {
  701. my $irev = $_;
  702. chomp $irev;
  703. my (undef, $csvnrev, undef) =
  704. cmt_metadata($irev);
  705. unless (defined $csvnrev) {
  706. # A child is missing SVN annotations...
  707. # this might be OK, or might not be.
  708. warn "W:child $irev is merged into revision "
  709. ."$d but does not have git-svn metadata. "
  710. ."This means git-svn cannot determine the "
  711. ."svn revision numbers to place into the "
  712. ."svn:mergeinfo property. You must ensure "
  713. ."a branch is entirely committed to "
  714. ."SVN before merging it in order for "
  715. ."svn:mergeinfo population to function "
  716. ."properly";
  717. }
  718. push @revsin, $csvnrev;
  719. }
  720. command_close_pipe($revlist, $ctx);
  721. last unless $all_parents_ok;
  722. # We now have a list of all SVN revnos which are
  723. # merged by this particular parent. Integrate them.
  724. next if $#revsin == -1;
  725. my $newmergeinfo = "$branchpath:" . join(',', @revsin);
  726. $aggregate_mergeinfo =
  727. merge_merge_info($aggregate_mergeinfo,
  728. $newmergeinfo,
  729. $target_branch);
  730. }
  731. if ($all_parents_ok and $aggregate_mergeinfo) {
  732. return $aggregate_mergeinfo;
  733. }
  734. }
  735. return undef;
  736. }
  737. sub dcommit_rebase {
  738. my ($is_last, $current, $fetched_ref, $svn_error) = @_;
  739. my @diff;
  740. if ($svn_error) {
  741. print STDERR "\nERROR from SVN:\n",
  742. $svn_error->expanded_message, "\n";
  743. }
  744. unless ($_no_rebase) {
  745. # we always want to rebase against the current HEAD,
  746. # not any head that was passed to us
  747. @diff = command('diff-tree', $current,
  748. $fetched_ref, '--');
  749. my @finish;
  750. if (@diff) {
  751. @finish = rebase_cmd();
  752. print STDERR "W: $current and ", $fetched_ref,
  753. " differ, using @finish:\n",
  754. join("\n", @diff), "\n";
  755. } elsif ($is_last) {
  756. print "No changes between ", $current, " and ",
  757. $fetched_ref,
  758. "\nResetting to the latest ",
  759. $fetched_ref, "\n";
  760. @finish = qw/reset --mixed/;
  761. }
  762. command_noisy(@finish, $fetched_ref) if @finish;
  763. }
  764. if ($svn_error) {
  765. die "ERROR: Not all changes have been committed into SVN"
  766. .($_no_rebase ? ".\n" : ", however the committed\n"
  767. ."ones (if any) seem to be successfully integrated "
  768. ."into the working tree.\n")
  769. ."Please see the above messages for details.\n";
  770. }
  771. return @diff;
  772. }
  773. sub cmd_dcommit {
  774. my $head = shift;
  775. command_noisy(qw/update-index --refresh/);
  776. git_cmd_try { command_oneline(qw/diff-index --quiet HEAD --/) }
  777. 'Cannot dcommit with a dirty index. Commit your changes first, '
  778. . "or stash them with `git stash'.\n";
  779. $head ||= 'HEAD';
  780. my $old_head;
  781. if ($head ne 'HEAD') {
  782. $old_head = eval {
  783. command_oneline([qw/symbolic-ref -q HEAD/])
  784. };
  785. if ($old_head) {
  786. $old_head =~ s{^refs/heads/}{};
  787. } else {
  788. $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
  789. }
  790. command(['checkout', $head], STDERR => 0);
  791. }
  792. my @refs;
  793. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
  794. unless ($gs) {
  795. die "Unable to determine upstream SVN information from ",
  796. "$head history.\nPerhaps the repository is empty.";
  797. }
  798. if (defined $_commit_url) {
  799. $url = $_commit_url;
  800. } else {
  801. $url = eval { command_oneline('config', '--get',
  802. "svn-remote.$gs->{repo_id}.commiturl") };
  803. if (!$url) {
  804. $url = $gs->full_pushurl
  805. }
  806. }
  807. my $last_rev = $_revision if defined $_revision;
  808. if ($url) {
  809. print "Committing to $url ...\n";
  810. }
  811. my ($linear_refs, $parents) = linearize_history($gs, \@refs);
  812. if ($_no_rebase && scalar(@$linear_refs) > 1) {
  813. warn "Attempting to commit more than one change while ",
  814. "--no-rebase is enabled.\n",
  815. "If these changes depend on each other, re-running ",
  816. "without --no-rebase may be required."
  817. }
  818. if (defined $_interactive){
  819. my $ask_default = "y";
  820. foreach my $d (@$linear_refs){
  821. my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
  822. while (<$fh>){
  823. print $_;
  824. }
  825. command_close_pipe($fh, $ctx);
  826. $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
  827. valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
  828. default => $ask_default);
  829. die "Commit this patch reply required" unless defined $_;
  830. if (/^[nq]/i) {
  831. exit(0);
  832. } elsif (/^a/i) {
  833. last;
  834. }
  835. }
  836. }
  837. my $expect_url = $url;
  838. my $push_merge_info = eval {
  839. command_oneline(qw/config --get svn.pushmergeinfo/)
  840. };
  841. if (not defined($push_merge_info)
  842. or $push_merge_info eq "false"
  843. or $push_merge_info eq "no"
  844. or $push_merge_info eq "never") {
  845. $push_merge_info = 0;
  846. }
  847. unless (defined($_merge_info) || ! $push_merge_info) {
  848. # Preflight check of changes to ensure no issues with mergeinfo
  849. # This includes check for uncommitted-to-SVN parents
  850. # (other than the first parent, which we will handle),
  851. # information from different SVN repos, and paths
  852. # which are not underneath this repository root.
  853. my $rooturl = $gs->repos_root;
  854. Git::SVN::remove_username($rooturl);
  855. foreach my $d (@$linear_refs) {
  856. my %parentshash;
  857. read_commit_parents(\%parentshash, $d);
  858. my @realparents = @{$parentshash{$d}};
  859. if ($#realparents > 0) {
  860. # Merge commit
  861. shift @realparents; # Remove/ignore first parent
  862. foreach my $parent (@realparents) {
  863. my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
  864. unless (defined $paruuid) {
  865. # A parent is missing SVN annotations...
  866. # abort the whole operation.
  867. fatal "$parent is merged into revision $d, "
  868. ."but does not have git-svn metadata. "
  869. ."Either dcommit the branch or use a "
  870. ."local cherry-pick, FF merge, or rebase "
  871. ."instead of an explicit merge commit.";
  872. }
  873. unless ($paruuid eq $uuid) {
  874. # Parent has SVN metadata from different repository
  875. fatal "merge parent $parent for change $d has "
  876. ."git-svn uuid $paruuid, while current change "
  877. ."has uuid $uuid!";
  878. }
  879. unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
  880. # This branch is very strange indeed.
  881. fatal "merge parent $parent for $d is on branch "
  882. ."$branchurl, which is not under the "
  883. ."git-svn root $rooturl!";
  884. }
  885. }
  886. }
  887. }
  888. }
  889. my $rewritten_parent;
  890. my $current_head = command_oneline(qw/rev-parse HEAD/);
  891. Git::SVN::remove_username($expect_url);
  892. if (defined($_merge_info)) {
  893. $_merge_info =~ tr{ }{\n};
  894. }
  895. while (1) {
  896. my $d = shift @$linear_refs or last;
  897. unless (defined $last_rev) {
  898. (undef, $last_rev, undef) = cmt_metadata("$d~1");
  899. unless (defined $last_rev) {
  900. fatal "Unable to extract revision information ",
  901. "from commit $d~1";
  902. }
  903. }
  904. if ($_dry_run) {
  905. print "diff-tree $d~1 $d\n";
  906. } else {
  907. my $cmt_rev;
  908. unless (defined($_merge_info) || ! $push_merge_info) {
  909. $_merge_info = populate_merge_info($d, $gs,
  910. $uuid,
  911. $linear_refs,
  912. $rewritten_parent);
  913. }
  914. my %ed_opts = ( r => $last_rev,
  915. log => get_commit_entry($d)->{log},
  916. ra => Git::SVN::Ra->new($url),
  917. config => SVN::Core::config_get_config(
  918. $Git::SVN::Ra::config_dir
  919. ),
  920. tree_a => "$d~1",
  921. tree_b => $d,
  922. editor_cb => sub {
  923. print "Committed r$_[0]\n";
  924. $cmt_rev = $_[0];
  925. },
  926. mergeinfo => $_merge_info,
  927. svn_path => '');
  928. my $err_handler = $SVN::Error::handler;
  929. $SVN::Error::handler = sub {
  930. my $err = shift;
  931. dcommit_rebase(1, $current_head, $gs->refname,
  932. $err);
  933. };
  934. if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
  935. print "No changes\n$d~1 == $d\n";
  936. } elsif ($parents->{$d} && @{$parents->{$d}}) {
  937. $gs->{inject_parents_dcommit}->{$cmt_rev} =
  938. $parents->{$d};
  939. }
  940. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  941. $SVN::Error::handler = $err_handler;
  942. $last_rev = $cmt_rev;
  943. next if $_no_rebase;
  944. my @diff = dcommit_rebase(@$linear_refs == 0, $d,
  945. $gs->refname, undef);
  946. $rewritten_parent = command_oneline(qw/rev-parse/,
  947. $gs->refname);
  948. if (@diff) {
  949. $current_head = command_oneline(qw/rev-parse
  950. HEAD/);
  951. @refs = ();
  952. my ($url_, $rev_, $uuid_, $gs_) =
  953. working_head_info('HEAD', \@refs);
  954. my ($linear_refs_, $parents_) =
  955. linearize_history($gs_, \@refs);
  956. if (scalar(@$linear_refs) !=
  957. scalar(@$linear_refs_)) {
  958. fatal "# of revisions changed ",
  959. "\nbefore:\n",
  960. join("\n", @$linear_refs),
  961. "\n\nafter:\n",
  962. join("\n", @$linear_refs_), "\n",
  963. 'If you are attempting to commit ',
  964. "merges, try running:\n\t",
  965. 'git rebase --interactive',
  966. '--preserve-merges ',
  967. $gs->refname,
  968. "\nBefore dcommitting";
  969. }
  970. if ($url_ ne $expect_url) {
  971. if ($url_ eq $gs->metadata_url) {
  972. print
  973. "Accepting rewritten URL:",
  974. " $url_\n";
  975. } else {
  976. fatal
  977. "URL mismatch after rebase:",
  978. " $url_ != $expect_url";
  979. }
  980. }
  981. if ($uuid_ ne $uuid) {
  982. fatal "uuid mismatch after rebase: ",
  983. "$uuid_ != $uuid";
  984. }
  985. # remap parents
  986. my (%p, @l, $i);
  987. for ($i = 0; $i < scalar @$linear_refs; $i++) {
  988. my $new = $linear_refs_->[$i] or next;
  989. $p{$new} =
  990. $parents->{$linear_refs->[$i]};
  991. push @l, $new;
  992. }
  993. $parents = \%p;
  994. $linear_refs = \@l;
  995. undef $last_rev;
  996. }
  997. }
  998. }
  999. if ($old_head) {
  1000. my $new_head = command_oneline(qw/rev-parse HEAD/);
  1001. my $new_is_symbolic = eval {
  1002. command_oneline(qw/symbolic-ref -q HEAD/);
  1003. };
  1004. if ($new_is_symbolic) {
  1005. print "dcommitted the branch ", $head, "\n";
  1006. } else {
  1007. print "dcommitted on a detached HEAD because you gave ",
  1008. "a revision argument.\n",
  1009. "The rewritten commit is: ", $new_head, "\n";
  1010. }
  1011. command(['checkout', $old_head], STDERR => 0);
  1012. }
  1013. unlink $gs->{index};
  1014. }
  1015. sub cmd_branch {
  1016. my ($branch_name, $head) = @_;
  1017. unless (defined $branch_name && length $branch_name) {
  1018. die(($_tag ? "tag" : "branch") . " name required\n");
  1019. }
  1020. $head ||= 'HEAD';
  1021. my (undef, $rev, undef, $gs) = working_head_info($head);
  1022. my $src = $gs->full_pushurl;
  1023. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1024. my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
  1025. my $glob;
  1026. if ($#{$allglobs} == 0) {
  1027. $glob = $allglobs->[0];
  1028. } else {
  1029. unless(defined $_branch_dest) {
  1030. die "Multiple ",
  1031. $_tag ? "tag" : "branch",
  1032. " paths defined for Subversion repository.\n",
  1033. "You must specify where you want to create the ",
  1034. $_tag ? "tag" : "branch",
  1035. " with the --destination argument.\n";
  1036. }
  1037. foreach my $g (@{$allglobs}) {
  1038. my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
  1039. if ($_branch_dest =~ /$re/) {
  1040. $glob = $g;
  1041. last;
  1042. }
  1043. }
  1044. unless (defined $glob) {
  1045. my $dest_re = qr/\b\Q$_branch_dest\E\b/;
  1046. foreach my $g (@{$allglobs}) {
  1047. $g->{path}->{left} =~ /$dest_re/ or next;
  1048. if (defined $glob) {
  1049. die "Ambiguous destination: ",
  1050. $_branch_dest, "\nmatches both '",
  1051. $glob->{path}->{left}, "' and '",
  1052. $g->{path}->{left}, "'\n";
  1053. }
  1054. $glob = $g;
  1055. }
  1056. unless (defined $glob) {
  1057. die "Unknown ",
  1058. $_tag ? "tag" : "branch",
  1059. " destination $_branch_dest\n";
  1060. }
  1061. }
  1062. }
  1063. my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
  1064. my $url;
  1065. if (defined $_commit_url) {
  1066. $url = $_commit_url;
  1067. } else {
  1068. $url = eval { command_oneline('config', '--get',
  1069. "svn-remote.$gs->{repo_id}.commiturl") };
  1070. if (!$url) {
  1071. $url = $remote->{pushurl} || $remote->{url};
  1072. }
  1073. }
  1074. my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
  1075. if ($dst =~ /^https:/ && $src =~ /^http:/) {
  1076. $src=~s/^http:/https:/;
  1077. }
  1078. ::_req_svn();
  1079. require SVN::Client;
  1080. my ($config, $baton, undef) = Git::SVN::Ra::prepare_config_once();
  1081. my $ctx = SVN::Client->new(
  1082. auth => $baton,
  1083. config => $config,
  1084. log_msg => sub {
  1085. ${ $_[0] } = defined $_message
  1086. ? $_message
  1087. : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
  1088. . $branch_name;
  1089. },
  1090. );
  1091. eval {
  1092. $ctx->ls($dst, 'HEAD', 0);
  1093. } and die "branch ${branch_name} already exists\n";
  1094. if ($_parents) {
  1095. mk_parent_dirs($ctx, $dst);
  1096. }
  1097. print "Copying ${src} at r${rev} to ${dst}...\n";
  1098. $ctx->copy($src, $rev, $dst)
  1099. unless $_dry_run;
  1100. # Release resources held by ctx before creating another SVN::Ra
  1101. # so destruction is orderly. This seems necessary with SVN 1.9.5
  1102. # to avoid segfaults.
  1103. $ctx = undef;
  1104. $gs->fetch_all;
  1105. }
  1106. sub mk_parent_dirs {
  1107. my ($ctx, $parent) = @_;
  1108. $parent =~ s{/[^/]*$}{};
  1109. if (!eval{$ctx->ls($parent, 'HEAD', 0)}) {
  1110. mk_parent_dirs($ctx, $parent);
  1111. print "Creating parent folder ${parent} ...\n";
  1112. $ctx->mkdir($parent) unless $_dry_run;
  1113. }
  1114. }
  1115. sub cmd_find_rev {
  1116. my $revision_or_hash = shift or die "SVN or git revision required ",
  1117. "as a command-line argument\n";
  1118. my $result;
  1119. if ($revision_or_hash =~ /^r\d+$/) {
  1120. my $head = shift;
  1121. $head ||= 'HEAD';
  1122. my @refs;
  1123. my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
  1124. unless ($gs) {
  1125. die "Unable to determine upstream SVN information from ",
  1126. "$head history\n";
  1127. }
  1128. my $desired_revision = substr($revision_or_hash, 1);
  1129. if ($_before) {
  1130. $result = $gs->find_rev_before($desired_revision, 1);
  1131. } elsif ($_after) {
  1132. $result = $gs->find_rev_after($desired_revision, 1);
  1133. } else {
  1134. $result = $gs->rev_map_get($desired_revision, $uuid);
  1135. }
  1136. } else {
  1137. my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
  1138. $result = $rev;
  1139. }
  1140. print "$result\n" if $result;
  1141. }
  1142. sub auto_create_empty_directories {
  1143. my ($gs) = @_;
  1144. my $var = eval { command_oneline('config', '--get', '--bool',
  1145. "svn-remote.$gs->{repo_id}.automkdirs") };
  1146. # By default, create empty directories by consulting the unhandled log,
  1147. # but allow setting it to 'false' to skip it.
  1148. return !($var && $var eq 'false');
  1149. }
  1150. sub cmd_rebase {
  1151. command_noisy(qw/update-index --refresh/);
  1152. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1153. unless ($gs) {
  1154. die "Unable to determine upstream SVN information from ",
  1155. "working tree history\n";
  1156. }
  1157. if ($_dry_run) {
  1158. print "Remote Branch: " . $gs->refname . "\n";
  1159. print "SVN URL: " . $url . "\n";
  1160. return;
  1161. }
  1162. if (command(qw/diff-index HEAD --/)) {
  1163. print STDERR "Cannot rebase with uncommitted changes:\n";
  1164. command_noisy('status');
  1165. exit 1;
  1166. }
  1167. unless ($_local) {
  1168. # rebase will checkout for us, so no need to do it explicitly
  1169. $_no_checkout = 'true';
  1170. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  1171. }
  1172. command_noisy(rebase_cmd(), $gs->refname);
  1173. if (auto_create_empty_directories($gs)) {
  1174. $gs->mkemptydirs;
  1175. }
  1176. }
  1177. sub cmd_show_ignore {
  1178. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1179. $gs ||= Git::SVN->new;
  1180. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1181. $gs->prop_walk($gs->path, $r, sub {
  1182. my ($gs, $path, $props) = @_;
  1183. print STDOUT "\n# $path\n";
  1184. my $s = $props->{'svn:ignore'} or return;
  1185. $s =~ s/[\r\n]+/\n/g;
  1186. $s =~ s/^\n+//;
  1187. chomp $s;
  1188. $s =~ s#^#$path#gm;
  1189. print STDOUT "$s\n";
  1190. });
  1191. }
  1192. sub cmd_show_externals {
  1193. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1194. $gs ||= Git::SVN->new;
  1195. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1196. $gs->prop_walk($gs->path, $r, sub {
  1197. my ($gs, $path, $props) = @_;
  1198. print STDOUT "\n# $path\n";
  1199. my $s = $props->{'svn:externals'} or return;
  1200. $s =~ s/[\r\n]+/\n/g;
  1201. chomp $s;
  1202. $s =~ s#^#$path#gm;
  1203. print STDOUT "$s\n";
  1204. });
  1205. }
  1206. sub cmd_create_ignore {
  1207. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1208. $gs ||= Git::SVN->new;
  1209. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1210. $gs->prop_walk($gs->path, $r, sub {
  1211. my ($gs, $path, $props) = @_;
  1212. # $path is of the form /path/to/dir/
  1213. $path = '.' . $path;
  1214. # SVN can have attributes on empty directories,
  1215. # which git won't track
  1216. mkpath([$path]) unless -d $path;
  1217. my $ignore = $path . '.gitignore';
  1218. my $s = $props->{'svn:ignore'} or return;
  1219. open(GITIGNORE, '>', $ignore)
  1220. or fatal("Failed to open `$ignore' for writing: $!");
  1221. $s =~ s/[\r\n]+/\n/g;
  1222. $s =~ s/^\n+//;
  1223. chomp $s;
  1224. # Prefix all patterns so that the ignore doesn't apply
  1225. # to sub-directories.
  1226. $s =~ s#^#/#gm;
  1227. print GITIGNORE "$s\n";
  1228. close(GITIGNORE)
  1229. or fatal("Failed to close `$ignore': $!");
  1230. command_noisy('add', '-f', $ignore);
  1231. });
  1232. }
  1233. sub cmd_mkdirs {
  1234. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1235. $gs ||= Git::SVN->new;
  1236. $gs->mkemptydirs($_revision);
  1237. }
  1238. # get_svnprops(PATH)
  1239. # ------------------
  1240. # Helper for cmd_propget and cmd_proplist below.
  1241. sub get_svnprops {
  1242. my $path = shift;
  1243. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1244. $gs ||= Git::SVN->new;
  1245. # prefix THE PATH by the sub-directory from which the user
  1246. # invoked us.
  1247. $path = $cmd_dir_prefix . $path;
  1248. fatal("No such file or directory: $path") unless -e $path;
  1249. my $is_dir = -d $path ? 1 : 0;
  1250. $path = join_paths($gs->path, $path);
  1251. # canonicalize the path (otherwise libsvn will abort or fail to
  1252. # find the file)
  1253. $path = canonicalize_path($path);
  1254. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1255. my $props;
  1256. if ($is_dir) {
  1257. (undef, undef, $props) = $gs->ra->get_dir($path, $r);
  1258. }
  1259. else {
  1260. (undef, $props) = $gs->ra->get_file($path, $r, undef);
  1261. }
  1262. return $props;
  1263. }
  1264. # cmd_propget (PROP, PATH)
  1265. # ------------------------
  1266. # Print the SVN property PROP for PATH.
  1267. sub cmd_propget {
  1268. my ($prop, $path) = @_;
  1269. $path = '.' if not defined $path;
  1270. usage(1) if not defined $prop;
  1271. my $props = get_svnprops($path);
  1272. if (not defined $props->{$prop}) {
  1273. fatal("`$path' does not have a `$prop' SVN property.");
  1274. }
  1275. print $props->{$prop} . "\n";
  1276. }
  1277. # cmd_propset (PROPNAME, PROPVAL, PATH)
  1278. # ------------------------
  1279. # Adjust the SVN property PROPNAME to PROPVAL for PATH.
  1280. sub cmd_propset {
  1281. my ($propname, $propval, $path) = @_;
  1282. $path = '.' if not defined $path;
  1283. $path = $cmd_dir_prefix . $path;
  1284. usage(1) if not defined $propname;
  1285. usage(1) if not defined $propval;
  1286. my $file = basename($path);
  1287. my $dn = dirname($path);
  1288. my $cur_props = Git::SVN::Editor::check_attr( "svn-properties", $path );
  1289. my @new_props;
  1290. if (!$cur_props || $cur_props eq "unset" || $cur_props eq "" || $cur_props eq "set") {
  1291. push @new_props, "$propname=$propval";
  1292. } else {
  1293. # TODO: handle combining properties better
  1294. my @props = split(/;/, $cur_props);
  1295. my $replaced_prop;
  1296. foreach my $prop (@props) {
  1297. # Parse 'name=value' syntax and set the property.
  1298. if ($prop =~ /([^=]+)=(.*)/) {
  1299. my ($n,$v) = ($1,$2);
  1300. if ($n eq $propname) {
  1301. $v = $propval;
  1302. $replaced_prop = 1;
  1303. }
  1304. push @new_props, "$n=$v";
  1305. }
  1306. }
  1307. if (!$replaced_prop) {
  1308. push @new_props, "$propname=$propval";
  1309. }
  1310. }
  1311. my $attrfile = "$dn/.gitattributes";
  1312. open my $attrfh, '>>', $attrfile or die "Can't open $attrfile: $!\n";
  1313. # TODO: don't simply append here if $file already has svn-properties
  1314. my $new_props = join(';', @new_props);
  1315. print $attrfh "$file svn-properties=$new_props\n" or
  1316. die "write to $attrfile: $!\n";
  1317. close $attrfh or die "close $attrfile: $!\n";
  1318. }
  1319. # cmd_proplist (PATH)
  1320. # -------------------
  1321. # Print the list of SVN properties for PATH.
  1322. sub cmd_proplist {
  1323. my $path = shift;
  1324. $path = '.' if not defined $path;
  1325. my $props = get_svnprops($path);
  1326. print "Properties on '$path':\n";
  1327. foreach (sort keys %{$props}) {
  1328. print " $_\n";
  1329. }
  1330. }
  1331. sub cmd_multi_init {
  1332. my $url = shift;
  1333. unless (defined $_trunk || @_branches || @_tags) {
  1334. usage(1);
  1335. }
  1336. $_prefix = 'origin/' unless defined $_prefix;
  1337. if (defined $url) {
  1338. $url = canonicalize_url($url);
  1339. init_subdir(@_);
  1340. }
  1341. do_git_init_db();
  1342. if (defined $_trunk) {
  1343. $_trunk =~ s#^/+##;
  1344. my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
  1345. # try both old-style and new-style lookups:
  1346. my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
  1347. unless ($gs_trunk) {
  1348. my ($trunk_url, $trunk_path) =
  1349. complete_svn_url($url, $_trunk);
  1350. $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
  1351. undef, $trunk_ref);
  1352. }
  1353. }
  1354. return unless @_branches || @_tags;
  1355. my $ra = $url ? Git::SVN::Ra->new($url) : undef;
  1356. foreach my $path (@_branches) {
  1357. complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
  1358. }
  1359. foreach my $path (@_tags) {
  1360. complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
  1361. }
  1362. }
  1363. sub cmd_multi_fetch {
  1364. $Git::SVN::no_reuse_existing = undef;
  1365. my $remotes = Git::SVN::read_all_remotes();
  1366. foreach my $repo_id (sort keys %$remotes) {
  1367. if ($remotes->{$repo_id}->{url}) {
  1368. Git::SVN::fetch_all($repo_id, $remotes);
  1369. }
  1370. }
  1371. }
  1372. # this command is special because it requires no metadata
  1373. sub cmd_commit_diff {
  1374. my ($ta, $tb, $url) = @_;
  1375. my $usage = "usage: $0 commit-diff -r<revision> ".
  1376. "<tree-ish> <tree-ish> [<URL>]";
  1377. fatal($usage) if (!defined $ta || !defined $tb);
  1378. my $svn_path = '';
  1379. if (!defined $url) {
  1380. my $gs = eval { Git::SVN->new };
  1381. if (!$gs) {
  1382. fatal("Needed URL or usable git-svn --id in ",
  1383. "the command-line\n", $usage);
  1384. }
  1385. $url = $gs->url;
  1386. $svn_path = $gs->path;
  1387. }
  1388. unless (defined $_revision) {
  1389. fatal("-r|--revision is a required argument\n", $usage);
  1390. }
  1391. if (defined $_message && defined $_file) {
  1392. fatal("Both --message/-m and --file/-F specified ",
  1393. "for the commit message.\n",
  1394. "I have no idea what you mean");
  1395. }
  1396. if (defined $_file) {
  1397. $_message = file_to_s($_file);
  1398. } else {
  1399. $_message ||= get_commit_entry($tb)->{log};
  1400. }
  1401. my $ra ||= Git::SVN::Ra->new($url);
  1402. my $r = $_revision;
  1403. if ($r eq 'HEAD') {
  1404. $r = $ra->get_latest_revnum;
  1405. } elsif ($r !~ /^\d+$/) {
  1406. die "revision argument: $r not understood by git-svn\n";
  1407. }
  1408. my %ed_opts = ( r => $r,
  1409. log => $_message,
  1410. ra => $ra,
  1411. tree_a => $ta,
  1412. tree_b => $tb,
  1413. editor_cb => sub { print "Committed r$_[0]\n" },
  1414. svn_path => $svn_path );
  1415. if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
  1416. print "No changes\n$ta == $tb\n";
  1417. }
  1418. }
  1419. sub cmd_info {
  1420. my $path_arg = defined($_[0]) ? $_[0] : '.';
  1421. my $path = $path_arg;
  1422. if (File::Spec->file_name_is_absolute($path)) {
  1423. $path = canonicalize_path($path);
  1424. my $toplevel = eval {
  1425. my @cmd = qw/rev-parse --show-toplevel/;
  1426. command_oneline(\@cmd, STDERR => 0);
  1427. };
  1428. # remove $toplevel from the absolute path:
  1429. my ($vol, $dirs, $file) = File::Spec->splitpath($path);
  1430. my (undef, $tdirs, $tfile) = File::Spec->splitpath($toplevel);
  1431. my @dirs = File::Spec->splitdir($dirs);
  1432. my @tdirs = File::Spec->splitdir($tdirs);
  1433. pop @dirs if $dirs[-1] eq '';
  1434. pop @tdirs if $tdirs[-1] eq '';
  1435. push @dirs, $file;
  1436. push @tdirs, $tfile;
  1437. while (@tdirs && @dirs && $tdirs[0] eq $dirs[0]) {
  1438. shift @dirs;
  1439. shift @tdirs;
  1440. }
  1441. $dirs = File::Spec->catdir(@dirs);
  1442. $path = File::Spec->catpath($vol, $dirs);
  1443. $path = canonicalize_path($path);
  1444. } else {
  1445. $path = canonicalize_path($cmd_dir_prefix . $path);
  1446. }
  1447. if (exists $_[1]) {
  1448. die "Too many arguments specified\n";
  1449. }
  1450. my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
  1451. if (!$file_type && !$diff_status) {
  1452. print STDERR "svn: '$path' is not under version control\n";
  1453. exit 1;
  1454. }
  1455. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1456. unless ($gs) {
  1457. die "Unable to determine upstream SVN information from ",
  1458. "working tree history\n";
  1459. }
  1460. # canonicalize_path() will return "" to make libsvn 1.5.x happy,
  1461. $path = "." if $path eq "";
  1462. my $full_url = canonicalize_url( add_path_to_url( $url, $path ) );
  1463. if ($_url) {
  1464. print "$full_url\n";
  1465. return;
  1466. }
  1467. my $result = "Path: $path_arg\n";
  1468. $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
  1469. $result .= "URL: $full_url\n";
  1470. eval {
  1471. my $repos_root = $gs->repos_root;
  1472. Git::SVN::remove_username($repos_root);
  1473. $result .= "Repository Root: " . canonicalize_url($repos_root) . "\n";
  1474. };
  1475. if ($@) {
  1476. $result .= "Repository Root: (offline)\n";
  1477. }
  1478. ::_req_svn();
  1479. $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
  1480. (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
  1481. $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
  1482. $result .= "Node Kind: " .
  1483. ($file_type eq "dir" ? "directory" : "file") . "\n";
  1484. my $schedule = $diff_status eq "A"
  1485. ? "add"
  1486. : ($diff_status eq "D" ? "delete" : "normal");
  1487. $result .= "Schedule: $schedule\n";
  1488. if ($diff_status eq "A") {
  1489. print $result, "\n";
  1490. return;
  1491. }
  1492. my ($lc_author, $lc_rev, $lc_date_utc);
  1493. my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
  1494. my $log = command_output_pipe(@args);
  1495. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  1496. while (<$log>) {
  1497. if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
  1498. $lc_author = $1;
  1499. $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
  1500. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  1501. (undef, $lc_rev, undef) = ::extract_metadata($1);
  1502. }
  1503. }
  1504. close $log;
  1505. Git::SVN::Log::set_local_timezone();
  1506. $result .= "Last Changed Author: $lc_author\n";
  1507. $result .= "Last Changed Rev: $lc_rev\n";
  1508. $result .= "Last Changed Date: " .
  1509. Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
  1510. if ($file_type ne "dir") {
  1511. my $text_last_updated_date =
  1512. ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
  1513. $result .=
  1514. "Text Last Updated: " .
  1515. Git::SVN::Log::format_svn_date($text_last_updated_date) .
  1516. "\n";
  1517. my $checksum;
  1518. if ($diff_status eq "D") {
  1519. my ($fh, $ctx) =
  1520. command_output_pipe(qw(cat-file blob), "HEAD:$path");
  1521. if ($file_type eq "link") {
  1522. my $file_name = <$fh>;
  1523. $checksum = md5sum("link $file_name");
  1524. } else {
  1525. $checksum = md5sum($fh);
  1526. }
  1527. command_close_pipe($fh, $ctx);
  1528. } elsif ($file_type eq "link") {
  1529. my $file_name =
  1530. command(qw(cat-file blob), "HEAD:$path");
  1531. $checksum =
  1532. md5sum("link " . $file_name);
  1533. } else {
  1534. open FILE, "<", $path or die $!;
  1535. $checksum = md5sum(\*FILE);
  1536. close FILE or die $!;
  1537. }
  1538. $result .= "Checksum: " . $checksum . "\n";
  1539. }
  1540. print $result, "\n";
  1541. }
  1542. sub cmd_reset {
  1543. my $target = shift || $_revision or die "SVN revision required\n";
  1544. $target = $1 if $target =~ /^r(\d+)$/;
  1545. $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
  1546. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1547. unless ($gs) {
  1548. die "Unable to determine upstream SVN information from ".
  1549. "history\n";
  1550. }
  1551. my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
  1552. die "Cannot find SVN revision $target\n" unless defined($c);
  1553. $gs->rev_map_set($r, $c, 'reset', $uuid);
  1554. print "r$r = $c ($gs->{ref_id})\n";
  1555. }
  1556. sub cmd_gc {
  1557. require File::Find;
  1558. if (!can_compress()) {
  1559. warn "Compress::Zlib could not be found; unhandled.log " .
  1560. "files will not be compressed.\n";
  1561. }
  1562. File::Find::find({ wanted => \&gc_directory, no_chdir => 1},
  1563. Git::SVN::svn_dir());
  1564. }
  1565. ########################### utility functions #########################
  1566. sub rebase_cmd {
  1567. my @cmd = qw/rebase/;
  1568. push @cmd, '-v' if $_verbose;
  1569. push @cmd, qw/--merge/ if $_merge;
  1570. push @cmd, "--strategy=$_strategy" if $_strategy;
  1571. push @cmd, "--preserve-merges" if $_preserve_merges;
  1572. @cmd;
  1573. }
  1574. sub post_fetch_checkout {
  1575. return if $_no_checkout;
  1576. return if verify_ref('HEAD^0');
  1577. my $gs = $Git::SVN::_head or return;
  1578. # look for "trunk" ref if it exists
  1579. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1580. my $fetch = $remote->{fetch};
  1581. if ($fetch) {
  1582. foreach my $p (keys %$fetch) {
  1583. basename($fetch->{$p}) eq 'trunk' or next;
  1584. $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
  1585. last;
  1586. }
  1587. }
  1588. command_noisy(qw(update-ref HEAD), $gs->refname);
  1589. return unless verify_ref('HEAD^0');
  1590. return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
  1591. my $index = command_oneline(qw(rev-parse --git-path index));
  1592. return if -f $index;
  1593. return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
  1594. return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
  1595. command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
  1596. print STDERR "Checked out HEAD:\n ",
  1597. $gs->full_url, " r", $gs->last_rev, "\n";
  1598. if (auto_create_empty_directories($gs)) {
  1599. $gs->mkemptydirs($gs->last_rev);
  1600. }
  1601. }
  1602. sub complete_svn_url {
  1603. my ($url, $path) = @_;
  1604. if ($path =~ m#^[a-z\+]+://#i) { # path is a URL
  1605. $path = canonicalize_url($path);
  1606. } else {
  1607. $path = canonicalize_path($path);
  1608. if (!defined $url || $url !~ m#^[a-z\+]+://#i) {
  1609. fatal("E: '$path' is not a complete URL ",
  1610. "and a separate URL is not specified");
  1611. }
  1612. return ($url, $path);
  1613. }
  1614. return ($path, '');
  1615. }
  1616. sub complete_url_ls_init {
  1617. my ($ra, $repo_path, $switch, $pfx) = @_;
  1618. unless ($repo_path) {
  1619. print STDERR "W: $switch not specified\n";
  1620. return;
  1621. }
  1622. if ($repo_path =~ m#^[a-z\+]+://#i) {
  1623. $repo_path = canonicalize_url($repo_path);
  1624. $ra = Git::SVN::Ra->new($repo_path);
  1625. $repo_path = '';
  1626. } else {
  1627. $repo_path = canonicalize_path($repo_path);
  1628. $repo_path =~ s#^/+##;
  1629. unless ($ra) {
  1630. fatal("E: '$repo_path' is not a complete URL ",
  1631. "and a separate URL is not specified");
  1632. }
  1633. }
  1634. my $url = $ra->url;
  1635. my $gs = Git::SVN->init($url, undef, undef, undef, 1);
  1636. my $k = "svn-remote.$gs->{repo_id}.url";
  1637. my $orig_url = eval { command_oneline(qw/config --get/, $k) };
  1638. if ($orig_url && ($orig_url ne $gs->url)) {
  1639. die "$k already set: $orig_url\n",
  1640. "wanted to set to: $gs->url\n";
  1641. }
  1642. command_oneline('config', $k, $gs->url) unless $orig_url;
  1643. my $remote_path = join_paths( $gs->path, $repo_path );
  1644. $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1645. $remote_path =~ s#^/##g;
  1646. $remote_path .= "/*" if $remote_path !~ /\*/;
  1647. my ($n) = ($switch =~ /^--(\w+)/);
  1648. if (length $pfx && $pfx !~ m#/$#) {
  1649. die "--prefix='$pfx' must have a trailing slash '/'\n";
  1650. }
  1651. command_noisy('config',
  1652. '--add',
  1653. "svn-remote.$gs->{repo_id}.$n",
  1654. "$remote_path:refs/remotes/$pfx*" .
  1655. ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
  1656. }
  1657. sub verify_ref {
  1658. my ($ref) = @_;
  1659. eval { command_oneline([ 'rev-parse', '--verify', $ref ],
  1660. { STDERR => 0 }); };
  1661. }
  1662. sub get_tree_from_treeish {
  1663. my ($treeish) = @_;
  1664. # $treeish can be a symbolic ref, too:
  1665. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1666. my $expected;
  1667. while ($type eq 'tag') {
  1668. ($treeish, $type) = command(qw/cat-file tag/, $treeish);
  1669. }
  1670. if ($type eq 'commit') {
  1671. $expected = (grep /^tree /, command(qw/cat-file commit/,
  1672. $treeish))[0];
  1673. ($expected) = ($expected =~ /^tree ($sha1)$/o);
  1674. die "Unable to get tree from $treeish\n" unless $expected;
  1675. } elsif ($type eq 'tree') {
  1676. $expected = $treeish;
  1677. } else {
  1678. die "$treeish is a $type, expected tree, tag or commit\n";
  1679. }
  1680. return $expected;
  1681. }
  1682. sub get_commit_entry {
  1683. my ($treeish) = shift;
  1684. my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
  1685. my @git_path = qw(rev-parse --git-path);
  1686. my $commit_editmsg = command_oneline(@git_path, 'COMMIT_EDITMSG');
  1687. my $commit_msg = command_oneline(@git_path, 'COMMIT_MSG');
  1688. open my $log_fh, '>', $commit_editmsg or croak $!;
  1689. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1690. if ($type eq 'commit' || $type eq 'tag') {
  1691. my ($msg_fh, $ctx) = command_output_pipe('cat-file',
  1692. $type, $treeish);
  1693. my $in_msg = 0;
  1694. my $author;
  1695. my $saw_from = 0;
  1696. my $msgbuf = "";
  1697. while (<$msg_fh>) {
  1698. if (!$in_msg) {
  1699. $in_msg = 1 if (/^$/);
  1700. $author = $1 if (/^author (.*>)/);
  1701. } elsif (/^git-svn-id: /) {
  1702. # skip this for now, we regenerate the
  1703. # correct one on re-fetch anyways
  1704. # TODO: set *:merge properties or like...
  1705. } else {
  1706. if (/^From:/ || /^Signed-off-by:/) {
  1707. $saw_from = 1;
  1708. }
  1709. $msgbuf .= $_;
  1710. }
  1711. }
  1712. $msgbuf =~ s/\s+$//s;
  1713. $msgbuf =~ s/\r\n/\n/sg; # SVN 1.6+ disallows CRLF
  1714. if ($Git::SVN::_add_author_from && defined($author)
  1715. && !$saw_from) {
  1716. $msgbuf .= "\n\nFrom: $author";
  1717. }
  1718. print $log_fh $msgbuf or croak $!;
  1719. command_close_pipe($msg_fh, $ctx);
  1720. }
  1721. close $log_fh or croak $!;
  1722. if ($_edit || ($type eq 'tree')) {
  1723. chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
  1724. system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
  1725. }
  1726. rename $commit_editmsg, $commit_msg or croak $!;
  1727. {
  1728. require Encode;
  1729. # SVN requires messages to be UTF-8 when entering the repo
  1730. open $log_fh, '<', $commit_msg or croak $!;
  1731. binmode $log_fh;
  1732. chomp($log_entry{log} = get_record($log_fh, undef));
  1733. my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
  1734. my $msg = $log_entry{log};
  1735. eval { $msg = Encode::decode($enc, $msg, 1) };
  1736. if ($@) {
  1737. die "Could not decode as $enc:\n", $msg,
  1738. "\nPerhaps you need to set i18n.commitencoding\n";
  1739. }
  1740. eval { $msg = Encode::encode('UTF-8', $msg, 1) };
  1741. die "Could not encode as UTF-8:\n$msg\n" if $@;
  1742. $log_entry{log} = $msg;
  1743. close $log_fh or croak $!;
  1744. }
  1745. unlink $commit_msg;
  1746. \%log_entry;
  1747. }
  1748. sub s_to_file {
  1749. my ($str, $file, $mode) = @_;
  1750. open my $fd,'>',$file or croak $!;
  1751. print $fd $str,"\n" or croak $!;
  1752. close $fd or croak $!;
  1753. chmod ($mode &~ umask, $file) if (defined $mode);
  1754. }
  1755. sub file_to_s {
  1756. my $file = shift;
  1757. open my $fd,'<',$file or croak "$!: file: $file\n";
  1758. local $/;
  1759. my $ret = <$fd>;
  1760. close $fd or croak $!;
  1761. $ret =~ s/\s*$//s;
  1762. return $ret;
  1763. }
  1764. # '<svn username> = real-name <email address>' mapping based on git-svnimport:
  1765. sub load_authors {
  1766. open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
  1767. my $log = $cmd eq 'log';
  1768. while (<$authors>) {
  1769. chomp;
  1770. next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.*)>\s*$/;
  1771. my ($user, $name, $email) = ($1, $2, $3);
  1772. if ($log) {
  1773. $Git::SVN::Log::rusers{"$name <$email>"} = $user;
  1774. } else {
  1775. $users{$user} = [$name, $email];
  1776. }
  1777. }
  1778. close $authors or croak $!;
  1779. }
  1780. # convert GetOpt::Long specs for use by git-config
  1781. sub read_git_config {
  1782. my $opts = shift;
  1783. my @config_only;
  1784. foreach my $o (keys %$opts) {
  1785. # if we have mixedCase and a long option-only, then
  1786. # it's a config-only variable that we don't need for
  1787. # the command-line.
  1788. push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
  1789. my $v = $opts->{$o};
  1790. my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
  1791. $key =~ s/-//g;
  1792. my $arg = 'git config';
  1793. $arg .= ' --int' if ($o =~ /[:=]i$/);
  1794. $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
  1795. if (ref $v eq 'ARRAY') {
  1796. chomp(my @tmp = `$arg --get-all svn.$key`);
  1797. @$v = @tmp if @tmp;
  1798. } else {
  1799. chomp(my $tmp = `$arg --get svn.$key`);
  1800. if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
  1801. $$v = $tmp;
  1802. }
  1803. }
  1804. }
  1805. delete @$opts{@config_only} if @config_only;
  1806. }
  1807. sub extract_metadata {
  1808. my $id = shift or return (undef, undef, undef);
  1809. my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
  1810. \s([a-f\d\-]+)$/ix);
  1811. if (!defined $rev || !$uuid || !$url) {
  1812. # some of the original repositories I made had
  1813. # identifiers like this:
  1814. ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
  1815. }
  1816. return ($url, $rev, $uuid);
  1817. }
  1818. sub cmt_metadata {
  1819. return extract_metadata((grep(/^git-svn-id: /,
  1820. command(qw/cat-file commit/, shift)))[-1]);
  1821. }
  1822. sub cmt_sha2rev_batch {
  1823. my %s2r;
  1824. my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
  1825. my $list = shift;
  1826. foreach my $sha (@{$list}) {
  1827. my $first = 1;
  1828. my $size = 0;
  1829. print $out $sha, "\n";
  1830. while (my $line = <$in>) {
  1831. if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
  1832. last;
  1833. } elsif ($first &&
  1834. $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
  1835. $first = 0;
  1836. $size = $1;
  1837. next;
  1838. } elsif ($line =~ /^(git-svn-id: )/) {
  1839. my (undef, $rev, undef) =
  1840. extract_metadata($line);
  1841. $s2r{$sha} = $rev;
  1842. }
  1843. $size -= length($line);
  1844. last if ($size == 0);
  1845. }
  1846. }
  1847. command_close_bidi_pipe($pid, $in, $out, $ctx);
  1848. return \%s2r;
  1849. }
  1850. sub working_head_info {
  1851. my ($head, $refs) = @_;
  1852. my @args = qw/rev-list --first-parent --pretty=medium/;
  1853. my ($fh, $ctx) = command_output_pipe(@args, $head, "--");
  1854. my $hash;
  1855. my %max;
  1856. while (<$fh>) {
  1857. if ( m{^commit ($::sha1)$} ) {
  1858. unshift @$refs, $hash if $hash and $refs;
  1859. $hash = $1;
  1860. next;
  1861. }
  1862. next unless s{^\s*(git-svn-id:)}{$1};
  1863. my ($url, $rev, $uuid) = extract_metadata($_);
  1864. if (defined $url && defined $rev) {
  1865. next if $max{$url} and $max{$url} < $rev;
  1866. if (my $gs = Git::SVN->find_by_url($url)) {
  1867. my $c = $gs->rev_map_get($rev, $uuid);
  1868. if ($c && $c eq $hash) {
  1869. close $fh; # break the pipe
  1870. return ($url, $rev, $uuid, $gs);
  1871. } else {
  1872. $max{$url} ||= $gs->rev_map_max;
  1873. }
  1874. }
  1875. }
  1876. }
  1877. command_close_pipe($fh, $ctx);
  1878. (undef, undef, undef, undef);
  1879. }
  1880. sub read_commit_parents {
  1881. my ($parents, $c) = @_;
  1882. chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
  1883. $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
  1884. @{$parents->{$c}} = split(/ /, $p);
  1885. }
  1886. sub linearize_history {
  1887. my ($gs, $refs) = @_;
  1888. my %parents;
  1889. foreach my $c (@$refs) {
  1890. read_commit_parents(\%parents, $c);
  1891. }
  1892. my @linear_refs;
  1893. my %skip = ();
  1894. my $last_svn_commit = $gs->last_commit;
  1895. foreach my $c (reverse @$refs) {
  1896. next if $c eq $last_svn_commit;
  1897. last if $skip{$c};
  1898. unshift @linear_refs, $c;
  1899. $skip{$c} = 1;
  1900. # we only want the first parent to diff against for linear
  1901. # history, we save the rest to inject when we finalize the
  1902. # svn commit
  1903. my $fp_a = verify_ref("$c~1");
  1904. my $fp_b = shift @{$parents{$c}} if $parents{$c};
  1905. if (!$fp_a || !$fp_b) {
  1906. die "Commit $c\n",
  1907. "has no parent commit, and therefore ",
  1908. "nothing to diff against.\n",
  1909. "You should be working from a repository ",
  1910. "originally created by git-svn\n";
  1911. }
  1912. if ($fp_a ne $fp_b) {
  1913. die "$c~1 = $fp_a, however parsing commit $c ",
  1914. "revealed that:\n$c~1 = $fp_b\nBUG!\n";
  1915. }
  1916. foreach my $p (@{$parents{$c}}) {
  1917. $skip{$p} = 1;
  1918. }
  1919. }
  1920. (\@linear_refs, \%parents);
  1921. }
  1922. sub find_file_type_and_diff_status {
  1923. my ($path) = @_;
  1924. return ('dir', '') if $path eq '';
  1925. my $diff_output =
  1926. command_oneline(qw(diff --cached --name-status --), $path) || "";
  1927. my $diff_status = (split(' ', $diff_output))[0] || "";
  1928. my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
  1929. return (undef, undef) if !$diff_status && !$ls_tree;
  1930. if ($diff_status eq "A") {
  1931. return ("link", $diff_status) if -l $path;
  1932. return ("dir", $diff_status) if -d $path;
  1933. return ("file", $diff_status);
  1934. }
  1935. my $mode = (split(' ', $ls_tree))[0] || "";
  1936. return ("link", $diff_status) if $mode eq "120000";
  1937. return ("dir", $diff_status) if $mode eq "040000";
  1938. return ("file", $diff_status);
  1939. }
  1940. sub md5sum {
  1941. my $arg = shift;
  1942. my $ref = ref $arg;
  1943. require Digest::MD5;
  1944. my $md5 = Digest::MD5->new();
  1945. if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
  1946. $md5->addfile($arg) or croak $!;
  1947. } elsif ($ref eq 'SCALAR') {
  1948. $md5->add($$arg) or croak $!;
  1949. } elsif (!$ref) {
  1950. $md5->add($arg) or croak $!;
  1951. } else {
  1952. fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
  1953. }
  1954. return $md5->hexdigest();
  1955. }
  1956. sub gc_directory {
  1957. if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
  1958. my $out_filename = $_ . ".gz";
  1959. open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
  1960. binmode $in_fh;
  1961. my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
  1962. die "Unable to open $out_filename: $!\n";
  1963. my $res;
  1964. while ($res = sysread($in_fh, my $str, 1024)) {
  1965. $gz->gzwrite($str) or
  1966. die "Unable to write: ".$gz->gzerror()."!\n";
  1967. }
  1968. no warnings 'once'; # $File::Find::name would warn
  1969. unlink $_ or die "unlink $File::Find::name: $!\n";
  1970. } elsif (-f $_ && basename($_) eq "index") {
  1971. unlink $_ or die "unlink $_: $!\n";
  1972. }
  1973. }
  1974. __END__
  1975. Data structures:
  1976. $remotes = { # returned by read_all_remotes()
  1977. 'svn' => {
  1978. # svn-remote.svn.url=https://svn.musicpd.org
  1979. url => 'https://svn.musicpd.org',
  1980. # svn-remote.svn.fetch=mpd/trunk:trunk
  1981. fetch => {
  1982. 'mpd/trunk' => 'trunk',
  1983. },
  1984. # svn-remote.svn.tags=mpd/tags/*:tags/*
  1985. tags => {
  1986. path => {
  1987. left => 'mpd/tags',
  1988. right => '',
  1989. regex => qr!mpd/tags/([^/]+)$!,
  1990. glob => 'tags/*',
  1991. },
  1992. ref => {
  1993. left => 'tags',
  1994. right => '',
  1995. regex => qr!tags/([^/]+)$!,
  1996. glob => 'tags/*',
  1997. },
  1998. }
  1999. }
  2000. };
  2001. $log_entry hashref as returned by libsvn_log_entry()
  2002. {
  2003. log => 'whitespace-formatted log entry
  2004. ', # trailing newline is preserved
  2005. revision => '8', # integer
  2006. date => '2004-02-24T17:01:44.108345Z', # commit date
  2007. author => 'committer name'
  2008. };
  2009. # this is generated by generate_diff();
  2010. @mods = array of diff-index line hashes, each element represents one line
  2011. of diff-index output
  2012. diff-index line ($m hash)
  2013. {
  2014. mode_a => first column of diff-index output, no leading ':',
  2015. mode_b => second column of diff-index output,
  2016. sha1_b => sha1sum of the final blob,
  2017. chg => change type [MCRADT],
  2018. file_a => original file name of a file (iff chg is 'C' or 'R')
  2019. file_b => new/current file name of a file (any chg)
  2020. }
  2021. ;
  2022. # retval of read_url_paths{,_all}();
  2023. $l_map = {
  2024. # repository root url
  2025. 'https://svn.musicpd.org' => {
  2026. # repository path # GIT_SVN_ID
  2027. 'mpd/trunk' => 'trunk',
  2028. 'mpd/tags/0.11.5' => 'tags/0.11.5',
  2029. },
  2030. }
  2031. Notes:
  2032. I don't trust the each() function on unless I created %hash myself
  2033. because the internal iterator may not have started at base.