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