chiark / gitweb /
Implement -EE (copy-edit-all)
[nailing-cargo.git] / nailing-cargo
1 #!/usr/bin/perl -w
2 # nailing-cargo: wrapper to use unpublished local crates
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4 our $usage = <<'END';
5
6 usages:
7
8   nailing-cargo <nailing-opts> <cargo-opts> [--] <subcmd>...
9   nailing-cargo <nailing-opts> --- <cargo> <cargo-opts> [--] <subcmd>...
10   nailing-cargo <nailing-opts> --- [--] <build-command>...
11
12 options:
13
14   -v  Increase verbosity.  (Default is 1)
15   -q  Set verbosity to 0
16   -D  Increase amount of debugging dump.
17   -n  "No action": stop after writing Cargo.toml.nailing~
18       everywhere, and do not run any build command
19
20   -c  Do add cargo command line options      } default is add if
21   -C  Do not add cargo command line options  }  command is cargo
22
23   -o --online                     -O --offline
24   -u --cargo-lock-update          -U --no-cargo-lock-update
25
26   -T<arch>  --target=<arch>       Specify target architecture
27   -h --help                       Print this message
28   --doc --man --manual            Display complete manual (in w3m)
29   --leave-nailed                  Leave the nailed Cargo.toml in place
30   -E | --edits-sources            Allow source edits (repeat: file creation)
31   --linkfarm[=no|shallow|git|full]        (default varies, usually "no")
32   --just-linkfarm | --clean-linkfarm | --keep-linkfarm (default is keep)
33   --[no-]preclean-build[=no|src|full]               (default is no)
34   --just-run                      Run the command, don't do cargo stuff
35   --no-nail                       Do not nail, just run the command.
36   --no-cargo-lock-manip           Do not manipulate Cargo.lock.
37   --no-concurrency-lock           Do not take the concurrency lock.
38
39   -s<subcommand>                  Treat command as `cargo <subcommand>`
40   --subcommand-props=<prop>,...   Override command props (see docs)
41
42 END
43
44 our $self;
45
46 use strict;
47 use POSIX;
48 use Types::Serialiser;
49 use File::Glob qw(bsd_glob GLOB_ERR GLOB_BRACE GLOB_NOMAGIC);
50 use Cwd qw(realpath);
51
52 our $base_path;
53 our %archmap = (
54     RPI => 'arm-unknown-linux-gnueabihf',
55     WASM => 'wasm32-unknown-unknown',
56 );
57
58 BEGIN {
59   $self = $0;  $self =~ s{^.*/(?=.)}{};
60   my $deref = $0;
61   our $base_path;
62   while ($deref =~ m{^/}) {
63     my $link = readlink $deref;
64     if (!defined $link) {
65       $! == EINVAL
66         or die "$self: checking our script location $deref: $!\n";
67       $deref =~ s{/[^/]+$}{}
68         or die "$self: unexpected script path: $deref\n";
69       $base_path = $deref;
70       unshift @INC, $deref."/TOML-Tiny/lib";
71       last;
72     }
73     last if $link !~ m{^/};
74     $deref = $link;
75   }
76 }
77
78 use Fcntl qw(LOCK_EX);
79 use File::Compare;
80 use TOML::Tiny::Faithful;
81
82 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
83
84 our $worksphere = $src_absdir;
85 $worksphere =~ s{/([^/]+)$}{}
86   or die "$self: cwd \`$worksphere' unsupported!\n";
87 our $subdir = $1; # leafname
88
89 our $lockfile = "../.nailing-cargo.lock";
90
91 our @args_preface;
92 our $cargo_subcmd;
93 our $command_is_cargo;
94 our $alt_cargo_lock;
95 our $cargo_lock_update;
96 our $pass_options;
97 our $online;
98 our $just_linkfarm;
99 our $leave_nailed;
100 our $oot_clean;
101 our $oot_preclean;
102 our $do_nail=1;
103 our $do_cargo_lock=1;
104 our $do_lock=1;
105 our $linkfarm_depth;
106
107 #
108 our %subcmd_props = (
109 # build (default)  =>[qw(                                                )],
110 'generate-lockfile'=>[qw( lock-update !target          !target-dir       )],
111  update            =>[qw( lock-update !target online                     )],
112  fetch             =>[qw(                     online   !target-dir       )],
113  fmt               =>[qw( !locked     !target !offline !target-dir edits )],
114  miri              =>[qw( !locked             !offline  linkfarm-shallow )],
115  publish           =>[qw(                     !offline  linkfarm-gitclean )],
116  upgrades          =>[qw( !locked                      !target-dir       )],
117                     );
118
119 our @subcmd_xprops = qw(!manifest-path);
120
121 our @configs;
122 our $verbose=1;
123 our ($noact,$dump);
124 our $target;
125
126 sub print_usage () {
127   print $usage or die $!;
128   exit 0;
129 }
130
131 sub show_manual () {
132   my $manual = ($base_path // '.').'/README.md';
133   stat $manual or die "$self: manual not found at $manual: $!\n";;
134   exec 'sh','-ec', 'pandoc -- "$1" 2>&1 | w3m -T text/html', '--', $manual;
135   die "$self: exec sh failed: $!";
136 }
137
138 sub read_or_enoent ($) {
139   my ($fn) = @_;
140   if (!open R, '<', $fn) {
141     return undef if $!==ENOENT;
142     die "$self: open $fn: $!\n";
143   }
144   local ($/) = undef;
145   my ($r) = <R> // die "$self: read $fn: $!\n";
146   $r;
147 }
148
149 sub stat_exists ($$) {
150   my ($fn, $what) = @_;
151   if (stat $fn) { return 1; }
152   $!==ENOENT or die "$self: stat $what: $fn: $!\n";
153   return 0;
154 }
155
156 sub subcmd_p ($) {
157   print STDERR " subcmd_p ".(join ' ', keys %$cargo_subcmd)."   | @_\n"
158     if $dump;
159   $cargo_subcmd->{$_[0]}
160 }
161
162 sub toml_or_enoent ($$) {
163   my ($f,$what) = @_;
164   my $toml = read_or_enoent($f) // return;
165   print STDERR "Read TOML from $f\n" if $dump;
166   my ($v,$e) = from_toml($toml);
167   if (!defined $v) {
168     chomp $e;
169     die "$self: parse TOML: $what: $f: $e\n";
170   }
171   die "$e ?" if length $e;
172   $v;
173 }
174
175 sub load1config ($) {
176   my ($f) = @_;
177   my $toml = toml_or_enoent($f, "config file");
178   push @configs, $toml if defined $toml;
179 }
180
181 sub loadconfigs () {
182   my $dotfile = ".nailing-cargo.toml";
183   load1config("../Nailing-Cargo.toml");
184   load1config($dotfile);
185   load1config("$ENV{HOME}/$dotfile") if defined $ENV{HOME};
186   load1config("/etc/nailing-cargo/cfg.toml");
187 }
188
189 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
190
191 sub same_file ($$) {
192   my ($x,$y) = @_;
193   "@$x[0..5]" eq "@$y[0..5]";
194 }
195
196 sub takelock () {
197   return unless $do_lock;
198
199   for (;;) {
200     open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
201     flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
202     my @fstat = stat LOCK or die "$self: fstat: $!\n";
203     my @stat  = stat $lockfile;
204     if (!@stat) {
205       next if $! == ENOENT;
206       die "$self: stat $lockfile: $!\n";
207     }
208     last if same_file(\@fstat,\@stat);
209   }
210 }
211 sub unlock () {
212   unlink $lockfile or die "$self: removing lockfile: $!\n";
213 }
214
215 our $nail;
216
217 sub badcfg {
218   my $m = pop @_;
219   $" = '.';
220   die "$self: config key \`@_': $m\n";
221 }
222
223 sub cfg_uc {
224   foreach my $cfg (@configs) {
225     my $v = $cfg;
226     foreach my $k (@_) {
227       last unless defined $v;
228       ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
229       $v = $v->{$k};
230     }
231     return $v if defined $v;
232   }
233   return undef;
234 }
235
236 sub cfge {
237   my $exp = shift @_;
238   my $v = cfg_uc @_;
239   my $got = ref($v) || 'scalar';
240   return $v if !defined($v) || $got eq $exp;
241   badcfg @_, "found \L$got\E, expected \L$exp\E";
242   # ^ toml doesn't make refs to scalars, so this is unambiguous
243 }
244
245 sub cfgn {
246   my $exp = shift @_;
247   (cfge $exp, @_) // badcfg @_, "missing";
248 }
249
250 sub cfgs  { cfge 'scalar', @_ }
251 sub cfgsn { cfgn 'scalar', @_ }
252
253 sub cfg_bool {
254   my $v = cfg_uc @_;
255   return $v if !defined($v) || Types::Serialiser::is_bool $v;
256   badcfg @_, "expected boolean";
257 }
258
259 sub cfgn_list {
260   my $l = cfge 'ARRAY', @_;
261   foreach my $x (@$l) {
262     !ref $x or badcfg @_, "list contains non-scalar element";
263   }
264   @$l
265 }
266
267 sub readnail () {
268   my $nailfile = "../Cargo.nail";
269   open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
270   local ($/) = undef;
271   my $toml = <N> // die "$self: read $nailfile: $!";
272   my $transformed;
273   if ($toml !~ m{^\s*\[/}m &&
274       $toml !~ m{^[^\n\#]*\=}m &&
275       # old non-toml syntax
276       $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
277     $toml =~ s{^}{[packages\]\n};
278     my @sd;
279     $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
280       push @sd, $1; '';
281     }mige;
282     $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
283     $transformed = 1;
284   }
285   my $e;
286   ($nail,$e) = from_toml($toml);
287   if (!defined $nail) {
288     if ($transformed) {
289       $toml =~ s/^/    /mg;
290       print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
291     }
292     $/="\n"; chomp $e;
293     die "$self: parse $nailfile: $e\n";
294   }
295   die "$e ?" if length $e;
296
297   $nail->{subdirs} //= [ ];
298
299   if (!ref $nail->{subdirs}) {
300     $nail->{subdirs} = [
301       grep /^[^\#]/,
302       map { s/^\s+//; s/\s+$//; $_; }
303       split m{\n},
304       $nail->{subdirs}
305     ];
306   }
307
308   unshift @configs, $nail;
309 }
310
311 sub get_dependency_tables ($) {
312   my ($toml) = @_;
313   my @keys = qw(dependencies build-dependencies dev-dependencies);
314   my @r;
315   my $process = sub {
316     my ($node) = @_;
317     foreach my $k (@keys) {
318       my $deps = $node->{$k};
319       push @r, $deps if $deps;
320     }
321   };
322   $process->($toml);
323   foreach my $target_node (values %{ $toml->{target} // { } }) {
324     $process->($target_node);
325   }
326   @r;
327 }
328
329 our @alt_cargo_lock_stat;
330
331 sub consider_alt_cargo_lock () {
332   my @ck = qw(alt_cargo_lock);
333   # User should *either* have Cargo.lock in .gitignore,
334   # or expect to commit Cargo.lock.example ($alt_cargo_lock)
335
336   return unless $do_cargo_lock;
337
338   $alt_cargo_lock = (cfg_uc @ck);
339
340   my $force = 0;
341   if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
342     $force = cfg_bool qw(alt_cargo_lock force);
343     my @ck = qw(alt_cargo_lock file);
344     $alt_cargo_lock = cfg_uc @ck;
345   }
346   $alt_cargo_lock //= Types::Serialiser::true;
347
348   if (Types::Serialiser::is_bool $alt_cargo_lock) {
349     if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
350     $alt_cargo_lock = 'Cargo.lock.example';
351   }
352
353   if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
354     badcfg @ck, "expected boolean, or leafname";
355   }
356
357   if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
358     $alt_cargo_lock = undef unless $force;
359     return;
360   }
361   
362   @alt_cargo_lock_stat = stat _;
363 }
364
365 our $oot_dir;      # oot.dir or "Build"
366 our $oot_absdir;
367
368 sub consider_oot () {
369   $oot_dir = cfgs qw(oot dir);
370   my $use = cfgs qw(oot use);
371   unless (defined($oot_dir) || defined($use) ||
372           defined(cfg_uc qw(oot user))) {
373     return;
374   }
375   if (($use//'') eq 'disable') {
376     $oot_dir = undef;
377     return;
378   }
379   $oot_clean //= cfg_bool qw(oot clean);
380   $oot_dir //= 'Build';
381   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
382 }
383
384 our %manifests;
385 our %packagemap;
386 our %workspaces;
387 our @queued_paths;
388
389 sub read_manifest ($$$) {
390   my ($subdir, $org_subdir, $why) = @_;
391   my $manifest = "../$subdir/Cargo.toml";
392   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
393   if (defined $manifests{$manifest}) {
394     print STDERR
395  "$self: warning: $subdir: specified more than once!".
396  " (ignoring $why)\n";
397     return undef;
398   }
399   foreach my $try ("$manifest.unnailed", "$manifest") {
400     my $toml = toml_or_enoent($try, "manifest, in $why") // next;
401     my $ws = $toml->{workspace};
402     if ($ws) {
403       queue_workspace_members($subdir, $org_subdir, $ws, "$subdir, $why");
404     }
405     my $p = $toml->{package}{name};
406     if (!defined $p and !defined $ws) {
407       print STDERR
408  "$self: warning: $subdir, $why: missing package.name in $try, ignoring\n";
409       next;
410     }
411     $manifests{$manifest} = [ $toml, $org_subdir ] if $p;
412     foreach my $dep (get_dependency_tables $toml) {
413       next unless defined $dep->{path};
414       queue_referenced_path($dep->{path}, $org_subdir,
415                             "dependency of $subdir, $why");
416     }
417     return ($p, $ws);
418   }
419   return undef;
420 }
421
422 sub queue_workspace_members ($$) {
423   my ($subdir, $org_subdir, $ws_toml, $what) = @_;
424   # We need to (more or less) reimplement the cargo workspace
425   # membership algorithm (see the "workspaces" section of the cargo
426   # reference).  How tiresome.
427   #
428   # It's not quite the same for us because we aren't interested in
429   # whether cargo thinks things are "in the workspace".  But we do
430   # need to do the automatic discover.
431
432   my @include = @{ $ws_toml->{members} // [ ] };
433   my $exclude = $ws_toml->{exclude} // [ ];
434
435   my @exclude = map {
436     s/[^*?0-9a-zA-Z_]/\\$&/g;
437     s/\?/./g;
438     s/\*/.*/g;
439   } @$exclude;
440
441   foreach my $spec (@include) {
442     if ($spec =~ m{^/}) {
443       print STDERR
444         "$self: warning: absolute workspace member $spec in $what (not nailing, but cargo will probably use it)\n";
445       next;
446     }
447     my $spec_glob = "../$subdir/$spec";
448     my $globflags = GLOB_ERR|GLOB_BRACE|GLOB_NOMAGIC;
449     foreach my $globent (bsd_glob($spec_glob, $globflags)) {
450       next if grep { $globent =~ m{^$_$} } @exclude;
451       queue_referenced_path($globent, $org_subdir,
452                             "member of workspace $what");
453     }
454   }
455 }
456
457 sub queue_referenced_path ($$$) {
458   my ($spec_path, $org_subdir, $why) = @_;
459   open REALPATH, "-|",
460     qw(realpath), "--relative-to=../$org_subdir", "--", $spec_path
461     or die "$self: fork/pipe/exec for realpath(1)\n";
462   my $rel_path = do { local $/=undef; <REALPATH>; };
463   $?=0; $!=0;
464   my $r = close(REALPATH);
465   die "$self: reap realpath: $!\n" if $!;
466   if (!chomp($rel_path) or $?) {
467     print STDERR
468  "$self: warning: failed to determine realpath for $spec_path in $org_subdir (exit code $?)\n";
469     return;
470   }
471   if ($rel_path =~ m{^\.\./} or $rel_path eq '..') {
472     print STDERR
473       "$self: warning: $spec_path ($why) points outside $org_subdir, not following so not nailing (although cargo probably will follow it)\n";
474     return;
475   }
476
477   my $q_subdir = "$org_subdir/$rel_path";
478   print STDERR "$self: making a note to look at $q_subdir, $why)\n"
479     if $verbose >= 4;
480
481   push @queued_paths, [ "$q_subdir", $org_subdir, $why ];
482 }
483
484 sub readorigs () {
485   # We (and our callees) populate %packagemap and %manifest, so if we
486   # don't run, they remain empty and nothing is nailed.
487   return unless $do_nail;
488
489   foreach my $p (keys %{ $nail->{packages} }) {
490     my $v = $nail->{packages}{$p};
491     my $subdir = ref($v) ? $v->{subdir} : $v;
492     my ($gotpackage, $ws) = read_manifest($subdir, $subdir, "from [packages]");
493     $gotpackage //= '<nothing!>';
494     if ($gotpackage ne $p) {
495       print STDERR
496  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
497     }
498     die if defined $packagemap{$p};
499     $packagemap{$p} = [ $subdir, $subdir ];
500   }
501   foreach my $subdir (@{ $nail->{subdirs} }) {
502     my ($gotpackage,$ws) = read_manifest($subdir, $subdir, "from [subdirs]");
503     if (!defined $gotpackage) {
504       print STDERR
505  "$self: warning: ignoring subdir $subdir which has no (suitable) Cargo.toml\n"
506         unless $ws;
507       next;
508     }
509     $packagemap{$gotpackage} //= [ $subdir, $subdir ];
510   }
511   while (my ($subdir, $org_subdir, $why) = @{ shift @queued_paths or [] }) {
512     next if $manifests{"../$subdir/Cargo.toml"};
513     my ($gotpackage, $ws) = read_manifest($subdir, $org_subdir, $why);
514     next unless $gotpackage;
515     $packagemap{$gotpackage} //= [ $subdir, $org_subdir ];
516   }
517 }
518
519 sub calculate () {
520   foreach my $p (sort keys %packagemap) {
521     print STDERR "$self: package $p in $packagemap{$p}[0]\n" if $verbose>=2;
522   }
523   foreach my $mf (keys %manifests) {
524     die "internal error" unless $do_nail; # belt and braces
525
526     my ($toml, $mf_org_subdir) = @{ $manifests{$mf} };
527     foreach my $deps (get_dependency_tables $toml) {
528       next unless $deps;
529       foreach my $p (keys %packagemap) {
530         my $info = $deps->{$p};
531         next unless defined $info;
532         next if $packagemap{$p}[1] eq $mf_org_subdir;
533         $deps->{$p} = $info = { } unless ref $info;
534         my $oldpath = $info->{path};
535         delete $info->{version};
536         my $newpath = $worksphere.'/'.$packagemap{$p}[0];
537         print STDERR "in $mf set $p path=$newpath (was ".
538           ($oldpath // '<unset>').")\n"
539           if $verbose >= 4;
540         $info->{path} = $newpath;
541         delete $info->{git};
542         delete $info->{branch};
543       }
544     }
545     my $nailing = "$mf.nailing~";
546     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
547     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
548     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
549     close N or die "$self: close new $nailing: $!\n";
550   }
551 }
552
553 sub addargs () {
554   if ($just_linkfarm) {
555     die "$self: --just-linkfarm but not doing out-of-tree builds!\n"
556       unless defined $oot_dir;
557     @ARGV = ();
558     return;
559   }
560
561   if (!defined $online) {
562     $_ = cfg_uc qw(misc online);
563     if (!defined $_) {
564     } elsif (Types::Serialiser::is_bool $_) {
565       $online = $_;
566     } elsif (ref $_) {
567     } elsif (m/^a/) {
568       $online = undef;
569     } elsif (m/^[1ty]/) { # allow booleanish strings
570       $online = 1;        # for less user frustration
571     } elsif (m/^[0fn]/) {
572       $online = 0;
573     } else {
574       badcfg qw(misc online), "expected boolean or 'auto', found '$_'";
575     }
576   }
577   $online //= 1 if subcmd_p('online');
578   $online //= 0;
579
580   if ($linkfarm_depth eq 'copy-edit-all') {
581     $oot_preclean //= 'src';
582     if ($oot_preclean !~ m/^(?:src|full)$/) {
583       print STDERR
584  "$self: *WARNING*: -EE specified, but also --preclean=no; will probably leave your source tree full of junk\n";
585     }
586   }
587
588   if (subcmd_p('linkfarm-gitclean')) {
589     $linkfarm_depth //= 'git';
590     $oot_preclean //= 'src';
591   }
592
593   $cargo_lock_update //= subcmd_p('lock-update');
594   $linkfarm_depth //=
595     subcmd_p('linkfarm-shallow') ? 'shallow' :
596     $cargo_lock_update           ? 'shallow' :
597     '';
598
599   $oot_preclean //= 'no';
600
601   our @add;
602
603   if (!$cargo_lock_update) {
604     push @add, qw(--locked) unless subcmd_p('!locked');
605   }
606   if ($linkfarm_depth eq '') {
607     if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
608       my $cargotoml = "${src_absdir}/Cargo.toml";
609       push @args_preface, "--manifest-path=$cargotoml" if $pass_options;
610       push @add, qw(--target-dir=target) unless subcmd_p('!target-dir');
611     }
612   }
613
614   if (defined($target) && !subcmd_p('!target')) {
615     if ($target =~ m{^[A-Z]}) {
616       $target = (cfgs 'arch', $target) // $archmap{$target}
617         // die "$self: --target=$target alias specified; not in cfg or map\n";
618     }
619     push @add, "--target=$target";
620   }
621
622   push @add, "--offline" unless $online || subcmd_p('!offline');
623
624   if (subcmd_p('creates') && $linkfarm_depth !~ m/^copy-edit-all/) {
625     print STDERR
626  "$self: *WARNING*: this subcommand expects to create new source files; you probably want to specify --edits-sources twice aka -EE (which is not the default even now, for safety reasons)\n";
627   } elsif (subcmd_p('edits') && $linkfarm_depth !~ m/^copy-edit/) {
628     print STDERR
629  "$self: *WARNING*: this subcommand expects to edit the source code; you probably want to specify --edits-sources aka -E (which is not the default even now, for safety reasons)\n";
630   }
631
632   push @args_preface, @add if $pass_options;
633   die if grep { m/ / } @add;
634   $ENV{NAILINGCARGO_CARGO_OPTIONS} = "@add";
635
636   unshift @ARGV, @args_preface;
637 }
638
639 our $build_absdir; # .../Build/<subdir>
640
641 sub oot_massage_cmdline () {
642   return unless defined $oot_dir;
643
644   my $use = cfgs qw(oot use);
645   $use // die "$self: out-of-tree build, but \`oot.use' not configured\n";
646   $build_absdir = "$oot_absdir/$subdir";
647
648   my ($pre,$post) = ('','');
649   my @xargs;
650   if ($linkfarm_depth eq '') {
651     push @xargs, $build_absdir;
652     ($pre, $post) = ('cd "$1"; shift; ', '');
653   } else {
654     push @xargs, $oot_absdir, $subdir, $src_absdir;
655     $pre = <<'END_BOTH';
656         bld="$1"; shift; sd="$1"; shift; src="$1"; shift;  
657         cd "$bld"; mkdir -p -- "$sd"; cd "$sd";
658 END_BOTH
659     if ($oot_preclean ne 'no') {
660       $pre.= "find . -maxdepth 1 ! -path .";
661       $pre.= " ! -path ./target" if $oot_preclean ne 'full';
662       $pre.= " -print0 | xargs -0r rm -r --;"
663     }
664     if ($linkfarm_depth eq 'shallow') {
665       $pre.= <<'END_SHALLOW';
666         clean () { find -lname "$src/*" -print0 | xargs -0r rm --; }; clean;
667         find "$src" -maxdepth 1 \! -name Cargo.lock -print0 |
668         xargs -0r sh -ec 'for f in "$@"; do
669                 rm -rf "${f##*/}";
670                 ln -sf -- "$f" .;
671         done';
672 END_SHALLOW
673     } elsif ($linkfarm_depth =~ /full|git/) {
674       $pre .= <<'END_EITHER_DEEP_DIRS';
675         clean () { find -follow -lname "$src/*" -print0 | xargs -0r rm --; };
676         (set -e; cd "$src"; find . \! -name Cargo.lock \! \( -name .git -prune \) \! -path . \! -name .git -type d -print0) |
677         xargs -0r sh -ec 'for f in "$@"; do
678                 rm -f "$f" 2>/dev/null ||:;
679                 mkdir -p "$f";
680         done' x;
681 END_EITHER_DEEP_DIRS
682       if ($linkfarm_depth eq 'git') {
683         $pre .= <<'END_FILES_GIT'
684         (set -e; cd "$src"; git ls-files --exclude-standard -co -z) |
685 END_FILES_GIT
686       } elsif ($linkfarm_depth eq 'full') {
687         $pre .= <<'END_FILES_FULL'
688         (set -e; cd "$src"; find . \! -name Cargo.lock \! \( -name .git -prune \) \! -type d -print0) |
689 END_FILES_FULL
690       }
691       $pre .= <<'END_DEEP';
692         perl -0 -ne '
693                 BEGIN { $src=shift @ARGV; }
694                 next if (readlink "$_"//"") eq "$src/$_";
695                 unlink "$_";
696                 symlink "$src/$_", "$_" or die "$_ $!";
697         ' "$src";
698 END_DEEP
699     } elsif ($linkfarm_depth =~ m/^copy-edit/) {
700       $pre .= <<'END_COPY_EDIT';
701         find -lname "$src/*" -print0 | xargs -0r rm --;
702         (set -e; cd "$src"; git ls-files -c -z |
703         cpio --quiet -p0m --no-preserve-owner -u --make-directories "$bld/$sd");
704         clean () {
705           (set -e; cd "$src"; git ls-files -c -z) | xargs -0r rm -f --;
706         };
707 END_COPY_EDIT
708       if ($linkfarm_depth eq 'copy-edit-all') {
709         $post .= <<'END_COPY_EDIT_GENFILES_ALL';
710         find -xdev \( \( -name .git -o -path ./target -o -path ./nailing-cargo-update.tar \) -prune \) -o
711               \( -type l -o -type f \) -print0 |
712 END_COPY_EDIT_GENFILES_ALL
713       } else {
714         $post .= <<'END_COPY_EDIT_GENFILES_GIT';
715         (set -e; cd "$src"; git ls-files -c -z) |
716 END_COPY_EDIT_GENFILES_GIT
717       }
718       $post .= <<'END_COPY_EDIT_BUNDLE';
719         cpio -Hustar -o0 --quiet >"nailing-cargo-update.tar";
720 END_COPY_EDIT_BUNDLE
721     } else {
722        die "$linkfarm_depth ?";
723     }
724     $pre .= <<'ENDLK' if $do_cargo_lock;
725         if test -e Cargo.lock; then
726           rm -f Cargo.lock;
727           cp -- "$src"/Cargo.lock .;
728         fi;
729 ENDLK
730     $post .= <<'ENDCLEAN' if $oot_clean && !$just_linkfarm;
731         clean;
732 ENDCLEAN
733   }
734   my $addpath = (cfg_uc qw(oot path_add)) //
735     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
736   $addpath =
737     !Types::Serialiser::is_bool $addpath ? $addpath           :
738     $addpath                             ? '$HOME/.cargo/bin' :
739                                            undef;
740   if (defined $addpath) {
741     $pre .= <<END
742         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
743         export PATH;
744 END
745   }
746   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
747   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
748
749   my $getuser = sub { cfgsn qw(oot user) };
750   my @command;
751   my $xe = $verbose >= 2 ? 'xe' : 'e';
752   my $sh_ec = sub {
753     if (!length $post) {
754       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
755     } else {
756       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
757     }
758     push @command, @ARGV;
759   };
760   my $command_sh = sub {
761     my $quoted = join ' ', map {
762       return $_ if !m/\W/;
763       s/\'/\'\\'\'/g;
764       "'$_'"
765     } @ARGV;
766     @command = @_, "set -${xe}; $pre $quoted; $post";
767   };
768   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
769     if $verbose;
770   if ($use eq 'really') {
771     my $user = $getuser->();
772     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
773     my $homedir = $pw[7];
774     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
775     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
776   } elsif ($use eq 'ssh') {
777     my $user = $getuser->();
778     $user .= '@localhost' unless $user =~ m/\@/;
779     $command_sh->('ssh',$user);
780     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
781   } elsif ($use eq 'command_args') {
782     my @c = cfgn_list qw(oot command);
783     $sh_ec->(@c);
784     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
785   } elsif ($use eq 'command_sh') {
786     my @c = cfgn_list qw(oot command);
787     $command_sh->(@c);
788     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
789   } elsif ($use eq 'null') {
790     $sh_ec->();
791   } else {
792     die "$self: oot.use mode $use not recognised\n";
793   }
794   die unless @command;
795   @ARGV = @command;
796 }
797
798 sub setenvs () {
799   $ENV{CARGO_MANIFEST_DIR} = $src_absdir unless $linkfarm_depth;
800   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
801   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
802   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
803   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
804   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
805 }
806
807 our $want_uninstall;
808
809 END {
810   if ($want_uninstall) {
811     local ($?);
812     foreach my $mf (keys %manifests) {
813       eval { uninstall1($mf,1); 1; } or warn "$@";
814     }
815     eval { unaltcargolock(1); 1; } or warn "$@";
816   }
817 }
818
819 sub consider_directories () {
820   return unless defined $oot_dir;
821   my $bsubdir = "../$oot_dir/$subdir";
822   return if stat $bsubdir;
823   die "$0: build directory $bsubdir inaccessible\n"
824     unless $!==ENOENT;
825   return if $cargo_lock_update; # will make it
826   die "$0: build directory $bsubdir does not exist, and not in Cargo.lock update mode!\n";
827 }
828
829 our $cleanup_cargo_lock;
830 sub makebackups () {
831   foreach my $mf (keys %manifests) {
832     link "$mf", "$mf.unnailed" or $!==EEXIST
833       or die "$self: make backup link $mf.unnailed: $!\n";
834   }
835
836   if (defined($alt_cargo_lock)) {
837     die 'internal error' unless $do_cargo_lock;
838     if (@alt_cargo_lock_stat) {
839       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
840         if $verbose>=3;
841       if (link $alt_cargo_lock, 'Cargo.lock') {
842         print STDERR " linked\n" if $verbose>=3;
843       } elsif ($! != EEXIST) {
844         print STDERR "\n" if $verbose>=3;
845         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
846       } else {
847         print STDERR "checking quality." if $verbose>=3;
848         my @lock_stat = stat 'Cargo.lock'
849           or die "$self: stat Cargo.lock (for alt check: $!\n";
850         same_file(\@alt_cargo_lock_stat, \@lock_stat)
851           or die
852 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
853       }
854       $cleanup_cargo_lock = 1;
855     } else {
856       $cleanup_cargo_lock = 1;
857       # If Cargo.lock exists and alt doesn't, that means either
858       # that a previous run was interrupted, or that the user has
859       # messed up.
860     }
861   }
862 }
863
864 sub nailed ($) {
865   my ($mf) = @_;
866   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
867   $nailed;
868 }    
869
870 sub install () {
871   my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
872     ? (stat _) : ();
873   foreach my $mf (keys %manifests) {
874     if (@our_unfound_stab) {
875       if (stat_exists $mf, "manifest in to-be-nailed directory") {
876         my @mf_stab = stat _ ;
877         if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
878           @our_unfound_stab = ();
879         }
880       }
881     }
882
883     my $nailing = "$mf.nailing~";
884     my $nailed = nailed($mf);
885     my ($use, $rm);
886     my $diff;
887     if (open NN, '<', $nailed) {
888       $diff = compare($nailing, \*NN);
889       die "$self: compare $nailing and $nailed: $!" if $diff<0;
890     } else {
891       $!==ENOENT or die "$self: check previous $nailed: $!\n";
892       $diff = 1;
893     }
894     if ($diff) {
895       $use = $nailing;
896       $rm  = $nailed;
897     } else {
898       $use = $nailed;
899       $rm  = $nailing;
900     }
901     rename $use, $mf or die "$self: install nailed $use: $!\n";
902     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
903     print STDERR "$self: nailed $mf\n" if $verbose>=3;
904   }
905
906   if (@our_unfound_stab && $do_nail) {
907     print STDERR
908  "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
909   }
910 }
911
912 sub invoke () {
913   my $r = system @ARGV;
914   if (!$r) {
915     return 0;
916   } elsif ($r<0) {
917     print STDERR "$self: could not execute $ARGV[0]: $!\n";
918     return 127;
919   } elsif ($r & 0xff00) {
920     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
921     return $r >> 8;
922   } else {
923     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
924     return 125;
925   }
926 }
927
928 sub files_return_after_update () {
929   if ($linkfarm_depth =~ m/^copy-edit/) {
930     my $tar_source_opts;
931     my $tar_stdin;
932     if ($linkfarm_depth eq 'copy-edit-all') {
933       $tar_source_opts = '--null --files-from=-';
934       $tar_stdin = <<'END_GIT_FILES';
935       git ls-files -c -z | \
936 END_GIT_FILES
937     } else {
938       $tar_source_opts = '--anchored --exclude=.git --exclude="*/.git" --exclude=target --exclude=nailing-cargo-update.tar';
939       $tar_stdin = '';
940     }
941     system qw(sh -ec), $tar_stdin . <<'END', 'x', "$build_absdir";
942       tar -x --keep-newer-files --no-same-permissions --no-same-owner \
943         --no-acls --no-selinux --no-xattrs --warning=no-ignore-newer \
944         -Hustar $tar_source_opts --force-local \
945         -f "$1/nailing-cargo-update.tar"
946 END
947   } elsif ($do_cargo_lock && $cargo_lock_update && !$just_linkfarm) {
948     # avoids importing File::Copy and the error handling is about as good
949     $!=0; $?=0;
950     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
951     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
952     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
953   }
954 }
955
956 sub uninstall1 ($$) {
957   my ($mf, $enoentok) = @_;
958   my $unnailed = "$mf.unnailed";
959   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
960     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
961 }
962
963 sub unaltcargolock ($) {
964   my ($enoentok) = @_;
965   return unless $cleanup_cargo_lock;
966   die 'internal error!' unless $do_cargo_lock && defined $alt_cargo_lock;
967
968   # we ignore $enoentok because we don't know if one was supposed to
969   # have been created.
970
971   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
972  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
973
974   unlink 'Cargo.lock' or $!==ENOENT or die
975  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
976   # ^ this also helps clean up the stupid rename() corner case
977 }
978
979 sub uninstall () {
980   foreach my $mf (keys %manifests) {
981     my $nailed = nailed($mf);
982     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
983     uninstall1($mf,0);
984   }
985   unaltcargolock(0);
986 }
987
988 sub parse_args () {
989   my $is_cargo;
990
991   # Loop exit condition:
992   #   $is_cargo is set
993   #   @ARGV contains
994   #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
995   #    $is_cargo==0   <build-command>...
996
997  OPTS: for (;;) {
998     if (!@ARGV) {
999       die "$self: need cargo subcommand\n"
1000         unless $noact || $just_linkfarm;;
1001       push @ARGV, "CARGO-SUBCOMMAND"; # dummy, user may see it
1002     }
1003
1004     $_ = shift @ARGV;
1005     my $orgopt = $_;
1006
1007     my $not_a_nailing_opt = sub { # usage 1
1008       unshift @ARGV, $orgopt;
1009       unshift @ARGV, 'cargo';
1010       $is_cargo = 1;
1011       no warnings qw(exiting);
1012       last OPTS;
1013     };
1014     $not_a_nailing_opt->() unless m{^-};
1015     $not_a_nailing_opt->() if $_ eq '--';
1016
1017     my $edits_sources = sub {
1018       $linkfarm_depth =
1019         ($linkfarm_depth//'') eq 'copy-edit' ? 'copy-edit-all' : 'copy-edit';
1020     };
1021
1022     if ($_ eq '---') { # usage 2 or 3
1023       if (!@ARGV) {
1024         die "$self: --- must be followed by build command\n" unless $noact;
1025         push @ARGV, 'BUILD-COMMAND';
1026       }
1027       if ($ARGV[0] eq '--') { # usage 3
1028         shift;
1029         $is_cargo = 0;
1030       } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
1031         $is_cargo = 1;
1032       } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
1033         $is_cargo = 1;
1034       } else {  # usage 3
1035         $is_cargo = 0;
1036       }
1037       last;
1038     }
1039     if (m{^-[^-]}) {
1040       while (m{^-.}) {
1041         if (s{^-h}{-}) {
1042           print_usage();
1043         } elsif (s{^-v}{-}) {
1044           $verbose++;
1045         } elsif (s{^-q}{-}) {
1046           $verbose=0;
1047         } elsif (s{^-n}{-}) {
1048           $noact++;
1049         } elsif (s{^-s(.+)}{-}s) {
1050           $cargo_subcmd = $1;
1051         } elsif (s{^-([uU])}{-}) {
1052           $cargo_lock_update = $1=~m/[a-z]/;
1053         } elsif (s{^-([cC])}{-}) {
1054           $pass_options = $1=~m/[a-z]/;
1055         } elsif (s{^-D}{-}) {
1056           $dump++;
1057         } elsif (s{^-E}{-}) {
1058           $edits_sources->();
1059         } elsif (s{^-T(.+)}{-}s) {
1060           $target = $1;
1061         } elsif (s{^-([oO])}{-}) {
1062           $online = $1=~m/[a-z]/;
1063         } else {
1064           die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
1065           $not_a_nailing_opt->();
1066         }
1067       }
1068     } elsif (s{^--help$}{}) {
1069       print_usage();
1070     } elsif (s{^--(?:doc|man|manual)?$}{}) {
1071       show_manual();
1072     } elsif (s{^--target=}{}) {
1073       $target = $_;
1074     } elsif (m{^--(on|off)line$}) {
1075       $online = $1 eq 'on';
1076     } elsif (m{^--just-linkfarm(?:=(shallow|git|full))?$}) {
1077       $just_linkfarm = 1;
1078       $linkfarm_depth = $1 if $1;
1079       $cargo_lock_update= 1; # will set $linkfarm_detph to 1 by default
1080     } elsif (m{^--linkfarm(?:=(no|shallow|git|full))?$}) {
1081       $linkfarm_depth = $1 || 'git';
1082     } elsif (m{^--edits?-sources?$}) {
1083       $edits_sources->();
1084     } elsif (m{^--just-run$}) {
1085       $do_nail = $do_cargo_lock = $do_lock = 0;
1086     } elsif (m{^--(clean|keep)-linkfarm$}) {
1087       $oot_clean = $1 eq 'clean';
1088     } elsif (m{^--(no-)?preclean-build$}) {
1089       $oot_preclean = $1 ? 'no' : 'src';
1090     } elsif (m{^--preclean-build=(no|src|full)$}) {
1091       $oot_preclean = $1;
1092     } elsif (m{^--(no-)?nail$}) {
1093       $do_nail = !$1;
1094     } elsif (m{^--(no-)?cargo-lock-manip$}) {
1095       $do_cargo_lock = !$1;
1096     } elsif (m{^--(no-)?concurrency-lock$}) {
1097       $do_lock = !$1;
1098     } elsif (m{^--leave-nailed$}) {
1099       $leave_nailed = 1;
1100     } elsif (s{^--subcommand-props=}{}) {
1101       my @props = split /\,/, $_;
1102       our %subcmd_prop_ok;
1103       if (!%subcmd_prop_ok) {
1104         foreach my $v (\@subcmd_xprops, values %subcmd_props) {
1105           $subcmd_prop_ok{$_}=1 foreach @$v;
1106         };
1107       }
1108       $subcmd_prop_ok{$_}
1109         or die "$self: unknown subcommand property \`$_'\n"
1110         foreach @props;
1111       $cargo_subcmd = \@props;
1112     } elsif (m{^--(no-)?cargo-lock-update}) {
1113       $cargo_lock_update= !!$1;
1114     } else {
1115       $not_a_nailing_opt->();
1116     }
1117   }
1118
1119   $is_cargo // die;
1120   @ARGV || die;
1121
1122   if ($is_cargo) {
1123     @args_preface = shift @ARGV;
1124     while (defined($_ = shift @ARGV)) {
1125       if (!m{^-|^\+}) { unshift @ARGV, $_; last; }
1126       if ($_ eq '--') { last; }
1127       push @args_preface, $_;
1128     }
1129     @ARGV || die "$self: need cargo subcommand\n";
1130     $cargo_subcmd //= $ARGV[0];
1131     $pass_options //= 1;
1132   } else {
1133     $cargo_subcmd //= '';
1134     $pass_options //= 0;
1135   }
1136   push @args_preface, shift @ARGV;
1137
1138   if (!ref($cargo_subcmd)) {
1139     print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
1140     $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
1141   }
1142
1143   print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
1144   my %cargo_subcmd;
1145   $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
1146   $cargo_subcmd = \%cargo_subcmd;
1147 }
1148
1149 parse_args();
1150 loadconfigs();
1151 readnail();
1152 takelock();
1153 consider_alt_cargo_lock();
1154 consider_oot();
1155 readorigs();
1156 calculate();
1157 addargs();
1158 consider_directories();
1159 our @display_cmd = @ARGV;
1160 oot_massage_cmdline();
1161 setenvs();
1162
1163 if ($dump) {
1164   eval '
1165     use Data::Dumper;
1166     print STDERR Dumper(\%manifests) if $dump>=2;
1167     print STDERR Dumper(\%packagemap, \@ARGV,
1168                         { src_absdir => $src_absdir,
1169                           worksphere => $worksphere,
1170                           subdir => $subdir,
1171                           oot_dir => $oot_dir,
1172                           oot_absdir => $oot_absdir,
1173                           build_absdir => $build_absdir,
1174                           linkfarm_depth => $linkfarm_depth,
1175                           oot_preclean => $oot_preclean, });
1176   ' or die $@;
1177 }
1178
1179 exit 0 if $noact;
1180
1181 $want_uninstall = !$leave_nailed;
1182 makebackups();
1183 install();
1184
1185 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
1186   (scalar keys %manifests), (scalar keys %packagemap),
1187   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
1188   if $verbose && $do_nail;
1189
1190 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
1191 my $estatus = invoke();
1192
1193 files_return_after_update();
1194
1195 uninstall() unless $leave_nailed;
1196 $want_uninstall = 0;
1197
1198 print STDERR "$self: ".($do_nail ? "unnailed" : "finished")
1199              .".  status $estatus.\n" if $verbose;
1200
1201 exit $estatus;