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