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