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