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