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