PageRenderTime 68ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 2ms

/git-svn.perl

https://bitbucket.org/definitelylion/git
Perl | 6787 lines | 5997 code | 471 blank | 319 comment | 835 complexity | 87a358f677d3b1a4ea91c10ac4040b68 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env perl
  2. # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
  3. # License: GPL v2 or later
  4. use 5.008;
  5. use warnings;
  6. use strict;
  7. use vars qw/ $AUTHOR $VERSION
  8. $sha1 $sha1_short $_revision $_repository
  9. $_q $_authors $_authors_prog %users/;
  10. $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  11. $VERSION = '@@GIT_VERSION@@';
  12. # From which subdir have we been invoked?
  13. my $cmd_dir_prefix = eval {
  14. command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  15. } || '';
  16. my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  17. $ENV{GIT_DIR} ||= '.git';
  18. $Git::SVN::default_repo_id = 'svn';
  19. $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
  20. $Git::SVN::Ra::_log_window_size = 100;
  21. $Git::SVN::_minimize_url = 'unset';
  22. if (! exists $ENV{SVN_SSH} && 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. sub _req_svn {
  34. require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  35. require SVN::Ra;
  36. require SVN::Delta;
  37. if ($SVN::Core::VERSION lt '1.1.0') {
  38. fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  39. }
  40. }
  41. my $can_compress = eval { require Compress::Zlib; 1};
  42. push @Git::SVN::Ra::ISA, 'SVN::Ra';
  43. push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
  44. push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
  45. use Carp qw/croak/;
  46. use Digest::MD5;
  47. use IO::File qw//;
  48. use File::Basename qw/dirname basename/;
  49. use File::Path qw/mkpath/;
  50. use File::Spec;
  51. use File::Find;
  52. use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  53. use IPC::Open3;
  54. use Git;
  55. use Memoize; # core since 5.8.0, Jul 2002
  56. BEGIN {
  57. # import functions from Git into our packages, en masse
  58. no strict 'refs';
  59. foreach (qw/command command_oneline command_noisy command_output_pipe
  60. command_input_pipe command_close_pipe
  61. command_bidi_pipe command_close_bidi_pipe/) {
  62. for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
  63. Git::SVN::Migration Git::SVN::Log Git::SVN),
  64. __PACKAGE__) {
  65. *{"${package}::$_"} = \&{"Git::$_"};
  66. }
  67. }
  68. Memoize::memoize 'Git::config';
  69. Memoize::memoize 'Git::config_bool';
  70. }
  71. my ($SVN);
  72. $sha1 = qr/[a-f\d]{40}/;
  73. $sha1_short = qr/[a-f\d]{4,40}/;
  74. my ($_stdin, $_help, $_edit,
  75. $_message, $_file, $_branch_dest,
  76. $_template, $_shared,
  77. $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
  78. $_merge, $_strategy, $_dry_run, $_local,
  79. $_prefix, $_no_checkout, $_url, $_verbose,
  80. $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
  81. $Git::SVN::_follow_parent = 1;
  82. $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
  83. $_q ||= 0;
  84. my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  85. 'config-dir=s' => \$Git::SVN::Ra::config_dir,
  86. 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
  87. 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
  88. 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
  89. my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  90. 'authors-file|A=s' => \$_authors,
  91. 'authors-prog=s' => \$_authors_prog,
  92. 'repack:i' => \$Git::SVN::_repack,
  93. 'noMetadata' => \$Git::SVN::_no_metadata,
  94. 'useSvmProps' => \$Git::SVN::_use_svm_props,
  95. 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  96. 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  97. 'no-checkout' => \$_no_checkout,
  98. 'quiet|q+' => \$_q,
  99. 'repack-flags|repack-args|repack-opts=s' =>
  100. \$Git::SVN::_repack_flags,
  101. 'use-log-author' => \$Git::SVN::_use_log_author,
  102. 'add-author-from' => \$Git::SVN::_add_author_from,
  103. 'localtime' => \$Git::SVN::_localtime,
  104. %remote_opts );
  105. my ($_trunk, @_tags, @_branches, $_stdlayout);
  106. my %icv;
  107. my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  108. 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
  109. 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
  110. 'stdlayout|s' => \$_stdlayout,
  111. 'minimize-url|m!' => \$Git::SVN::_minimize_url,
  112. 'no-metadata' => sub { $icv{noMetadata} = 1 },
  113. 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  114. 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  115. 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  116. 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
  117. %remote_opts );
  118. my %cmt_opts = ( 'edit|e' => \$_edit,
  119. 'rmdir' => \$SVN::Git::Editor::_rmdir,
  120. 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
  121. 'l=i' => \$SVN::Git::Editor::_rename_limit,
  122. 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
  123. );
  124. my %cmd = (
  125. fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  126. { 'revision|r=s' => \$_revision,
  127. 'fetch-all|all' => \$_fetch_all,
  128. 'parent|p' => \$_fetch_parent,
  129. %fc_opts } ],
  130. clone => [ \&cmd_clone, "Initialize and fetch revisions",
  131. { 'revision|r=s' => \$_revision,
  132. 'preserve-empty-dirs' =>
  133. \$SVN::Git::Fetcher::_preserve_empty_dirs,
  134. 'placeholder-filename=s' =>
  135. \$SVN::Git::Fetcher::_placeholder_filename,
  136. %fc_opts, %init_opts } ],
  137. init => [ \&cmd_init, "Initialize a repo for tracking" .
  138. " (requires URL argument)",
  139. \%init_opts ],
  140. 'multi-init' => [ \&cmd_multi_init,
  141. "Deprecated alias for ".
  142. "'$0 init -T<trunk> -b<branches> -t<tags>'",
  143. \%init_opts ],
  144. dcommit => [ \&cmd_dcommit,
  145. 'Commit several diffs to merge with upstream',
  146. { 'merge|m|M' => \$_merge,
  147. 'strategy|s=s' => \$_strategy,
  148. 'verbose|v' => \$_verbose,
  149. 'dry-run|n' => \$_dry_run,
  150. 'fetch-all|all' => \$_fetch_all,
  151. 'commit-url=s' => \$_commit_url,
  152. 'revision|r=i' => \$_revision,
  153. 'no-rebase' => \$_no_rebase,
  154. 'mergeinfo=s' => \$_merge_info,
  155. 'interactive|i' => \$_interactive,
  156. %cmt_opts, %fc_opts } ],
  157. branch => [ \&cmd_branch,
  158. 'Create a branch in the SVN repository',
  159. { 'message|m=s' => \$_message,
  160. 'destination|d=s' => \$_branch_dest,
  161. 'dry-run|n' => \$_dry_run,
  162. 'tag|t' => \$_tag,
  163. 'username=s' => \$Git::SVN::Prompt::_username,
  164. 'commit-url=s' => \$_commit_url } ],
  165. tag => [ sub { $_tag = 1; cmd_branch(@_) },
  166. 'Create a tag in the SVN repository',
  167. { 'message|m=s' => \$_message,
  168. 'destination|d=s' => \$_branch_dest,
  169. 'dry-run|n' => \$_dry_run,
  170. 'username=s' => \$Git::SVN::Prompt::_username,
  171. 'commit-url=s' => \$_commit_url } ],
  172. 'set-tree' => [ \&cmd_set_tree,
  173. "Set an SVN repository to a git tree-ish",
  174. { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
  175. 'create-ignore' => [ \&cmd_create_ignore,
  176. 'Create a .gitignore per svn:ignore',
  177. { 'revision|r=i' => \$_revision
  178. } ],
  179. 'mkdirs' => [ \&cmd_mkdirs ,
  180. "recreate empty directories after a checkout",
  181. { 'revision|r=i' => \$_revision } ],
  182. 'propget' => [ \&cmd_propget,
  183. 'Print the value of a property on a file or directory',
  184. { 'revision|r=i' => \$_revision } ],
  185. 'proplist' => [ \&cmd_proplist,
  186. 'List all properties of a file or directory',
  187. { 'revision|r=i' => \$_revision } ],
  188. 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
  189. { 'revision|r=i' => \$_revision
  190. } ],
  191. 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
  192. { 'revision|r=i' => \$_revision
  193. } ],
  194. 'multi-fetch' => [ \&cmd_multi_fetch,
  195. "Deprecated alias for $0 fetch --all",
  196. { 'revision|r=s' => \$_revision, %fc_opts } ],
  197. 'migrate' => [ sub { },
  198. # no-op, we automatically run this anyways,
  199. 'Migrate configuration/metadata/layout from
  200. previous versions of git-svn',
  201. { 'minimize' => \$Git::SVN::Migration::_minimize,
  202. %remote_opts } ],
  203. 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
  204. { 'limit=i' => \$Git::SVN::Log::limit,
  205. 'revision|r=s' => \$_revision,
  206. 'verbose|v' => \$Git::SVN::Log::verbose,
  207. 'incremental' => \$Git::SVN::Log::incremental,
  208. 'oneline' => \$Git::SVN::Log::oneline,
  209. 'show-commit' => \$Git::SVN::Log::show_commit,
  210. 'non-recursive' => \$Git::SVN::Log::non_recursive,
  211. 'authors-file|A=s' => \$_authors,
  212. 'color' => \$Git::SVN::Log::color,
  213. 'pager=s' => \$Git::SVN::Log::pager
  214. } ],
  215. 'find-rev' => [ \&cmd_find_rev,
  216. "Translate between SVN revision numbers and tree-ish",
  217. {} ],
  218. 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
  219. { 'merge|m|M' => \$_merge,
  220. 'verbose|v' => \$_verbose,
  221. 'strategy|s=s' => \$_strategy,
  222. 'local|l' => \$_local,
  223. 'fetch-all|all' => \$_fetch_all,
  224. 'dry-run|n' => \$_dry_run,
  225. %fc_opts } ],
  226. 'commit-diff' => [ \&cmd_commit_diff,
  227. 'Commit a diff between two trees',
  228. { 'message|m=s' => \$_message,
  229. 'file|F=s' => \$_file,
  230. 'revision|r=s' => \$_revision,
  231. %cmt_opts } ],
  232. 'info' => [ \&cmd_info,
  233. "Show info about the latest SVN revision
  234. on the current branch",
  235. { 'url' => \$_url, } ],
  236. 'blame' => [ \&Git::SVN::Log::cmd_blame,
  237. "Show what revision and author last modified each line of a file",
  238. { 'git-format' => \$_git_format } ],
  239. 'reset' => [ \&cmd_reset,
  240. "Undo fetches back to the specified SVN revision",
  241. { 'revision|r=s' => \$_revision,
  242. 'parent|p' => \$_fetch_parent } ],
  243. 'gc' => [ \&cmd_gc,
  244. "Compress unhandled.log files in .git/svn and remove " .
  245. "index files in .git/svn",
  246. {} ],
  247. );
  248. use Term::ReadLine;
  249. package FakeTerm;
  250. sub new {
  251. my ($class, $reason) = @_;
  252. return bless \$reason, shift;
  253. }
  254. sub readline {
  255. my $self = shift;
  256. die "Cannot use readline on FakeTerm: $$self";
  257. }
  258. package main;
  259. my $term = eval {
  260. $ENV{"GIT_SVN_NOTTY"}
  261. ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
  262. : new Term::ReadLine 'git-svn';
  263. };
  264. if ($@) {
  265. $term = new FakeTerm "$@: going non-interactive";
  266. }
  267. my $cmd;
  268. for (my $i = 0; $i < @ARGV; $i++) {
  269. if (defined $cmd{$ARGV[$i]}) {
  270. $cmd = $ARGV[$i];
  271. splice @ARGV, $i, 1;
  272. last;
  273. } elsif ($ARGV[$i] eq 'help') {
  274. $cmd = $ARGV[$i+1];
  275. usage(0);
  276. }
  277. };
  278. # make sure we're always running at the top-level working directory
  279. unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
  280. unless (-d $ENV{GIT_DIR}) {
  281. if ($git_dir_user_set) {
  282. die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
  283. "but it is not a directory\n";
  284. }
  285. my $git_dir = delete $ENV{GIT_DIR};
  286. my $cdup = undef;
  287. git_cmd_try {
  288. $cdup = command_oneline(qw/rev-parse --show-cdup/);
  289. $git_dir = '.' unless ($cdup);
  290. chomp $cdup if ($cdup);
  291. $cdup = "." unless ($cdup && length $cdup);
  292. } "Already at toplevel, but $git_dir not found\n";
  293. chdir $cdup or die "Unable to chdir up to '$cdup'\n";
  294. unless (-d $git_dir) {
  295. die "$git_dir still not found after going to ",
  296. "'$cdup'\n";
  297. }
  298. $ENV{GIT_DIR} = $git_dir;
  299. }
  300. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  301. }
  302. my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  303. read_git_config(\%opts);
  304. if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
  305. Getopt::Long::Configure('pass_through');
  306. }
  307. my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
  308. 'minimize-connections' => \$Git::SVN::Migration::_minimize,
  309. 'id|i=s' => \$Git::SVN::default_ref_id,
  310. 'svn-remote|remote|R=s' => sub {
  311. $Git::SVN::no_reuse_existing = 1;
  312. $Git::SVN::default_repo_id = $_[1] });
  313. exit 1 if (!$rv && $cmd && $cmd ne 'log');
  314. usage(0) if $_help;
  315. version() if $_version;
  316. usage(1) unless defined $cmd;
  317. load_authors() if $_authors;
  318. if (defined $_authors_prog) {
  319. $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
  320. }
  321. unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
  322. Git::SVN::Migration::migration_check();
  323. }
  324. Git::SVN::init_vars();
  325. eval {
  326. Git::SVN::verify_remotes_sanity();
  327. $cmd{$cmd}->[0]->(@ARGV);
  328. };
  329. fatal $@ if $@;
  330. post_fetch_checkout();
  331. exit 0;
  332. ####################### primary functions ######################
  333. sub usage {
  334. my $exit = shift || 0;
  335. my $fd = $exit ? \*STDERR : \*STDOUT;
  336. print $fd <<"";
  337. git-svn - bidirectional operations between a single Subversion tree and git
  338. Usage: git svn <command> [options] [arguments]\n
  339. print $fd "Available commands:\n" unless $cmd;
  340. foreach (sort keys %cmd) {
  341. next if $cmd && $cmd ne $_;
  342. next if /^multi-/; # don't show deprecated commands
  343. print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
  344. foreach (sort keys %{$cmd{$_}->[2]}) {
  345. # mixed-case options are for .git/config only
  346. next if /[A-Z]/ && /^[a-z]+$/i;
  347. # prints out arguments as they should be passed:
  348. my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
  349. print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
  350. "--$_" : "-$_" }
  351. split /\|/,$_)," $x\n";
  352. }
  353. }
  354. print $fd <<"";
  355. \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
  356. arbitrary identifier if you're tracking multiple SVN branches/repositories in
  357. one git repository and want to keep them separate. See git-svn(1) for more
  358. information.
  359. exit $exit;
  360. }
  361. sub version {
  362. ::_req_svn();
  363. print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
  364. exit 0;
  365. }
  366. sub ask {
  367. my ($prompt, %arg) = @_;
  368. my $valid_re = $arg{valid_re};
  369. my $default = $arg{default};
  370. my $resp;
  371. my $i = 0;
  372. if ( !( defined($term->IN)
  373. && defined( fileno($term->IN) )
  374. && defined( $term->OUT )
  375. && defined( fileno($term->OUT) ) ) ){
  376. return defined($default) ? $default : undef;
  377. }
  378. while ($i++ < 10) {
  379. $resp = $term->readline($prompt);
  380. if (!defined $resp) { # EOF
  381. print "\n";
  382. return defined $default ? $default : undef;
  383. }
  384. if ($resp eq '' and defined $default) {
  385. return $default;
  386. }
  387. if (!defined $valid_re or $resp =~ /$valid_re/) {
  388. return $resp;
  389. }
  390. }
  391. return undef;
  392. }
  393. sub do_git_init_db {
  394. unless (-d $ENV{GIT_DIR}) {
  395. my @init_db = ('init');
  396. push @init_db, "--template=$_template" if defined $_template;
  397. if (defined $_shared) {
  398. if ($_shared =~ /[a-z]/) {
  399. push @init_db, "--shared=$_shared";
  400. } else {
  401. push @init_db, "--shared";
  402. }
  403. }
  404. command_noisy(@init_db);
  405. $_repository = Git->repository(Repository => ".git");
  406. }
  407. my $set;
  408. my $pfx = "svn-remote.$Git::SVN::default_repo_id";
  409. foreach my $i (keys %icv) {
  410. die "'$set' and '$i' cannot both be set\n" if $set;
  411. next unless defined $icv{$i};
  412. command_noisy('config', "$pfx.$i", $icv{$i});
  413. $set = $i;
  414. }
  415. my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
  416. command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
  417. if defined $$ignore_paths_regex;
  418. my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
  419. command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
  420. if defined $$ignore_refs_regex;
  421. if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
  422. my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
  423. command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
  424. command_noisy('config', "$pfx.placeholder-filename", $$fname);
  425. }
  426. }
  427. sub init_subdir {
  428. my $repo_path = shift or return;
  429. mkpath([$repo_path]) unless -d $repo_path;
  430. chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
  431. $ENV{GIT_DIR} = '.git';
  432. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  433. }
  434. sub cmd_clone {
  435. my ($url, $path) = @_;
  436. if (!defined $path &&
  437. (defined $_trunk || @_branches || @_tags ||
  438. defined $_stdlayout) &&
  439. $url !~ m#^[a-z\+]+://#) {
  440. $path = $url;
  441. }
  442. $path = basename($url) if !defined $path || !length $path;
  443. my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
  444. cmd_init($url, $path);
  445. command_oneline('config', 'svn.authorsfile', $authors_absolute)
  446. if $_authors;
  447. Git::SVN::fetch_all($Git::SVN::default_repo_id);
  448. }
  449. sub cmd_init {
  450. if (defined $_stdlayout) {
  451. $_trunk = 'trunk' if (!defined $_trunk);
  452. @_tags = 'tags' if (! @_tags);
  453. @_branches = 'branches' if (! @_branches);
  454. }
  455. if (defined $_trunk || @_branches || @_tags) {
  456. return cmd_multi_init(@_);
  457. }
  458. my $url = shift or die "SVN repository location required ",
  459. "as a command-line argument\n";
  460. $url = canonicalize_url($url);
  461. init_subdir(@_);
  462. do_git_init_db();
  463. if ($Git::SVN::_minimize_url eq 'unset') {
  464. $Git::SVN::_minimize_url = 0;
  465. }
  466. Git::SVN->init($url);
  467. }
  468. sub cmd_fetch {
  469. if (grep /^\d+=./, @_) {
  470. die "'<rev>=<commit>' fetch arguments are ",
  471. "no longer supported.\n";
  472. }
  473. my ($remote) = @_;
  474. if (@_ > 1) {
  475. die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
  476. }
  477. $Git::SVN::no_reuse_existing = undef;
  478. if ($_fetch_parent) {
  479. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  480. unless ($gs) {
  481. die "Unable to determine upstream SVN information from ",
  482. "working tree history\n";
  483. }
  484. # just fetch, don't checkout.
  485. $_no_checkout = 'true';
  486. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  487. } elsif ($_fetch_all) {
  488. cmd_multi_fetch();
  489. } else {
  490. $remote ||= $Git::SVN::default_repo_id;
  491. Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
  492. }
  493. }
  494. sub cmd_set_tree {
  495. my (@commits) = @_;
  496. if ($_stdin || !@commits) {
  497. print "Reading from stdin...\n";
  498. @commits = ();
  499. while (<STDIN>) {
  500. if (/\b($sha1_short)\b/o) {
  501. unshift @commits, $1;
  502. }
  503. }
  504. }
  505. my @revs;
  506. foreach my $c (@commits) {
  507. my @tmp = command('rev-parse',$c);
  508. if (scalar @tmp == 1) {
  509. push @revs, $tmp[0];
  510. } elsif (scalar @tmp > 1) {
  511. push @revs, reverse(command('rev-list',@tmp));
  512. } else {
  513. fatal "Failed to rev-parse $c";
  514. }
  515. }
  516. my $gs = Git::SVN->new;
  517. my ($r_last, $cmt_last) = $gs->last_rev_commit;
  518. $gs->fetch;
  519. if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
  520. fatal "There are new revisions that were fetched ",
  521. "and need to be merged (or acknowledged) ",
  522. "before committing.\nlast rev: $r_last\n",
  523. " current: $gs->{last_rev}";
  524. }
  525. $gs->set_tree($_) foreach @revs;
  526. print "Done committing ",scalar @revs," revisions to SVN\n";
  527. unlink $gs->{index};
  528. }
  529. sub split_merge_info_range {
  530. my ($range) = @_;
  531. if ($range =~ /(\d+)-(\d+)/) {
  532. return (int($1), int($2));
  533. } else {
  534. return (int($range), int($range));
  535. }
  536. }
  537. sub combine_ranges {
  538. my ($in) = @_;
  539. my @fnums = ();
  540. my @arr = split(/,/, $in);
  541. for my $element (@arr) {
  542. my ($start, $end) = split_merge_info_range($element);
  543. push @fnums, $start;
  544. }
  545. my @sorted = @arr [ sort {
  546. $fnums[$a] <=> $fnums[$b]
  547. } 0..$#arr ];
  548. my @return = ();
  549. my $last = -1;
  550. my $first = -1;
  551. for my $element (@sorted) {
  552. my ($start, $end) = split_merge_info_range($element);
  553. if ($last == -1) {
  554. $first = $start;
  555. $last = $end;
  556. next;
  557. }
  558. if ($start <= $last+1) {
  559. if ($end > $last) {
  560. $last = $end;
  561. }
  562. next;
  563. }
  564. if ($first == $last) {
  565. push @return, "$first";
  566. } else {
  567. push @return, "$first-$last";
  568. }
  569. $first = $start;
  570. $last = $end;
  571. }
  572. if ($first != -1) {
  573. if ($first == $last) {
  574. push @return, "$first";
  575. } else {
  576. push @return, "$first-$last";
  577. }
  578. }
  579. return join(',', @return);
  580. }
  581. sub merge_revs_into_hash {
  582. my ($hash, $minfo) = @_;
  583. my @lines = split(' ', $minfo);
  584. for my $line (@lines) {
  585. my ($branchpath, $revs) = split(/:/, $line);
  586. if (exists($hash->{$branchpath})) {
  587. # Merge the two revision sets
  588. my $combined = "$hash->{$branchpath},$revs";
  589. $hash->{$branchpath} = combine_ranges($combined);
  590. } else {
  591. # Just do range combining for consolidation
  592. $hash->{$branchpath} = combine_ranges($revs);
  593. }
  594. }
  595. }
  596. sub merge_merge_info {
  597. my ($mergeinfo_one, $mergeinfo_two) = @_;
  598. my %result_hash = ();
  599. merge_revs_into_hash(\%result_hash, $mergeinfo_one);
  600. merge_revs_into_hash(\%result_hash, $mergeinfo_two);
  601. my $result = '';
  602. # Sort below is for consistency's sake
  603. for my $branchname (sort keys(%result_hash)) {
  604. my $revlist = $result_hash{$branchname};
  605. $result .= "$branchname:$revlist\n"
  606. }
  607. return $result;
  608. }
  609. sub populate_merge_info {
  610. my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
  611. my %parentshash;
  612. read_commit_parents(\%parentshash, $d);
  613. my @parents = @{$parentshash{$d}};
  614. if ($#parents > 0) {
  615. # Merge commit
  616. my $all_parents_ok = 1;
  617. my $aggregate_mergeinfo = '';
  618. my $rooturl = $gs->repos_root;
  619. if (defined($rewritten_parent)) {
  620. # Replace first parent with newly-rewritten version
  621. shift @parents;
  622. unshift @parents, $rewritten_parent;
  623. }
  624. foreach my $parent (@parents) {
  625. my ($branchurl, $svnrev, $paruuid) =
  626. cmt_metadata($parent);
  627. unless (defined($svnrev)) {
  628. # Should have been caught be preflight check
  629. fatal "merge commit $d has ancestor $parent, but that change "
  630. ."does not have git-svn metadata!";
  631. }
  632. unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
  633. fatal "commit $parent git-svn metadata changed mid-run!";
  634. }
  635. my $branchpath = $1;
  636. my $ra = Git::SVN::Ra->new($branchurl);
  637. my (undef, undef, $props) =
  638. $ra->get_dir(canonicalize_path("."), $svnrev);
  639. my $par_mergeinfo = $props->{'svn:mergeinfo'};
  640. unless (defined $par_mergeinfo) {
  641. $par_mergeinfo = '';
  642. }
  643. # Merge previous mergeinfo values
  644. $aggregate_mergeinfo =
  645. merge_merge_info($aggregate_mergeinfo,
  646. $par_mergeinfo, 0);
  647. next if $parent eq $parents[0]; # Skip first parent
  648. # Add new changes being placed in tree by merge
  649. my @cmd = (qw/rev-list --reverse/,
  650. $parent, qw/--not/);
  651. foreach my $par (@parents) {
  652. unless ($par eq $parent) {
  653. push @cmd, $par;
  654. }
  655. }
  656. my @revsin = ();
  657. my ($revlist, $ctx) = command_output_pipe(@cmd);
  658. while (<$revlist>) {
  659. my $irev = $_;
  660. chomp $irev;
  661. my (undef, $csvnrev, undef) =
  662. cmt_metadata($irev);
  663. unless (defined $csvnrev) {
  664. # A child is missing SVN annotations...
  665. # this might be OK, or might not be.
  666. warn "W:child $irev is merged into revision "
  667. ."$d but does not have git-svn metadata. "
  668. ."This means git-svn cannot determine the "
  669. ."svn revision numbers to place into the "
  670. ."svn:mergeinfo property. You must ensure "
  671. ."a branch is entirely committed to "
  672. ."SVN before merging it in order for "
  673. ."svn:mergeinfo population to function "
  674. ."properly";
  675. }
  676. push @revsin, $csvnrev;
  677. }
  678. command_close_pipe($revlist, $ctx);
  679. last unless $all_parents_ok;
  680. # We now have a list of all SVN revnos which are
  681. # merged by this particular parent. Integrate them.
  682. next if $#revsin == -1;
  683. my $newmergeinfo = "$branchpath:" . join(',', @revsin);
  684. $aggregate_mergeinfo =
  685. merge_merge_info($aggregate_mergeinfo,
  686. $newmergeinfo, 1);
  687. }
  688. if ($all_parents_ok and $aggregate_mergeinfo) {
  689. return $aggregate_mergeinfo;
  690. }
  691. }
  692. return undef;
  693. }
  694. sub cmd_dcommit {
  695. my $head = shift;
  696. command_noisy(qw/update-index --refresh/);
  697. git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
  698. 'Cannot dcommit with a dirty index. Commit your changes first, '
  699. . "or stash them with `git stash'.\n";
  700. $head ||= 'HEAD';
  701. my $old_head;
  702. if ($head ne 'HEAD') {
  703. $old_head = eval {
  704. command_oneline([qw/symbolic-ref -q HEAD/])
  705. };
  706. if ($old_head) {
  707. $old_head =~ s{^refs/heads/}{};
  708. } else {
  709. $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
  710. }
  711. command(['checkout', $head], STDERR => 0);
  712. }
  713. my @refs;
  714. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
  715. unless ($gs) {
  716. die "Unable to determine upstream SVN information from ",
  717. "$head history.\nPerhaps the repository is empty.";
  718. }
  719. if (defined $_commit_url) {
  720. $url = $_commit_url;
  721. } else {
  722. $url = eval { command_oneline('config', '--get',
  723. "svn-remote.$gs->{repo_id}.commiturl") };
  724. if (!$url) {
  725. $url = $gs->full_pushurl
  726. }
  727. }
  728. my $last_rev = $_revision if defined $_revision;
  729. if ($url) {
  730. print "Committing to $url ...\n";
  731. }
  732. my ($linear_refs, $parents) = linearize_history($gs, \@refs);
  733. if ($_no_rebase && scalar(@$linear_refs) > 1) {
  734. warn "Attempting to commit more than one change while ",
  735. "--no-rebase is enabled.\n",
  736. "If these changes depend on each other, re-running ",
  737. "without --no-rebase may be required."
  738. }
  739. if (defined $_interactive){
  740. my $ask_default = "y";
  741. foreach my $d (@$linear_refs){
  742. my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
  743. while (<$fh>){
  744. print $_;
  745. }
  746. command_close_pipe($fh, $ctx);
  747. $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
  748. valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
  749. default => $ask_default);
  750. die "Commit this patch reply required" unless defined $_;
  751. if (/^[nq]/i) {
  752. exit(0);
  753. } elsif (/^a/i) {
  754. last;
  755. }
  756. }
  757. }
  758. my $expect_url = $url;
  759. my $push_merge_info = eval {
  760. command_oneline(qw/config --get svn.pushmergeinfo/)
  761. };
  762. if (not defined($push_merge_info)
  763. or $push_merge_info eq "false"
  764. or $push_merge_info eq "no"
  765. or $push_merge_info eq "never") {
  766. $push_merge_info = 0;
  767. }
  768. unless (defined($_merge_info) || ! $push_merge_info) {
  769. # Preflight check of changes to ensure no issues with mergeinfo
  770. # This includes check for uncommitted-to-SVN parents
  771. # (other than the first parent, which we will handle),
  772. # information from different SVN repos, and paths
  773. # which are not underneath this repository root.
  774. my $rooturl = $gs->repos_root;
  775. foreach my $d (@$linear_refs) {
  776. my %parentshash;
  777. read_commit_parents(\%parentshash, $d);
  778. my @realparents = @{$parentshash{$d}};
  779. if ($#realparents > 0) {
  780. # Merge commit
  781. shift @realparents; # Remove/ignore first parent
  782. foreach my $parent (@realparents) {
  783. my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
  784. unless (defined $paruuid) {
  785. # A parent is missing SVN annotations...
  786. # abort the whole operation.
  787. fatal "$parent is merged into revision $d, "
  788. ."but does not have git-svn metadata. "
  789. ."Either dcommit the branch or use a "
  790. ."local cherry-pick, FF merge, or rebase "
  791. ."instead of an explicit merge commit.";
  792. }
  793. unless ($paruuid eq $uuid) {
  794. # Parent has SVN metadata from different repository
  795. fatal "merge parent $parent for change $d has "
  796. ."git-svn uuid $paruuid, while current change "
  797. ."has uuid $uuid!";
  798. }
  799. unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
  800. # This branch is very strange indeed.
  801. fatal "merge parent $parent for $d is on branch "
  802. ."$branchurl, which is not under the "
  803. ."git-svn root $rooturl!";
  804. }
  805. }
  806. }
  807. }
  808. }
  809. my $rewritten_parent;
  810. Git::SVN::remove_username($expect_url);
  811. if (defined($_merge_info)) {
  812. $_merge_info =~ tr{ }{\n};
  813. }
  814. while (1) {
  815. my $d = shift @$linear_refs or last;
  816. unless (defined $last_rev) {
  817. (undef, $last_rev, undef) = cmt_metadata("$d~1");
  818. unless (defined $last_rev) {
  819. fatal "Unable to extract revision information ",
  820. "from commit $d~1";
  821. }
  822. }
  823. if ($_dry_run) {
  824. print "diff-tree $d~1 $d\n";
  825. } else {
  826. my $cmt_rev;
  827. unless (defined($_merge_info) || ! $push_merge_info) {
  828. $_merge_info = populate_merge_info($d, $gs,
  829. $uuid,
  830. $linear_refs,
  831. $rewritten_parent);
  832. }
  833. my %ed_opts = ( r => $last_rev,
  834. log => get_commit_entry($d)->{log},
  835. ra => Git::SVN::Ra->new($url),
  836. config => SVN::Core::config_get_config(
  837. $Git::SVN::Ra::config_dir
  838. ),
  839. tree_a => "$d~1",
  840. tree_b => $d,
  841. editor_cb => sub {
  842. print "Committed r$_[0]\n";
  843. $cmt_rev = $_[0];
  844. },
  845. mergeinfo => $_merge_info,
  846. svn_path => '');
  847. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  848. print "No changes\n$d~1 == $d\n";
  849. } elsif ($parents->{$d} && @{$parents->{$d}}) {
  850. $gs->{inject_parents_dcommit}->{$cmt_rev} =
  851. $parents->{$d};
  852. }
  853. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  854. $last_rev = $cmt_rev;
  855. next if $_no_rebase;
  856. # we always want to rebase against the current HEAD,
  857. # not any head that was passed to us
  858. my @diff = command('diff-tree', $d,
  859. $gs->refname, '--');
  860. my @finish;
  861. if (@diff) {
  862. @finish = rebase_cmd();
  863. print STDERR "W: $d and ", $gs->refname,
  864. " differ, using @finish:\n",
  865. join("\n", @diff), "\n";
  866. } else {
  867. print "No changes between current HEAD and ",
  868. $gs->refname,
  869. "\nResetting to the latest ",
  870. $gs->refname, "\n";
  871. @finish = qw/reset --mixed/;
  872. }
  873. command_noisy(@finish, $gs->refname);
  874. $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
  875. if (@diff) {
  876. @refs = ();
  877. my ($url_, $rev_, $uuid_, $gs_) =
  878. working_head_info('HEAD', \@refs);
  879. my ($linear_refs_, $parents_) =
  880. linearize_history($gs_, \@refs);
  881. if (scalar(@$linear_refs) !=
  882. scalar(@$linear_refs_)) {
  883. fatal "# of revisions changed ",
  884. "\nbefore:\n",
  885. join("\n", @$linear_refs),
  886. "\n\nafter:\n",
  887. join("\n", @$linear_refs_), "\n",
  888. 'If you are attempting to commit ',
  889. "merges, try running:\n\t",
  890. 'git rebase --interactive',
  891. '--preserve-merges ',
  892. $gs->refname,
  893. "\nBefore dcommitting";
  894. }
  895. if ($url_ ne $expect_url) {
  896. if ($url_ eq $gs->metadata_url) {
  897. print
  898. "Accepting rewritten URL:",
  899. " $url_\n";
  900. } else {
  901. fatal
  902. "URL mismatch after rebase:",
  903. " $url_ != $expect_url";
  904. }
  905. }
  906. if ($uuid_ ne $uuid) {
  907. fatal "uuid mismatch after rebase: ",
  908. "$uuid_ != $uuid";
  909. }
  910. # remap parents
  911. my (%p, @l, $i);
  912. for ($i = 0; $i < scalar @$linear_refs; $i++) {
  913. my $new = $linear_refs_->[$i] or next;
  914. $p{$new} =
  915. $parents->{$linear_refs->[$i]};
  916. push @l, $new;
  917. }
  918. $parents = \%p;
  919. $linear_refs = \@l;
  920. }
  921. }
  922. }
  923. if ($old_head) {
  924. my $new_head = command_oneline(qw/rev-parse HEAD/);
  925. my $new_is_symbolic = eval {
  926. command_oneline(qw/symbolic-ref -q HEAD/);
  927. };
  928. if ($new_is_symbolic) {
  929. print "dcommitted the branch ", $head, "\n";
  930. } else {
  931. print "dcommitted on a detached HEAD because you gave ",
  932. "a revision argument.\n",
  933. "The rewritten commit is: ", $new_head, "\n";
  934. }
  935. command(['checkout', $old_head], STDERR => 0);
  936. }
  937. unlink $gs->{index};
  938. }
  939. sub cmd_branch {
  940. my ($branch_name, $head) = @_;
  941. unless (defined $branch_name && length $branch_name) {
  942. die(($_tag ? "tag" : "branch") . " name required\n");
  943. }
  944. $head ||= 'HEAD';
  945. my (undef, $rev, undef, $gs) = working_head_info($head);
  946. my $src = $gs->full_pushurl;
  947. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  948. my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
  949. my $glob;
  950. if ($#{$allglobs} == 0) {
  951. $glob = $allglobs->[0];
  952. } else {
  953. unless(defined $_branch_dest) {
  954. die "Multiple ",
  955. $_tag ? "tag" : "branch",
  956. " paths defined for Subversion repository.\n",
  957. "You must specify where you want to create the ",
  958. $_tag ? "tag" : "branch",
  959. " with the --destination argument.\n";
  960. }
  961. foreach my $g (@{$allglobs}) {
  962. # SVN::Git::Editor could probably be moved to Git.pm..
  963. my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
  964. if ($_branch_dest =~ /$re/) {
  965. $glob = $g;
  966. last;
  967. }
  968. }
  969. unless (defined $glob) {
  970. my $dest_re = qr/\b\Q$_branch_dest\E\b/;
  971. foreach my $g (@{$allglobs}) {
  972. $g->{path}->{left} =~ /$dest_re/ or next;
  973. if (defined $glob) {
  974. die "Ambiguous destination: ",
  975. $_branch_dest, "\nmatches both '",
  976. $glob->{path}->{left}, "' and '",
  977. $g->{path}->{left}, "'\n";
  978. }
  979. $glob = $g;
  980. }
  981. unless (defined $glob) {
  982. die "Unknown ",
  983. $_tag ? "tag" : "branch",
  984. " destination $_branch_dest\n";
  985. }
  986. }
  987. }
  988. my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
  989. my $url;
  990. if (defined $_commit_url) {
  991. $url = $_commit_url;
  992. } else {
  993. $url = eval { command_oneline('config', '--get',
  994. "svn-remote.$gs->{repo_id}.commiturl") };
  995. if (!$url) {
  996. $url = $remote->{pushurl} || $remote->{url};
  997. }
  998. }
  999. my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
  1000. if ($dst =~ /^https:/ && $src =~ /^http:/) {
  1001. $src=~s/^http:/https:/;
  1002. }
  1003. ::_req_svn();
  1004. my $ctx = SVN::Client->new(
  1005. auth => Git::SVN::Ra::_auth_providers(),
  1006. log_msg => sub {
  1007. ${ $_[0] } = defined $_message
  1008. ? $_message
  1009. : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
  1010. . $branch_name;
  1011. },
  1012. );
  1013. eval {
  1014. $ctx->ls($dst, 'HEAD', 0);
  1015. } and die "branch ${branch_name} already exists\n";
  1016. print "Copying ${src} at r${rev} to ${dst}...\n";
  1017. $ctx->copy($src, $rev, $dst)
  1018. unless $_dry_run;
  1019. $gs->fetch_all;
  1020. }
  1021. sub cmd_find_rev {
  1022. my $revision_or_hash = shift or die "SVN or git revision required ",
  1023. "as a command-line argument\n";
  1024. my $result;
  1025. if ($revision_or_hash =~ /^r\d+$/) {
  1026. my $head = shift;
  1027. $head ||= 'HEAD';
  1028. my @refs;
  1029. my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
  1030. unless ($gs) {
  1031. die "Unable to determine upstream SVN information from ",
  1032. "$head history\n";
  1033. }
  1034. my $desired_revision = substr($revision_or_hash, 1);
  1035. $result = $gs->rev_map_get($desired_revision, $uuid);
  1036. } else {
  1037. my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
  1038. $result = $rev;
  1039. }
  1040. print "$result\n" if $result;
  1041. }
  1042. sub auto_create_empty_directories {
  1043. my ($gs) = @_;
  1044. my $var = eval { command_oneline('config', '--get', '--bool',
  1045. "svn-remote.$gs->{repo_id}.automkdirs") };
  1046. # By default, create empty directories by consulting the unhandled log,
  1047. # but allow setting it to 'false' to skip it.
  1048. return !($var && $var eq 'false');
  1049. }
  1050. sub cmd_rebase {
  1051. command_noisy(qw/update-index --refresh/);
  1052. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1053. unless ($gs) {
  1054. die "Unable to determine upstream SVN information from ",
  1055. "working tree history\n";
  1056. }
  1057. if ($_dry_run) {
  1058. print "Remote Branch: " . $gs->refname . "\n";
  1059. print "SVN URL: " . $url . "\n";
  1060. return;
  1061. }
  1062. if (command(qw/diff-index HEAD --/)) {
  1063. print STDERR "Cannot rebase with uncommited changes:\n";
  1064. command_noisy('status');
  1065. exit 1;
  1066. }
  1067. unless ($_local) {
  1068. # rebase will checkout for us, so no need to do it explicitly
  1069. $_no_checkout = 'true';
  1070. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  1071. }
  1072. command_noisy(rebase_cmd(), $gs->refname);
  1073. if (auto_create_empty_directories($gs)) {
  1074. $gs->mkemptydirs;
  1075. }
  1076. }
  1077. sub cmd_show_ignore {
  1078. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1079. $gs ||= Git::SVN->new;
  1080. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1081. $gs->prop_walk($gs->{path}, $r, sub {
  1082. my ($gs, $path, $props) = @_;
  1083. print STDOUT "\n# $path\n";
  1084. my $s = $props->{'svn:ignore'} or return;
  1085. $s =~ s/[\r\n]+/\n/g;
  1086. $s =~ s/^\n+//;
  1087. chomp $s;
  1088. $s =~ s#^#$path#gm;
  1089. print STDOUT "$s\n";
  1090. });
  1091. }
  1092. sub cmd_show_externals {
  1093. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1094. $gs ||= Git::SVN->new;
  1095. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1096. $gs->prop_walk($gs->{path}, $r, sub {
  1097. my ($gs, $path, $props) = @_;
  1098. print STDOUT "\n# $path\n";
  1099. my $s = $props->{'svn:externals'} or return;
  1100. $s =~ s/[\r\n]+/\n/g;
  1101. chomp $s;
  1102. $s =~ s#^#$path#gm;
  1103. print STDOUT "$s\n";
  1104. });
  1105. }
  1106. sub cmd_create_ignore {
  1107. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1108. $gs ||= Git::SVN->new;
  1109. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1110. $gs->prop_walk($gs->{path}, $r, sub {
  1111. my ($gs, $path, $props) = @_;
  1112. # $path is of the form /path/to/dir/
  1113. $path = '.' . $path;
  1114. # SVN can have attributes on empty directories,
  1115. # which git won't track
  1116. mkpath([$path]) unless -d $path;
  1117. my $ignore = $path . '.gitignore';
  1118. my $s = $props->{'svn:ignore'} or return;
  1119. open(GITIGNORE, '>', $ignore)
  1120. or fatal("Failed to open `$ignore' for writing: $!");
  1121. $s =~ s/[\r\n]+/\n/g;
  1122. $s =~ s/^\n+//;
  1123. chomp $s;
  1124. # Prefix all patterns so that the ignore doesn't apply
  1125. # to sub-directories.
  1126. $s =~ s#^#/#gm;
  1127. print GITIGNORE "$s\n";
  1128. close(GITIGNORE)
  1129. or fatal("Failed to close `$ignore': $!");
  1130. command_noisy('add', '-f', $ignore);
  1131. });
  1132. }
  1133. sub cmd_mkdirs {
  1134. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1135. $gs ||= Git::SVN->new;
  1136. $gs->mkemptydirs($_revision);
  1137. }
  1138. sub canonicalize_path {
  1139. my ($path) = @_;
  1140. my $dot_slash_added = 0;
  1141. if (substr($path, 0, 1) ne "/") {
  1142. $path = "./" . $path;
  1143. $dot_slash_added = 1;
  1144. }
  1145. # File::Spec->canonpath doesn't collapse x/../y into y (for a
  1146. # good reason), so let's do this manually.
  1147. $path =~ s#/+#/#g;
  1148. $path =~ s#/\.(?:/|$)#/#g;
  1149. $path =~ s#/[^/]+/\.\.##g;
  1150. $path =~ s#/$##g;
  1151. $path =~ s#^\./## if $dot_slash_added;
  1152. $path =~ s#^/##;
  1153. $path =~ s#^\.$##;
  1154. return $path;
  1155. }
  1156. sub canonicalize_url {
  1157. my ($url) = @_;
  1158. $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
  1159. return $url;
  1160. }
  1161. # get_svnprops(PATH)
  1162. # ------------------
  1163. # Helper for cmd_propget and cmd_proplist below.
  1164. sub get_svnprops {
  1165. my $path = shift;
  1166. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1167. $gs ||= Git::SVN->new;
  1168. # prefix THE PATH by the sub-directory from which the user
  1169. # invoked us.
  1170. $path = $cmd_dir_prefix . $path;
  1171. fatal("No such file or directory: $path") unless -e $path;
  1172. my $is_dir = -d $path ? 1 : 0;
  1173. $path = $gs->{path} . '/' . $path;
  1174. # canonicalize the path (otherwise libsvn will abort or fail to
  1175. # find the file)
  1176. $path = canonicalize_path($path);
  1177. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1178. my $props;
  1179. if ($is_dir) {
  1180. (undef, undef, $props) = $gs->ra->get_dir($path, $r);
  1181. }
  1182. else {
  1183. (undef, $props) = $gs->ra->get_file($path, $r, undef);
  1184. }
  1185. return $props;
  1186. }
  1187. # cmd_propget (PROP, PATH)
  1188. # ------------------------
  1189. # Print the SVN property PROP for PATH.
  1190. sub cmd_propget {
  1191. my ($prop, $path) = @_;
  1192. $path = '.' if not defined $path;
  1193. usage(1) if not defined $prop;
  1194. my $props = get_svnprops($path);
  1195. if (not defined $props->{$prop}) {
  1196. fatal("`$path' does not have a `$prop' SVN property.");
  1197. }
  1198. print $props->{$prop} . "\n";
  1199. }
  1200. # cmd_proplist (PATH)
  1201. # -------------------
  1202. # Print the list of SVN properties for PATH.
  1203. sub cmd_proplist {
  1204. my $path = shift;
  1205. $path = '.' if not defined $path;
  1206. my $props = get_svnprops($path);
  1207. print "Properties on '$path':\n";
  1208. foreach (sort keys %{$props}) {
  1209. print " $_\n";
  1210. }
  1211. }
  1212. sub cmd_multi_init {
  1213. my $url = shift;
  1214. unless (defined $_trunk || @_branches || @_tags) {
  1215. usage(1);
  1216. }
  1217. $_prefix = '' unless defined $_prefix;
  1218. if (defined $url) {
  1219. $url = canonicalize_url($url);
  1220. init_subdir(@_);
  1221. }
  1222. do_git_init_db();
  1223. if (defined $_trunk) {
  1224. $_trunk =~ s#^/+##;
  1225. my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
  1226. # try both old-style and new-style lookups:
  1227. my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
  1228. unless ($gs_trunk) {
  1229. my ($trunk_url, $trunk_path) =
  1230. complete_svn_url($url, $_trunk);
  1231. $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
  1232. undef, $trunk_ref);
  1233. }
  1234. }
  1235. return unless @_branches || @_tags;
  1236. my $ra = $url ? Git::SVN::Ra->new($url) : undef;
  1237. foreach my $path (@_branches) {
  1238. complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
  1239. }
  1240. foreach my $path (@_tags) {
  1241. complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
  1242. }
  1243. }
  1244. sub cmd_multi_fetch {
  1245. $Git::SVN::no_reuse_existing = undef;
  1246. my $remotes = Git::SVN::read_all_remotes();
  1247. foreach my $repo_id (sort keys %$remotes) {
  1248. if ($remotes->{$repo_id}->{url}) {
  1249. Git::SVN::fetch_all($repo_id, $remotes);
  1250. }
  1251. }
  1252. }
  1253. # this command is special because it requires no metadata
  1254. sub cmd_commit_diff {
  1255. my ($ta, $tb, $url) = @_;
  1256. my $usage = "Usage: $0 commit-diff -r<revision> ".
  1257. "<tree-ish> <tree-ish> [<URL>]";
  1258. fatal($usage) if (!defined $ta || !defined $tb);
  1259. my $svn_path = '';
  1260. if (!defined $url) {
  1261. my $gs = eval { Git::SVN->new };
  1262. if (!$gs) {
  1263. fatal("Needed URL or usable git-svn --id in ",
  1264. "the command-line\n", $usage);
  1265. }
  1266. $url = $gs->{url};
  1267. $svn_path = $gs->{path};
  1268. }
  1269. unless (defined $_revision) {
  1270. fatal("-r|--revision is a required argument\n", $usage);
  1271. }
  1272. if (defined $_message && defined $_file) {
  1273. fatal("Both --message/-m and --file/-F specified ",
  1274. "for the commit message.\n",
  1275. "I have no idea what you mean");
  1276. }
  1277. if (defined $_file) {
  1278. $_message = file_to_s($_file);
  1279. } else {
  1280. $_message ||= get_commit_entry($tb)->{log};
  1281. }
  1282. my $ra ||= Git::SVN::Ra->new($url);
  1283. my $r = $_revision;
  1284. if ($r eq 'HEAD') {
  1285. $r = $ra->get_latest_revnum;
  1286. } elsif ($r !~ /^\d+$/) {
  1287. die "revision argument: $r not understood by git-svn\n";
  1288. }
  1289. my %ed_opts = ( r => $r,
  1290. log => $_message,
  1291. ra => $ra,
  1292. tree_a => $ta,
  1293. tree_b => $tb,
  1294. editor_cb => sub { print "Committed r$_[0]\n" },
  1295. svn_path => $svn_path );
  1296. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  1297. print "No changes\n$ta == $tb\n";
  1298. }
  1299. }
  1300. sub escape_uri_only {
  1301. my ($uri) = @_;
  1302. my @tmp;
  1303. foreach (split m{/}, $uri) {
  1304. s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
  1305. push @tmp, $_;
  1306. }
  1307. join('/', @tmp);
  1308. }
  1309. sub escape_url {
  1310. my ($url) = @_;
  1311. if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
  1312. my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
  1313. $url = "$scheme://$domain$uri";
  1314. }
  1315. $url;
  1316. }
  1317. sub cmd_info {
  1318. my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
  1319. my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
  1320. if (exists $_[1]) {
  1321. die "Too many arguments specified\n";
  1322. }
  1323. my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
  1324. if (!$file_type && !$diff_status) {
  1325. print STDERR "svn: '$path' is not under version control\n";
  1326. exit 1;
  1327. }
  1328. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1329. unless ($gs) {
  1330. die "Unable to determine upstream SVN information from ",
  1331. "working tree history\n";
  1332. }
  1333. # canonicalize_path() will return "" to make libsvn 1.5.x happy,
  1334. $path = "." if $path eq "";
  1335. my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
  1336. if ($_url) {
  1337. print escape_url($full_url), "\n";
  1338. return;
  1339. }
  1340. my $result = "Path: $path\n";
  1341. $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
  1342. $result .= "URL: " . escape_url($full_url) . "\n";
  1343. eval {
  1344. my $repos_root = $gs->repos_root;
  1345. Git::SVN::remove_username($repos_root);
  1346. $result .= "Repository Root: " . escape_url($repos_root) . "\n";
  1347. };
  1348. if ($@) {
  1349. $result .= "Repository Root: (offline)\n";
  1350. }
  1351. ::_req_svn();
  1352. $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
  1353. ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
  1354. $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
  1355. $result .= "Node Kind: " .
  1356. ($file_type eq "dir" ? "directory" : "file") . "\n";
  1357. my $schedule = $diff_status eq "A"
  1358. ? "add"
  1359. : ($diff_status eq "D" ? "delete" : "normal");
  1360. $result .= "Schedule: $schedule\n";
  1361. if ($diff_status eq "A") {
  1362. print $result, "\n";
  1363. return;
  1364. }
  1365. my ($lc_author, $lc_rev, $lc_date_utc);
  1366. my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
  1367. my $log = command_output_pipe(@args);
  1368. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  1369. while (<$log>) {
  1370. if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
  1371. $lc_author = $1;
  1372. $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
  1373. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  1374. (undef, $lc_rev, undef) = ::extract_metadata($1);
  1375. }
  1376. }
  1377. close $log;
  1378. Git::SVN::Log::set_local_timezone();
  1379. $result .= "Last Changed Author: $lc_author\n";
  1380. $result .= "Last Changed Rev: $lc_rev\n";
  1381. $result .= "Last Changed Date: " .
  1382. Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
  1383. if ($file_type ne "dir") {
  1384. my $text_last_updated_date =
  1385. ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
  1386. $result .=
  1387. "Text Last Updated: " .
  1388. Git::SVN::Log::format_svn_date($text_last_updated_date) .
  1389. "\n";
  1390. my $checksum;
  1391. if ($diff_status eq "D") {
  1392. my ($fh, $ctx) =
  1393. command_output_pipe(qw(cat-file blob), "HEAD:$path");
  1394. if ($file_type eq "link") {
  1395. my $file_name = <$fh>;
  1396. $checksum = md5sum("link $file_name");
  1397. } else {
  1398. $checksum = md5sum($fh);
  1399. }
  1400. command_close_pipe($fh, $ctx);
  1401. } elsif ($file_type eq "link") {
  1402. my $file_name =
  1403. command(qw(cat-file blob), "HEAD:$path");
  1404. $checksum =
  1405. md5sum("link " . $file_name);
  1406. } else {
  1407. open FILE, "<", $path or die $!;
  1408. $checksum = md5sum(\*FILE);
  1409. close FILE or die $!;
  1410. }
  1411. $result .= "Checksum: " . $checksum . "\n";
  1412. }
  1413. print $result, "\n";
  1414. }
  1415. sub cmd_reset {
  1416. my $target = shift || $_revision or die "SVN revision required\n";
  1417. $target = $1 if $target =~ /^r(\d+)$/;
  1418. $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
  1419. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1420. unless ($gs) {
  1421. die "Unable to determine upstream SVN information from ".
  1422. "history\n";
  1423. }
  1424. my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
  1425. die "Cannot find SVN revision $target\n" unless defined($c);
  1426. $gs->rev_map_set($r, $c, 'reset', $uuid);
  1427. print "r$r = $c ($gs->{ref_id})\n";
  1428. }
  1429. sub cmd_gc {
  1430. if (!$can_compress) {
  1431. warn "Compress::Zlib could not be found; unhandled.log " .
  1432. "files will not be compressed.\n";
  1433. }
  1434. find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
  1435. }
  1436. ########################### utility functions #########################
  1437. sub rebase_cmd {
  1438. my @cmd = qw/rebase/;
  1439. push @cmd, '-v' if $_verbose;
  1440. push @cmd, qw/--merge/ if $_merge;
  1441. push @cmd, "--strategy=$_strategy" if $_strategy;
  1442. @cmd;
  1443. }
  1444. sub post_fetch_checkout {
  1445. return if $_no_checkout;
  1446. my $gs = $Git::SVN::_head or return;
  1447. return if verify_ref('refs/heads/master^0');
  1448. # look for "trunk" ref if it exists
  1449. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1450. my $fetch = $remote->{fetch};
  1451. if ($fetch) {
  1452. foreach my $p (keys %$fetch) {
  1453. basename($fetch->{$p}) eq 'trunk' or next;
  1454. $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
  1455. last;
  1456. }
  1457. }
  1458. my $valid_head = verify_ref('HEAD^0');
  1459. command_noisy(qw(update-ref refs/heads/master), $gs->refname);
  1460. return if ($valid_head || !verify_ref('HEAD^0'));
  1461. return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
  1462. my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
  1463. return if -f $index;
  1464. return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
  1465. return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
  1466. command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
  1467. print STDERR "Checked out HEAD:\n ",
  1468. $gs->full_url, " r", $gs->last_rev, "\n";
  1469. if (auto_create_empty_directories($gs)) {
  1470. $gs->mkemptydirs($gs->last_rev);
  1471. }
  1472. }
  1473. sub complete_svn_url {
  1474. my ($url, $path) = @_;
  1475. $path =~ s#/+$##;
  1476. if ($path !~ m#^[a-z\+]+://#) {
  1477. if (!defined $url || $url !~ m#^[a-z\+]+://#) {
  1478. fatal("E: '$path' is not a complete URL ",
  1479. "and a separate URL is not specified");
  1480. }
  1481. return ($url, $path);
  1482. }
  1483. return ($path, '');
  1484. }
  1485. sub complete_url_ls_init {
  1486. my ($ra, $repo_path, $switch, $pfx) = @_;
  1487. unless ($repo_path) {
  1488. print STDERR "W: $switch not specified\n";
  1489. return;
  1490. }
  1491. $repo_path =~ s#/+$##;
  1492. if ($repo_path =~ m#^[a-z\+]+://#) {
  1493. $ra = Git::SVN::Ra->new($repo_path);
  1494. $repo_path = '';
  1495. } else {
  1496. $repo_path =~ s#^/+##;
  1497. unless ($ra) {
  1498. fatal("E: '$repo_path' is not a complete URL ",
  1499. "and a separate URL is not specified");
  1500. }
  1501. }
  1502. my $url = $ra->{url};
  1503. my $gs = Git::SVN->init($url, undef, undef, undef, 1);
  1504. my $k = "svn-remote.$gs->{repo_id}.url";
  1505. my $orig_url = eval { command_oneline(qw/config --get/, $k) };
  1506. if ($orig_url && ($orig_url ne $gs->{url})) {
  1507. die "$k already set: $orig_url\n",
  1508. "wanted to set to: $gs->{url}\n";
  1509. }
  1510. command_oneline('config', $k, $gs->{url}) unless $orig_url;
  1511. my $remote_path = "$gs->{path}/$repo_path";
  1512. $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1513. $remote_path =~ s#/+#/#g;
  1514. $remote_path =~ s#^/##g;
  1515. $remote_path .= "/*" if $remote_path !~ /\*/;
  1516. my ($n) = ($switch =~ /^--(\w+)/);
  1517. if (length $pfx && $pfx !~ m#/$#) {
  1518. die "--prefix='$pfx' must have a trailing slash '/'\n";
  1519. }
  1520. command_noisy('config',
  1521. '--add',
  1522. "svn-remote.$gs->{repo_id}.$n",
  1523. "$remote_path:refs/remotes/$pfx*" .
  1524. ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
  1525. }
  1526. sub verify_ref {
  1527. my ($ref) = @_;
  1528. eval { command_oneline([ 'rev-parse', '--verify', $ref ],
  1529. { STDERR => 0 }); };
  1530. }
  1531. sub get_tree_from_treeish {
  1532. my ($treeish) = @_;
  1533. # $treeish can be a symbolic ref, too:
  1534. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1535. my $expected;
  1536. while ($type eq 'tag') {
  1537. ($treeish, $type) = command(qw/cat-file tag/, $treeish);
  1538. }
  1539. if ($type eq 'commit') {
  1540. $expected = (grep /^tree /, command(qw/cat-file commit/,
  1541. $treeish))[0];
  1542. ($expected) = ($expected =~ /^tree ($sha1)$/o);
  1543. die "Unable to get tree from $treeish\n" unless $expected;
  1544. } elsif ($type eq 'tree') {
  1545. $expected = $treeish;
  1546. } else {
  1547. die "$treeish is a $type, expected tree, tag or commit\n";
  1548. }
  1549. return $expected;
  1550. }
  1551. sub get_commit_entry {
  1552. my ($treeish) = shift;
  1553. my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
  1554. my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
  1555. my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
  1556. open my $log_fh, '>', $commit_editmsg or croak $!;
  1557. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1558. if ($type eq 'commit' || $type eq 'tag') {
  1559. my ($msg_fh, $ctx) = command_output_pipe('ca…

Large files files are truncated, but you can click here to view the full file