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