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