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