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