chiark / gitweb /
nailing-cargo: oot_massage_cmdline: Initialise $pre and $post
[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         cp -- "$1"/Cargo.toml
514 END
515     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
516               "$1"/Cargo.lock
517 ENDLK
518     $pre .= <<'ENDCP';
519                               .;
520 ENDCP
521     $pre .= <<'ENDPRE';
522         shift;
523         mkdir -p src; >src/lib.rs; >build.rs
524 ENDPRE
525     $post = <<'ENDPOST';
526         rm -r src Cargo.toml build.rs;
527 ENDPOST
528   }
529   my $addpath = (cfg_uc qw(oot path_add)) //
530     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
531   $addpath =
532     !Types::Serialiser::is_bool $addpath ? $addpath           :
533     $addpath                             ? '$HOME/.cargo/bin' :
534                                            undef;
535   if (defined $addpath) {
536     $pre .= <<END
537         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
538         export PATH;
539 END
540   }
541   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
542   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
543
544   my $getuser = sub { cfgsn qw(oot user) };
545   my @command;
546   my $xe = $verbose >= 2 ? 'xe' : 'e';
547   my $sh_ec = sub {
548     if (!length $post) {
549       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
550     } else {
551       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
552     }
553     push @command, @ARGV;
554   };
555   my $command_sh = sub {
556     my $quoted = join ' ', map {
557       return $_ if !m/\W/;
558       s/\'/\'\\'\'/g;
559       "'$_'"
560     } @ARGV;
561     @command = @_, "set -${xe}; $pre $quoted; $post";
562   };
563   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
564     if $verbose;
565   if ($use eq 'really') {
566     my $user = $getuser->();
567     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
568     my $homedir = $pw[7];
569     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
570     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
571   } elsif ($use eq 'ssh') {
572     my $user = $getuser->();
573     $user .= '@localhost' unless $user =~ m/\@/;
574     $command_sh->('ssh',$user);
575     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
576   } elsif ($use eq 'command_args') {
577     my @c = cfgn_list qw(oot command);
578     $sh_ec->(@c);
579     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
580   } elsif ($use eq 'command_sh') {
581     my @c = cfgn_list qw(oot command);
582     $command_sh->(@c);
583     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
584   } elsif ($use eq 'null') {
585     $sh_ec->();
586   } else {
587     die "$self: oot.use mode $use not recognised\n";
588   }
589   die unless @command;
590   @ARGV = @command;
591 }
592
593 sub setenvs () {
594   $ENV{CARGO_MANIFEST_DIR} = $src_absdir;
595   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
596   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
597   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
598   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
599   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
600 }
601
602 our $want_uninstall;
603
604 END {
605   if ($want_uninstall) {
606     local ($?);
607     foreach my $mf (keys %manifests) {
608       eval { uninstall1($mf,1); 1; } or warn "$@";
609     }
610     eval { unaltcargolock(1); 1; } or warn "$@";
611   }
612 }
613
614 sub consider_directories () {
615   return unless defined $oot_dir;
616   my $bsubdir = "../$oot_dir/$subdir";
617   return if stat $bsubdir;
618   die "$0: build directory $bsubdir inaccessible\n"
619     unless $!==ENOENT;
620   return if $cargo_lock_update; # will make it
621   die "$0: build directory $bsubdir does not exist, and not in Cargo.lock update mode!\n";
622 }
623
624 our $cleanup_cargo_lock;
625 sub makebackups () {
626   foreach my $mf (keys %manifests) {
627     link "$mf", "$mf.unnailed" or $!==EEXIST
628       or die "$self: make backup link $mf.unnailed: $!\n";
629   }
630
631   if (defined($alt_cargo_lock)) {
632     if (@alt_cargo_lock_stat) {
633       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
634         if $verbose>=3;
635       if (link $alt_cargo_lock, 'Cargo.lock') {
636         print STDERR " linked\n" if $verbose>=3;
637       } elsif ($! != EEXIST) {
638         print STDERR "\n" if $verbose>=3;
639         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
640       } else {
641         print STDERR "checking quality." if $verbose>=3;
642         my @lock_stat = stat 'Cargo.lock'
643           or die "$self: stat Cargo.lock (for alt check: $!\n";
644         same_file(\@alt_cargo_lock_stat, \@lock_stat)
645           or die
646 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
647       }
648       $cleanup_cargo_lock = 1;
649     } else {
650       $cleanup_cargo_lock = 1;
651       # If Cargo.lock exists and alt doesn't, that means either
652       # that a previous run was interrupted, or that the user has
653       # messed up.
654     }
655   }
656 }
657
658 sub nailed ($) {
659   my ($mf) = @_;
660   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
661   $nailed;
662 }    
663
664 sub install () {
665   my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
666     ? (stat _) : ();
667   foreach my $mf (keys %manifests) {
668     if (@our_unfound_stab) {
669       if (stat_exists $mf, "manifest in to-be-nailed directory") {
670         my @mf_stab = stat _ ;
671         if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
672           @our_unfound_stab = ();
673         }
674       }
675     }
676
677     my $nailing = "$mf.nailing~";
678     my $nailed = nailed($mf);
679     my ($use, $rm);
680     my $diff;
681     if (open NN, '<', $nailed) {
682       $diff = compare($nailing, \*NN);
683       die "$self: compare $nailing and $nailed: $!" if $diff<0;
684     } else {
685       $!==ENOENT or die "$self: check previous $nailed: $!\n";
686       $diff = 1;
687     }
688     if ($diff) {
689       $use = $nailing;
690       $rm  = $nailed;
691     } else {
692       $use = $nailed;
693       $rm  = $nailing;
694     }
695     rename $use, $mf or die "$self: install nailed $use: $!\n";
696     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
697     print STDERR "$self: nailed $mf\n" if $verbose>=3;
698   }
699
700   if (@our_unfound_stab) {
701     print STDERR
702  "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
703   }
704 }
705
706 sub invoke () {
707   my $r = system @ARGV;
708   if (!$r) {
709     return 0;
710   } elsif ($r<0) {
711     print STDERR "$self: could not execute $ARGV[0]: $!\n";
712     return 127;
713   } elsif ($r & 0xff00) {
714     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
715     return $r >> 8;
716   } else {
717     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
718     return 125;
719   }
720 }
721
722 sub cargo_lock_update_after () {
723   if ($cargo_lock_update) {
724     # avoids importing File::Copy and the error handling is about as good
725     $!=0; $?=0;
726     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
727     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
728     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
729   }
730 }
731
732 sub uninstall1 ($$) {
733   my ($mf, $enoentok) = @_;
734   my $unnailed = "$mf.unnailed";
735   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
736     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
737 }
738
739 sub unaltcargolock ($) {
740   my ($enoentok) = @_;
741   return unless $cleanup_cargo_lock;
742   die 'internal error!' unless defined $alt_cargo_lock;
743
744   # we ignore $enoentok because we don't know if one was supposed to
745   # have been created.
746
747   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
748  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
749
750   unlink 'Cargo.lock' or $!==ENOENT or die
751  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
752   # ^ this also helps clean up the stupid rename() corner case
753 }
754
755 sub uninstall () {
756   foreach my $mf (keys %manifests) {
757     my $nailed = nailed($mf);
758     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
759     uninstall1($mf,0);
760   }
761   unaltcargolock(0);
762 }
763
764 sub parse_args () {
765   my $is_cargo;
766
767   # Loop exit condition:
768   #   $is_cargo is set
769   #   @ARGV contains
770   #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
771   #    $is_cargo==0   <build-command>...
772
773  OPTS: for (;;) {
774     @ARGV or die "$self: need cargo subcommand\n";
775
776     $_ = shift @ARGV;
777     my $orgopt = $_;
778
779     my $not_a_nailing_opt = sub { # usage 1
780       unshift @ARGV, $orgopt;
781       unshift @ARGV, 'cargo';
782       $is_cargo = 1;
783       no warnings qw(exiting);
784       last OPTS;
785     };
786     $not_a_nailing_opt->() unless m{^-};
787     $not_a_nailing_opt->() if $_ eq '--';
788
789     if ($_ eq '---') { # usage 2 or 3
790       die "$self: --- must be followed by build command\n" unless @ARGV;
791       if ($ARGV[0] eq '--') { # usage 3
792         shift;
793         $is_cargo = 0;
794       } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
795         $is_cargo = 1;
796       } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
797         $is_cargo = 1;
798       } else {  # usage 3
799         $is_cargo = 0;
800       }
801       last;
802     }
803     if (m{^-[^-]}) {
804       while (m{^-.}) {
805         if (s{^-v}{-}) {
806           $verbose++;
807         } elsif (s{^-q}{-}) {
808           $verbose=0;
809         } elsif (s{^-n}{-}) {
810           $noact++;
811         } elsif (s{^-s(.+)}{-}s) {
812           $cargo_subcmd = $1;
813         } elsif (s{^-([uU])}{-}) {
814           $cargo_lock_update = $1=~m/[a-z]/;
815         } elsif (s{^-([cC])}{-}) {
816           $pass_options = $1=~m/[a-z]/;
817         } elsif (s{^-D}{-}) {
818           $dump++;
819         } elsif (s{^-T(.+)}{-}s) {
820           $target = $1;
821         } elsif (s{^-([oO])}{-}) {
822           $online = $1=~m/[a-z]/;
823         } else {
824           die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
825           $not_a_nailing_opt->();
826         }
827       }
828     } elsif (s{^--target=}{}) {
829       $target = $_;
830     } elsif (m{^--(on|off)line$}) {
831       $online = $1 eq 'on';
832     } elsif (s{^--subcommand-props=}{}) {
833       my @props = split /\,/, $_;
834       our %subcmd_prop_ok;
835       if (!%subcmd_prop_ok) {
836         foreach my $v (\@subcmd_xprops, values %subcmd_props) {
837           $subcmd_prop_ok{$_}=1 foreach @$v;
838         };
839       }
840       $subcmd_prop_ok{$_}
841         or die "$self: unknown subcommand property \`$_'\n"
842         foreach @props;
843       $cargo_subcmd = \@props;
844     } elsif (m{^--(no-)?cargo-lock-update}) {
845       $cargo_lock_update= !!$1;
846     } else {
847       $not_a_nailing_opt->();
848     }
849   }
850
851   $is_cargo // die;
852   @ARGV || die;
853
854   if ($is_cargo) {
855     @args_preface = shift @ARGV;
856     while (defined($_ = shift @ARGV)) {
857       if (!m{^-}) { unshift @ARGV, $_; last; }
858       if ($_ eq '--') { last; }
859       push @args_preface, $_;
860     }
861     @ARGV || die "$self: need cargo subcommand\n";
862     $cargo_subcmd //= $ARGV[0];
863     $pass_options //= 1;
864   } else {
865     $cargo_subcmd //= '';
866     $pass_options //= 0;
867   }
868   push @args_preface, shift @ARGV;
869
870   if (!ref($cargo_subcmd)) {
871     print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
872     $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
873   }
874
875   print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
876   my %cargo_subcmd;
877   $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
878   $cargo_subcmd = \%cargo_subcmd;
879 }
880
881 parse_args();
882 loadconfigs();
883 takelock();
884 readnail();
885 consider_alt_cargo_lock();
886 consider_oot();
887 readorigs();
888 calculate();
889 addargs();
890 consider_directories();
891 our @display_cmd = @ARGV;
892 oot_massage_cmdline();
893 setenvs();
894
895 if ($dump) {
896   eval '
897     use Data::Dumper;
898     print STDERR Dumper(\%manifests) if $dump>=2;
899     print STDERR Dumper(\%packagemap, \@ARGV,
900                         { src_absdir => $src_absdir,
901                           worksphere => $worksphere,
902                           subdir => $subdir,
903                           oot_dir => $oot_dir,
904                           oot_absdir => $oot_absdir,
905                           build_absdir => $build_absdir });
906   ' or die $@;
907 }
908
909 exit 0 if $noact;
910
911 $want_uninstall = 1;
912 makebackups();
913 install();
914
915 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
916   (scalar keys %manifests), (scalar keys %packagemap),
917   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
918   if $verbose;
919
920 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
921 my $estatus = invoke();
922
923 cargo_lock_update_after();
924
925 uninstall();
926 $want_uninstall = 0;
927
928 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
929
930 exit $estatus;