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