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