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