chiark / gitweb /
nailing-cargo: Break out get_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   foreach my $k (@keys) {
247     my $deps = $toml->{$k};
248     push @r, $deps if $deps;
249   }
250   @r;
251 }
252
253 our @alt_cargo_lock_stat;
254
255 sub consider_alt_cargo_lock () {
256   my @ck = qw(alt_cargo_lock);
257   # User should *either* have Cargo.lock in .gitignore,
258   # or expect to commit Cargo.lock.example ($alt_cargo_lock)
259
260   $alt_cargo_lock = (cfg_uc @ck);
261
262   my $force = 0;
263   if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
264     $force = cfg_bool qw(alt_cargo_lock force);
265     my @ck = qw(alt_cargo_lock file);
266     $alt_cargo_lock = cfg_uc @ck;
267   }
268   $alt_cargo_lock //= Types::Serialiser::true;
269
270   if (Types::Serialiser::is_bool $alt_cargo_lock) {
271     if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
272     $alt_cargo_lock = 'Cargo.lock.example';
273   }
274
275   if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
276     badcfg @ck, "expected boolean, or leafname";
277   }
278
279   if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
280     $alt_cargo_lock = undef unless $force;
281     return;
282   }
283   
284   @alt_cargo_lock_stat = stat _;
285 }
286
287 our $oot_dir;      # oot.dir or "Build"
288 our $oot_absdir;
289
290 sub consider_oot () {
291   $oot_dir = cfgs qw(oot dir);
292   my $use = cfgs qw(oot use);
293   unless (defined($oot_dir) || defined($use) ||
294           defined(cfg_uc qw(oot user))) {
295     return;
296   }
297   if (($use//'') eq 'disable') {
298     $oot_dir = undef;
299     return;
300   }
301   $oot_dir //= 'Build';
302   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
303 }
304
305 our %manifests;
306 our %packagemap;
307 our %workspaces;
308 our @queued_paths;
309
310 sub read_manifest ($$$) {
311   my ($subdir, $org_subdir, $why) = @_;
312   my $manifest = "../$subdir/Cargo.toml";
313   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
314   if (defined $manifests{$manifest}) {
315     print STDERR
316  "$self: warning: $subdir: specified more than once!".
317  " (ignoring $why)\n";
318     return undef;
319   }
320   foreach my $try ("$manifest.unnailed", "$manifest") {
321     my $toml = toml_or_enoent($try, "manifest, in $why") // next;
322     my $ws = $toml->{workspace};
323     if ($ws) {
324       queue_workspace_members($subdir, $org_subdir, $ws, "$subdir, $why");
325     }
326     my $p = $toml->{package}{name};
327     if (!defined $p and !defined $ws) {
328       print STDERR
329  "$self: warning: $subdir, $why: missing package.name in $try, ignoring\n";
330       next;
331     }
332     $manifests{$manifest} = $toml if $p;
333     return ($p, $ws);
334   }
335   return undef;
336 }
337
338 sub queue_workspace_members ($$) {
339   my ($subdir, $org_subdir, $ws_toml, $what) = @_;
340   # We need to (more or less) reimplement the cargo workspace
341   # membership algorithm (see the "workspaces" section of the cargo
342   # reference).  How tiresome.
343   #
344   # It's not quite the same for us because we aren't interested in
345   # whether cargo thinks things are "in the workspace".  But we do
346   # need to do the automatic discover.
347
348   my @include = @{ $ws_toml->{members} // [ ] };
349   my $exclude = $ws_toml->{exclude} // [ ];
350
351   my @exclude = map {
352     s/[^*?0-9a-zA-Z_]/\\$&/g;
353     s/\?/./g;
354     s/\*/.*/g;
355   } @$exclude;
356
357   foreach my $spec (@include) {
358     if ($spec =~ m{^/}) {
359       print STDERR
360         "$self: warning: absolute workspace member $spec in $what (not nailing, but cargo will probably use it)\n";
361       next;
362     }
363     my $spec_glob = "../$subdir/$spec";
364     my $globflags = GLOB_ERR|GLOB_BRACE|GLOB_NOMAGIC;
365     foreach my $globent (bsd_glob($spec_glob, $globflags)) {
366       next if grep { $globent =~ m{^$_$} } @exclude;
367       queue_referenced_path($globent, $org_subdir,
368                             "member of workspace $what");
369     }
370   }
371 }
372
373 sub queue_referenced_path ($$$) {
374   my ($spec_path, $org_subdir, $why) = @_;
375   open REALPATH, "-|",
376     qw(realpath), "--relative-to=../$org_subdir", "--", $spec_path
377     or die "$self: fork/pipe/exec for realpath(1)\n";
378   my $rel_path = do { local $/=undef; <REALPATH>; };
379   $?=0; $!=0;
380   my $r = close(REALPATH);
381   die "$self: reap realpath: $!\n" if $!;
382   if (!chomp($rel_path) or $?) {
383     print STDERR
384  "$self: warning: failed to determine realpath for $spec_path in $org_subdir (exit code $?)\n";
385     return;
386   }
387   if ($rel_path =~ m{^\.\./} or $rel_path eq '..') {
388     print STDERR
389       "$self: warning: $spec_path ($why) points outside $org_subdir, not following so not nailing (although cargo probably will follow it)\n";
390     return;
391   }
392
393   my $q_subdir = "$org_subdir/$rel_path";
394   print STDERR "$self: making a note to look at $q_subdir, $why)\n"
395     if $verbose >= 4;
396
397   push @queued_paths, [ "$q_subdir", $org_subdir, $why ];
398 }
399
400 sub readorigs () {
401   foreach my $p (keys %{ $nail->{packages} }) {
402     my $v = $nail->{packages}{$p};
403     my $subdir = ref($v) ? $v->{subdir} : $v;
404     my ($gotpackage, $ws) = read_manifest($subdir, $subdir, "from [packages]");
405     $gotpackage //= '<nothing!>';
406     if ($gotpackage ne $p) {
407       print STDERR
408  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
409     }
410     die if defined $packagemap{$p};
411     $packagemap{$p} = $subdir;
412   }
413   foreach my $subdir (@{ $nail->{subdirs} }) {
414     my ($gotpackage,$ws) = read_manifest($subdir, $subdir, "from [subdirs]");
415     if (!defined $gotpackage) {
416       print STDERR
417  "$self: warning: ignoring subdir $subdir which has no (suitable) Cargo.toml\n"
418         unless $ws;
419       next;
420     }
421     $packagemap{$gotpackage} //= $subdir;
422   }
423   while (my ($subdir, $org_subdir, $why) = @{ shift @queued_paths or [] }) {
424     next if $manifests{"../$subdir/Cargo.toml"};
425     my ($gotpackage, $ws) = read_manifest($subdir, $org_subdir, $why);
426     next unless $gotpackage;
427     $packagemap{$gotpackage} //= $subdir;
428   }
429 }
430
431 sub calculate () {
432   foreach my $p (sort keys %packagemap) {
433     print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
434   }
435   foreach my $mf (keys %manifests) {
436     my $toml = $manifests{$mf};
437     foreach my $deps (get_dependency_tables $toml) {
438       next unless $deps;
439       foreach my $p (keys %packagemap) {
440         my $info = $deps->{$p};
441         next unless defined $info;
442         $deps->{$p} = $info = { } unless ref $info;
443         delete $info->{version};
444         my $newpath = $worksphere.'/'.$packagemap{$p};
445         if ($cargo_lock_update and defined $oot_dir and
446             $newpath =~ m{^\Q$src_absdir\E(?=$|/)}) {
447           our $oot_subdir_realpath;
448           $oot_subdir_realpath //= Cwd::realpath "$oot_absdir/$subdir"
449             // die "$self: cannot resolve $oot_absdir/$subdir: $!";
450           $newpath = $oot_subdir_realpath.$';
451         }
452         $info->{path} = $newpath;
453       }
454     }
455     my $nailing = "$mf.nailing~";
456     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
457     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
458     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
459     close N or die "$self: close new $nailing: $!\n";
460   }
461 }
462
463 sub addargs () {
464   if (!defined $online) {
465     $_ = cfg_uc qw(misc online);
466     if (!defined $_) {
467     } elsif (Types::Serialiser::is_bool $_) {
468       $online = $_;
469     } elsif (ref $_) {
470     } elsif (m/^a/) {
471       $online = undef;
472     } elsif (m/^[1ty]/) { # allow booleanish strings
473       $online = 1;        # for less user frustration
474     } elsif (m/^[0fn]/) {
475       $online = 0;
476     } else {
477       badcfg qw(misc online), "expected boolean or 'auto', found '$_'";
478     }
479   }
480   $online //= 1 if subcmd_p('online');
481   $online //= 0;
482
483   $cargo_lock_update //= subcmd_p('lock-update');
484
485   our @add;
486
487   if (!$cargo_lock_update) {
488     push @add, qw(--locked) unless subcmd_p('!locked');
489     if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
490       my $cargotoml = "${src_absdir}/Cargo.toml";
491       push @args_preface, "--manifest-path=$cargotoml" if $pass_options;
492       push @add, qw(--target-dir=target) unless subcmd_p('!target-dir');
493     }
494   }
495
496   if (defined($target) && !subcmd_p('!target')) {
497     if ($target =~ m{^[A-Z]}) {
498       $target = (cfgs 'arch', $target) // $archmap{$target}
499         // die "$self: --target=$target alias specified; not in cfg or map\n";
500     }
501     push @add, "--target=$target";
502   }
503
504   push @add, "--offline" unless $online || subcmd_p('!offline');
505
506   push @args_preface, @add if $pass_options;
507   die if grep { m/ / } @add;
508   $ENV{NAILINGCARGO_CARGO_OPTIONS} = "@add";
509
510   unshift @ARGV, @args_preface;
511 }
512
513 our $build_absdir; # .../Build/<subdir>
514
515 sub oot_massage_cmdline () {
516   return unless defined $oot_dir;
517
518   my $use = cfgs qw(oot use);
519   $use // die "$self: out-of-tree build, but \`oot.use' not configured\n";
520   $build_absdir = "$oot_absdir/$subdir";
521
522   my ($pre,$post) = ('','');
523   my @xargs;
524   if (!$cargo_lock_update) {
525     push @xargs, $build_absdir;
526     ($pre, $post) = ('cd "$1"; shift; ', '');
527   } else {
528     push @xargs, $oot_absdir, $subdir, $src_absdir;
529     $pre =  <<'END';
530         cd "$1"; shift;
531         mkdir -p -- "$1"; cd "$1"; shift;
532         clean () { find -lname "$1/*" -print0 | xargs -0r rm --; }; clean;
533         find "$1" -maxdepth 1 \! -name Cargo.lock -print0 | xargs -0r -I_ ln -sf -- _ .;
534 END
535     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
536         rm -f Cargo.lock;
537         cp -- "$1"/Cargo.lock .;
538 ENDLK
539     $pre .= <<'ENDPRE';
540         shift;
541 ENDPRE
542 #    $post = <<'ENDCLEAN';
543 #        clean;
544 #ENDCLEAN
545   }
546   my $addpath = (cfg_uc qw(oot path_add)) //
547     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
548   $addpath =
549     !Types::Serialiser::is_bool $addpath ? $addpath           :
550     $addpath                             ? '$HOME/.cargo/bin' :
551                                            undef;
552   if (defined $addpath) {
553     $pre .= <<END
554         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
555         export PATH;
556 END
557   }
558   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
559   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
560
561   my $getuser = sub { cfgsn qw(oot user) };
562   my @command;
563   my $xe = $verbose >= 2 ? 'xe' : 'e';
564   my $sh_ec = sub {
565     if (!length $post) {
566       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
567     } else {
568       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
569     }
570     push @command, @ARGV;
571   };
572   my $command_sh = sub {
573     my $quoted = join ' ', map {
574       return $_ if !m/\W/;
575       s/\'/\'\\'\'/g;
576       "'$_'"
577     } @ARGV;
578     @command = @_, "set -${xe}; $pre $quoted; $post";
579   };
580   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
581     if $verbose;
582   if ($use eq 'really') {
583     my $user = $getuser->();
584     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
585     my $homedir = $pw[7];
586     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
587     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
588   } elsif ($use eq 'ssh') {
589     my $user = $getuser->();
590     $user .= '@localhost' unless $user =~ m/\@/;
591     $command_sh->('ssh',$user);
592     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
593   } elsif ($use eq 'command_args') {
594     my @c = cfgn_list qw(oot command);
595     $sh_ec->(@c);
596     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
597   } elsif ($use eq 'command_sh') {
598     my @c = cfgn_list qw(oot command);
599     $command_sh->(@c);
600     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
601   } elsif ($use eq 'null') {
602     $sh_ec->();
603   } else {
604     die "$self: oot.use mode $use not recognised\n";
605   }
606   die unless @command;
607   @ARGV = @command;
608 }
609
610 sub setenvs () {
611   $ENV{CARGO_MANIFEST_DIR} = $src_absdir;
612   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
613   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
614   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
615   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
616   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
617 }
618
619 our $want_uninstall;
620
621 END {
622   if ($want_uninstall) {
623     local ($?);
624     foreach my $mf (keys %manifests) {
625       eval { uninstall1($mf,1); 1; } or warn "$@";
626     }
627     eval { unaltcargolock(1); 1; } or warn "$@";
628   }
629 }
630
631 sub consider_directories () {
632   return unless defined $oot_dir;
633   my $bsubdir = "../$oot_dir/$subdir";
634   return if stat $bsubdir;
635   die "$0: build directory $bsubdir inaccessible\n"
636     unless $!==ENOENT;
637   return if $cargo_lock_update; # will make it
638   die "$0: build directory $bsubdir does not exist, and not in Cargo.lock update mode!\n";
639 }
640
641 our $cleanup_cargo_lock;
642 sub makebackups () {
643   foreach my $mf (keys %manifests) {
644     link "$mf", "$mf.unnailed" or $!==EEXIST
645       or die "$self: make backup link $mf.unnailed: $!\n";
646   }
647
648   if (defined($alt_cargo_lock)) {
649     if (@alt_cargo_lock_stat) {
650       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
651         if $verbose>=3;
652       if (link $alt_cargo_lock, 'Cargo.lock') {
653         print STDERR " linked\n" if $verbose>=3;
654       } elsif ($! != EEXIST) {
655         print STDERR "\n" if $verbose>=3;
656         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
657       } else {
658         print STDERR "checking quality." if $verbose>=3;
659         my @lock_stat = stat 'Cargo.lock'
660           or die "$self: stat Cargo.lock (for alt check: $!\n";
661         same_file(\@alt_cargo_lock_stat, \@lock_stat)
662           or die
663 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
664       }
665       $cleanup_cargo_lock = 1;
666     } else {
667       $cleanup_cargo_lock = 1;
668       # If Cargo.lock exists and alt doesn't, that means either
669       # that a previous run was interrupted, or that the user has
670       # messed up.
671     }
672   }
673 }
674
675 sub nailed ($) {
676   my ($mf) = @_;
677   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
678   $nailed;
679 }    
680
681 sub install () {
682   my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
683     ? (stat _) : ();
684   foreach my $mf (keys %manifests) {
685     if (@our_unfound_stab) {
686       if (stat_exists $mf, "manifest in to-be-nailed directory") {
687         my @mf_stab = stat _ ;
688         if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
689           @our_unfound_stab = ();
690         }
691       }
692     }
693
694     my $nailing = "$mf.nailing~";
695     my $nailed = nailed($mf);
696     my ($use, $rm);
697     my $diff;
698     if (open NN, '<', $nailed) {
699       $diff = compare($nailing, \*NN);
700       die "$self: compare $nailing and $nailed: $!" if $diff<0;
701     } else {
702       $!==ENOENT or die "$self: check previous $nailed: $!\n";
703       $diff = 1;
704     }
705     if ($diff) {
706       $use = $nailing;
707       $rm  = $nailed;
708     } else {
709       $use = $nailed;
710       $rm  = $nailing;
711     }
712     rename $use, $mf or die "$self: install nailed $use: $!\n";
713     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
714     print STDERR "$self: nailed $mf\n" if $verbose>=3;
715   }
716
717   if (@our_unfound_stab) {
718     print STDERR
719  "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
720   }
721 }
722
723 sub invoke () {
724   my $r = system @ARGV;
725   if (!$r) {
726     return 0;
727   } elsif ($r<0) {
728     print STDERR "$self: could not execute $ARGV[0]: $!\n";
729     return 127;
730   } elsif ($r & 0xff00) {
731     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
732     return $r >> 8;
733   } else {
734     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
735     return 125;
736   }
737 }
738
739 sub cargo_lock_update_after () {
740   if ($cargo_lock_update) {
741     # avoids importing File::Copy and the error handling is about as good
742     $!=0; $?=0;
743     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
744     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
745     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
746   }
747 }
748
749 sub uninstall1 ($$) {
750   my ($mf, $enoentok) = @_;
751   my $unnailed = "$mf.unnailed";
752   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
753     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
754 }
755
756 sub unaltcargolock ($) {
757   my ($enoentok) = @_;
758   return unless $cleanup_cargo_lock;
759   die 'internal error!' unless defined $alt_cargo_lock;
760
761   # we ignore $enoentok because we don't know if one was supposed to
762   # have been created.
763
764   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
765  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
766
767   unlink 'Cargo.lock' or $!==ENOENT or die
768  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
769   # ^ this also helps clean up the stupid rename() corner case
770 }
771
772 sub uninstall () {
773   foreach my $mf (keys %manifests) {
774     my $nailed = nailed($mf);
775     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
776     uninstall1($mf,0);
777   }
778   unaltcargolock(0);
779 }
780
781 sub parse_args () {
782   my $is_cargo;
783
784   # Loop exit condition:
785   #   $is_cargo is set
786   #   @ARGV contains
787   #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
788   #    $is_cargo==0   <build-command>...
789
790  OPTS: for (;;) {
791     @ARGV or die "$self: need cargo subcommand\n";
792
793     $_ = shift @ARGV;
794     my $orgopt = $_;
795
796     my $not_a_nailing_opt = sub { # usage 1
797       unshift @ARGV, $orgopt;
798       unshift @ARGV, 'cargo';
799       $is_cargo = 1;
800       no warnings qw(exiting);
801       last OPTS;
802     };
803     $not_a_nailing_opt->() unless m{^-};
804     $not_a_nailing_opt->() if $_ eq '--';
805
806     if ($_ eq '---') { # usage 2 or 3
807       die "$self: --- must be followed by build command\n" unless @ARGV;
808       if ($ARGV[0] eq '--') { # usage 3
809         shift;
810         $is_cargo = 0;
811       } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
812         $is_cargo = 1;
813       } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
814         $is_cargo = 1;
815       } else {  # usage 3
816         $is_cargo = 0;
817       }
818       last;
819     }
820     if (m{^-[^-]}) {
821       while (m{^-.}) {
822         if (s{^-v}{-}) {
823           $verbose++;
824         } elsif (s{^-q}{-}) {
825           $verbose=0;
826         } elsif (s{^-n}{-}) {
827           $noact++;
828         } elsif (s{^-s(.+)}{-}s) {
829           $cargo_subcmd = $1;
830         } elsif (s{^-([uU])}{-}) {
831           $cargo_lock_update = $1=~m/[a-z]/;
832         } elsif (s{^-([cC])}{-}) {
833           $pass_options = $1=~m/[a-z]/;
834         } elsif (s{^-D}{-}) {
835           $dump++;
836         } elsif (s{^-T(.+)}{-}s) {
837           $target = $1;
838         } elsif (s{^-([oO])}{-}) {
839           $online = $1=~m/[a-z]/;
840         } else {
841           die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
842           $not_a_nailing_opt->();
843         }
844       }
845     } elsif (s{^--target=}{}) {
846       $target = $_;
847     } elsif (m{^--(on|off)line$}) {
848       $online = $1 eq 'on';
849     } elsif (s{^--subcommand-props=}{}) {
850       my @props = split /\,/, $_;
851       our %subcmd_prop_ok;
852       if (!%subcmd_prop_ok) {
853         foreach my $v (\@subcmd_xprops, values %subcmd_props) {
854           $subcmd_prop_ok{$_}=1 foreach @$v;
855         };
856       }
857       $subcmd_prop_ok{$_}
858         or die "$self: unknown subcommand property \`$_'\n"
859         foreach @props;
860       $cargo_subcmd = \@props;
861     } elsif (m{^--(no-)?cargo-lock-update}) {
862       $cargo_lock_update= !!$1;
863     } else {
864       $not_a_nailing_opt->();
865     }
866   }
867
868   $is_cargo // die;
869   @ARGV || die;
870
871   if ($is_cargo) {
872     @args_preface = shift @ARGV;
873     while (defined($_ = shift @ARGV)) {
874       if (!m{^-}) { unshift @ARGV, $_; last; }
875       if ($_ eq '--') { last; }
876       push @args_preface, $_;
877     }
878     @ARGV || die "$self: need cargo subcommand\n";
879     $cargo_subcmd //= $ARGV[0];
880     $pass_options //= 1;
881   } else {
882     $cargo_subcmd //= '';
883     $pass_options //= 0;
884   }
885   push @args_preface, shift @ARGV;
886
887   if (!ref($cargo_subcmd)) {
888     print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
889     $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
890   }
891
892   print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
893   my %cargo_subcmd;
894   $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
895   $cargo_subcmd = \%cargo_subcmd;
896 }
897
898 parse_args();
899 loadconfigs();
900 takelock();
901 readnail();
902 consider_alt_cargo_lock();
903 consider_oot();
904 readorigs();
905 calculate();
906 addargs();
907 consider_directories();
908 our @display_cmd = @ARGV;
909 oot_massage_cmdline();
910 setenvs();
911
912 if ($dump) {
913   eval '
914     use Data::Dumper;
915     print STDERR Dumper(\%manifests) if $dump>=2;
916     print STDERR Dumper(\%packagemap, \@ARGV,
917                         { src_absdir => $src_absdir,
918                           worksphere => $worksphere,
919                           subdir => $subdir,
920                           oot_dir => $oot_dir,
921                           oot_absdir => $oot_absdir,
922                           build_absdir => $build_absdir });
923   ' or die $@;
924 }
925
926 exit 0 if $noact;
927
928 $want_uninstall = 1;
929 makebackups();
930 install();
931
932 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
933   (scalar keys %manifests), (scalar keys %packagemap),
934   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
935   if $verbose;
936
937 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
938 my $estatus = invoke();
939
940 cargo_lock_update_after();
941
942 uninstall();
943 $want_uninstall = 0;
944
945 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
946
947 exit $estatus;