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