PageRenderTime 73ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

/git/git-svn.perl

https://review.tizen.org/git/
Perl | 6213 lines | 5519 code | 414 blank | 280 comment | 780 complexity | 674221d6d3d9cdf47333b1897f2da209 MD5 | raw file
Possible License(s): GPL-3.0, AGPL-3.0, GPL-2.0, MPL-2.0, JSON, WTFPL, CC-BY-SA-4.0, CC-BY-3.0, BSD-3-Clause, LGPL-2.0, MPL-2.0-no-copyleft-exception, AGPL-1.0, 0BSD, Zlib, Unlicense, BSD-2-Clause, Apache-2.0, LGPL-3.0, ISC, MIT, CC-BY-SA-3.0, CC0-1.0, LGPL-2.1

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

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