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