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