chiark / gitweb /
Pass options right after the cargo subommand
[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     die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
281       if $cargo_lock_update;
282     $cargo_lock_update=0;
283     return;
284   }
285   if ($use eq 'disable') {
286     $oot_dir = undef;
287     return;
288   }
289   $oot_dir //= 'Build';
290 }
291
292 our %manifests;
293 our %packagemap;
294
295 sub read_manifest ($) {
296   my ($subdir) = @_;
297   my $manifest = "../$subdir/Cargo.toml";
298   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
299   if (defined $manifests{$manifest}) {
300     print STDERR
301  "$self: warning: $subdir: specified more than once!\n";
302     return undef;
303   }
304   foreach my $try ("$manifest.unnailed", "$manifest") {
305     my $toml = toml_or_enoent($try, "package manifest") // next;
306     my $p = $toml->{package}{name};
307     if (!defined $p) {
308       print STDERR
309  "$self: warning: $subdir: missing package.name in $try, ignoring\n";
310       next;
311     }
312     $manifests{$manifest} = $toml;
313     return $p;
314   }
315   return undef;
316 }
317
318 sub readorigs () {
319   foreach my $p (keys %{ $nail->{packages} }) {
320     my $v = $nail->{packages}{$p};
321     my $subdir = ref($v) ? $v->{subdir} : $v;
322     my $gotpackage = read_manifest($subdir) // '<nothing!>';
323     if ($gotpackage ne $p) {
324       print STDERR
325  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
326     }
327     die if defined $packagemap{$p};
328     $packagemap{$p} = $subdir;
329   }
330   foreach my $subdir (@{ $nail->{subdirs} }) {
331     my $gotpackage = read_manifest($subdir);
332     if (!defined $gotpackage) {
333       print STDERR
334  "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
335       next;
336     }
337     $packagemap{$gotpackage} //= $subdir;
338   }
339 }
340
341 sub calculate () {
342   foreach my $p (sort keys %packagemap) {
343     print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
344   }
345   foreach my $mf (keys %manifests) {
346     my $toml = $manifests{$mf};
347     foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
348       my $deps = $toml->{$k};
349       next unless $deps;
350       foreach my $p (keys %packagemap) {
351         my $info = $deps->{$p};
352         next unless defined $info;
353         $deps->{$p} = $info = { } unless ref $info;
354         delete $info->{version};
355         $info->{path} = $worksphere.'/'.$packagemap{$p};
356       }
357     }
358     my $nailing = "$mf.nailing~";
359     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
360     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
361     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
362     close N or die "$self: close new $nailing: $!\n";
363   }
364 }
365
366 sub addargs () {
367   $online = 1 if subcmd_p('online');
368   $online //= cfg_bool qw(misc online);
369   $online //= 0;
370
371   $cargo_lock_update //= subcmd_p('lock-update');
372
373   our @add;
374
375   if (!$cargo_lock_update) {
376     push @add, qw(--locked) unless subcmd_p('!locked');
377     if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
378       my $cargotoml = "${src_absdir}/Cargo.toml";
379       push @args_preface, "--manifest-path=$cargotoml" if $pass_options;
380       push @add, qw(--target-dir=target) unless subcmd_p('!target-dir');
381     }
382   }
383
384   if (defined($target) && !subcmd_p('!target')) {
385     if ($target =~ m{^[A-Z]}) {
386       $target = (cfgs 'arch', $target) // $archmap{$target}
387         // die "$self: --target=$target alias specified; not in cfg or map\n";
388     }
389     push @add, "--target=$target";
390   }
391
392   push @add, "--offline" unless $online || subcmd_p('!offline');
393
394   push @args_preface, @add if $pass_options;
395   die if grep { m/ / } @add;
396   $ENV{NAILINGCARGO_CARGO_OPTIONS} = "@add";
397
398   unshift @ARGV, @args_preface;
399 }
400
401 our $oot_absdir;
402 our $build_absdir; # .../Build/<subdir>
403
404 sub oot_massage_cmdline () {
405   return unless defined $oot_dir;
406
407   my $use = cfgs qw(oot use);
408   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
409   $build_absdir = "$oot_absdir/$subdir";
410
411   my ($pre,$post);
412   my @xargs;
413   if (!$cargo_lock_update) {
414     push @xargs, $build_absdir;
415     ($pre, $post) = ('cd "$1"; shift; ', '');
416   } else {
417     push @xargs, $oot_absdir, $subdir, $src_absdir;
418     $pre =  <<'END';
419         cd "$1"; shift;
420         mkdir -p -- "$1"; cd "$1"; shift;
421         cp -- "$1"/Cargo.toml
422 END
423     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
424               "$1"/Cargo.lock
425 ENDLK
426     $pre .= <<'ENDCP';
427                               .;
428 ENDCP
429     $pre .= <<'ENDPRE';
430         shift;
431         mkdir -p src; >src/lib.rs; >build.rs
432 ENDPRE
433     $post = <<'ENDPOST';
434         rm -r src Cargo.toml build.rs;
435 ENDPOST
436   }
437   my $addpath = (cfg_uc qw(oot path_add)) //
438     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
439   $addpath =
440     !Types::Serialiser::is_bool $addpath ? $addpath           :
441     $addpath                             ? '$HOME/.cargo/bin' :
442                                            undef;
443   if (defined $addpath) {
444     $pre .= <<END
445         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
446         export PATH;
447 END
448   }
449   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
450   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
451
452   my $getuser = sub { cfgsn qw(oot user) };
453   my @command;
454   my $xe = $verbose >= 2 ? 'xe' : 'e';
455   my $sh_ec = sub {
456     if (!length $post) {
457       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
458     } else {
459       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
460     }
461     push @command, @ARGV;
462   };
463   my $command_sh = sub {
464     my $quoted = join ' ', map {
465       return $_ if !m/\W/;
466       s/\'/\'\\'\'/g;
467       "'$_'"
468     } @ARGV;
469     @command = @_, "set -${xe}; $pre $quoted; $post";
470   };
471   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
472     if $verbose;
473   if ($use eq 'really') {
474     my $user = $getuser->();
475     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
476     my $homedir = $pw[7];
477     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
478     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
479   } elsif ($use eq 'ssh') {
480     my $user = $getuser->();
481     $user .= '@localhost' unless $user =~ m/\@/;
482     $command_sh->('ssh',$user);
483     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
484   } elsif ($use eq 'command_args') {
485     my @c = cfgn_list qw(oot command);
486     $sh_ec->(@c);
487     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
488   } elsif ($use eq 'command_sh') {
489     my @c = cfgn_list qw(oot command);
490     $command_sh->(@c);
491     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
492   } elsif ($use eq 'null') {
493     $sh_ec->();
494   } else {
495     die "$self: oot.use mode $use not recognised\n";
496   }
497   die unless @command;
498   @ARGV = @command;
499 }
500
501 sub setenvs () {
502   $ENV{CARGO_MANIFEST_DIR} = $src_absdir;
503   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
504   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
505   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
506   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
507   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
508 }
509
510 our $want_uninstall;
511
512 END {
513   if ($want_uninstall) {
514     local ($?);
515     foreach my $mf (keys %manifests) {
516       eval { uninstall1($mf,1); 1; } or warn "$@";
517     }
518     eval { unaltcargolock(1); 1; } or warn "$@";
519   }
520 }
521
522 our $cleanup_cargo_lock;
523 sub makebackups () {
524   foreach my $mf (keys %manifests) {
525     link "$mf", "$mf.unnailed" or $!==EEXIST
526       or die "$self: make backup link $mf.unnailed: $!\n";
527   }
528
529   if (defined($alt_cargo_lock)) {
530     if (@alt_cargo_lock_stat) {
531       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
532         if $verbose>=3;
533       if (link $alt_cargo_lock, 'Cargo.lock') {
534         print STDERR " linked\n" if $verbose>=3;
535       } elsif ($! != EEXIST) {
536         print STDERR "\n" if $verbose>=3;
537         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
538       } else {
539         print STDERR "checking quality." if $verbose>=3;
540         my @lock_stat = stat 'Cargo.lock'
541           or die "$self: stat Cargo.lock (for alt check: $!\n";
542         same_file(\@alt_cargo_lock_stat, \@lock_stat)
543           or die
544 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
545       }
546       $cleanup_cargo_lock = 1;
547     } else {
548       $cleanup_cargo_lock = 1;
549       # If Cargo.lock exists and alt doesn't, that means either
550       # that a previous run was interrupted, or that the user has
551       # messed up.
552     }
553   }
554 }
555
556 sub nailed ($) {
557   my ($mf) = @_;
558   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
559   $nailed;
560 }    
561
562 sub install () {
563   my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
564     ? (stat _) : ();
565   foreach my $mf (keys %manifests) {
566     if (@our_unfound_stab) {
567       if (stat_exists $mf, "manifest in to-be-nailed directory") {
568         my @mf_stab = stat _ ;
569         if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
570           @our_unfound_stab = ();
571         }
572       }
573     }
574
575     my $nailing = "$mf.nailing~";
576     my $nailed = nailed($mf);
577     my ($use, $rm);
578     my $diff;
579     if (open NN, '<', $nailed) {
580       $diff = compare($nailing, \*NN);
581       die "$self: compare $nailing and $nailed: $!" if $diff<0;
582     } else {
583       $!==ENOENT or die "$self: check previous $nailed: $!\n";
584       $diff = 1;
585     }
586     if ($diff) {
587       $use = $nailing;
588       $rm  = $nailed;
589     } else {
590       $use = $nailed;
591       $rm  = $nailing;
592     }
593     rename $use, $mf or die "$self: install nailed $use: $!\n";
594     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
595     print STDERR "$self: nailed $mf\n" if $verbose>=3;
596   }
597
598   if (@our_unfound_stab) {
599     print STDERR
600  "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
601   }
602 }
603
604 sub invoke () {
605   my $r = system @ARGV;
606   if (!$r) {
607     return 0;
608   } elsif ($r<0) {
609     print STDERR "$self: could not execute $ARGV[0]: $!\n";
610     return 127;
611   } elsif ($r & 0xff00) {
612     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
613     return $r >> 8;
614   } else {
615     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
616     return 125;
617   }
618 }
619
620 sub cargo_lock_update_after () {
621   if ($cargo_lock_update) {
622     # avoids importing File::Copy and the error handling is about as good
623     $!=0; $?=0;
624     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
625     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
626     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
627   }
628 }
629
630 sub uninstall1 ($$) {
631   my ($mf, $enoentok) = @_;
632   my $unnailed = "$mf.unnailed";
633   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
634     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
635 }
636
637 sub unaltcargolock ($) {
638   my ($enoentok) = @_;
639   return unless $cleanup_cargo_lock;
640   die 'internal error!' unless defined $alt_cargo_lock;
641
642   # we ignore $enoentok because we don't know if one was supposed to
643   # have been created.
644
645   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
646  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
647
648   unlink 'Cargo.lock' or $!==ENOENT or die
649  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
650   # ^ this also helps clean up the stupid rename() corner case
651 }
652
653 sub uninstall () {
654   foreach my $mf (keys %manifests) {
655     my $nailed = nailed($mf);
656     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
657     uninstall1($mf,0);
658   }
659   unaltcargolock(0);
660 }
661
662 sub parse_args () {
663   my $is_cargo;
664
665   # Loop exit condition:
666   #   $is_cargo is set
667   #   @ARGV contains
668   #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
669   #    $is_cargo==0   <build-command>...
670
671   for (;;) {
672     @ARGV or die "$self: need cargo subcommand\n";
673
674     $_ = shift @ARGV;
675     my $orgopt = $_;
676
677     my $not_a_nailing_opt = sub { # usage 1
678       unshift @ARGV, $orgopt;
679       unshift @ARGV, 'cargo';
680       $is_cargo = 1;
681       no warnings qw(exiting);
682       last;
683     };
684     $not_a_nailing_opt->() unless m{^-};
685     $not_a_nailing_opt->() if $_ eq '--';
686
687     if ($_ eq '---') { # usage 2 or 3
688       die "$self: --- must be followed by build command\n" unless @ARGV;
689       if ($ARGV[0] eq '--') { # usage 3
690         shift;
691         $is_cargo = 0;
692       } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
693         $is_cargo = 1;
694       } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
695         $is_cargo = 1;
696       } else {  # usage 3
697         $is_cargo = 0;
698       }
699       last;
700     }
701     if (m{^-[^-]}) {
702       while (m{^-.}) {
703         if (s{^-v}{-}) {
704           $verbose++;
705         } elsif (s{^-q}{-}) {
706           $verbose=0;
707         } elsif (s{^-n}{-}) {
708           $noact++;
709         } elsif (s{^-s(.+)}{-}s) {
710           $cargo_subcmd = $1;
711         } elsif (s{^-([cC])}{-}) {
712           $pass_options = $1=~m/[a-z]/;
713         } elsif (s{^-D}{-}) {
714           $dump++;
715         } elsif (s{^-T(.+)}{-}s) {
716           $target = $1;
717         } elsif (s{^-([oO])}{-}) {
718           $online = $1=~m/[a-z]/;
719         } else {
720           die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
721           $not_a_nailing_opt->();
722         }
723       }
724     } elsif (s{^--target=}{}) {
725       $target = $_;
726     } elsif (m{^--(on|off)line$}) {
727       $online = $1 eq 'on';
728     } elsif (s{^--subcommand-props=}{}) {
729       my @props = split /\,/, $_;
730       our %subcmd_prop_ok;
731       if (!%subcmd_prop_ok) {
732         foreach my $v (\@subcmd_xprops, values %subcmd_props) {
733           $subcmd_prop_ok{$_}=1 foreach @$v;
734         };
735       }
736       $subcmd_prop_ok{$_}
737         or die "$self: unknown subcommand property \`$_'\n"
738         foreach @props;
739       $cargo_subcmd = \@props;
740     } elsif (m{^--(no-)?cargo-lock-update}) {
741       $cargo_lock_update= !!$1;
742     } else {
743       $not_a_nailing_opt->();
744     }
745   }
746
747   $is_cargo // die;
748   @ARGV || die;
749
750   if ($is_cargo) {
751     @args_preface = shift @ARGV;
752     while (defined($_ = shift @ARGV)) {
753       if (!m{^-}) { unshift @ARGV, $_; last; }
754       if ($_ eq '--') { last; }
755       push @args_preface, $_;
756     }
757     @ARGV || die "$self: need cargo subcommand\n";
758     $cargo_subcmd //= $ARGV[0];
759     $pass_options //= 1;
760   } else {
761     $cargo_subcmd //= '';
762     $pass_options //= 0;
763   }
764   push @args_preface, shift @ARGV;
765
766   if (!ref($cargo_subcmd)) {
767     print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
768     $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
769   }
770
771   print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
772   my %cargo_subcmd;
773   $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
774   $cargo_subcmd = \%cargo_subcmd;
775 }
776
777 parse_args();
778 loadconfigs();
779 takelock();
780 readnail();
781 consider_alt_cargo_lock();
782 consider_oot();
783 readorigs();
784 calculate();
785 addargs();
786 our @display_cmd = @ARGV;
787 oot_massage_cmdline();
788 setenvs();
789
790 if ($dump) {
791   eval '
792     use Data::Dumper;
793     print STDERR Dumper(\%manifests) if $dump>=2;
794     print STDERR Dumper(\%packagemap, \@ARGV,
795                         { src_absdir => $src_absdir,
796                           worksphere => $worksphere,
797                           subdir => $subdir,
798                           oot_dir => $oot_dir,
799                           oot_absdir => $oot_absdir,
800                           build_absdir => $build_absdir });
801   ' or die $@;
802 }
803
804 exit 0 if $noact;
805
806 $want_uninstall = 1;
807 makebackups();
808 install();
809
810 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
811   (scalar keys %manifests), (scalar keys %packagemap),
812   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
813   if $verbose;
814
815 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
816 my $estatus = invoke();
817
818 cargo_lock_update_after();
819
820 uninstall();
821 $want_uninstall = 0;
822
823 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
824
825 exit $estatus;