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