chiark / gitweb /
Allow for $post to be already set by linkdepth-specific code
[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         cd "$1"; shift;
622         mkdir -p -- "$1"; cd "$1"; shift; src="$1"; shift;
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     } else {
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     }
660     $pre .= <<'ENDLK' if $do_cargo_lock;
661         if test -e Cargo.lock; then
662           rm -f Cargo.lock;
663           cp -- "$src"/Cargo.lock .;
664         fi;
665 ENDLK
666     $post .= <<'ENDCLEAN' if $oot_clean && !$just_linkfarm;
667         clean;
668 ENDCLEAN
669   }
670   my $addpath = (cfg_uc qw(oot path_add)) //
671     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
672   $addpath =
673     !Types::Serialiser::is_bool $addpath ? $addpath           :
674     $addpath                             ? '$HOME/.cargo/bin' :
675                                            undef;
676   if (defined $addpath) {
677     $pre .= <<END
678         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
679         export PATH;
680 END
681   }
682   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
683   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
684
685   my $getuser = sub { cfgsn qw(oot user) };
686   my @command;
687   my $xe = $verbose >= 2 ? 'xe' : 'e';
688   my $sh_ec = sub {
689     if (!length $post) {
690       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
691     } else {
692       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
693     }
694     push @command, @ARGV;
695   };
696   my $command_sh = sub {
697     my $quoted = join ' ', map {
698       return $_ if !m/\W/;
699       s/\'/\'\\'\'/g;
700       "'$_'"
701     } @ARGV;
702     @command = @_, "set -${xe}; $pre $quoted; $post";
703   };
704   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
705     if $verbose;
706   if ($use eq 'really') {
707     my $user = $getuser->();
708     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
709     my $homedir = $pw[7];
710     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
711     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
712   } elsif ($use eq 'ssh') {
713     my $user = $getuser->();
714     $user .= '@localhost' unless $user =~ m/\@/;
715     $command_sh->('ssh',$user);
716     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
717   } elsif ($use eq 'command_args') {
718     my @c = cfgn_list qw(oot command);
719     $sh_ec->(@c);
720     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
721   } elsif ($use eq 'command_sh') {
722     my @c = cfgn_list qw(oot command);
723     $command_sh->(@c);
724     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
725   } elsif ($use eq 'null') {
726     $sh_ec->();
727   } else {
728     die "$self: oot.use mode $use not recognised\n";
729   }
730   die unless @command;
731   @ARGV = @command;
732 }
733
734 sub setenvs () {
735   $ENV{CARGO_MANIFEST_DIR} = $src_absdir unless $linkfarm_depth;
736   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
737   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
738   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
739   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
740   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
741 }
742
743 our $want_uninstall;
744
745 END {
746   if ($want_uninstall) {
747     local ($?);
748     foreach my $mf (keys %manifests) {
749       eval { uninstall1($mf,1); 1; } or warn "$@";
750     }
751     eval { unaltcargolock(1); 1; } or warn "$@";
752   }
753 }
754
755 sub consider_directories () {
756   return unless defined $oot_dir;
757   my $bsubdir = "../$oot_dir/$subdir";
758   return if stat $bsubdir;
759   die "$0: build directory $bsubdir inaccessible\n"
760     unless $!==ENOENT;
761   return if $cargo_lock_update; # will make it
762   die "$0: build directory $bsubdir does not exist, and not in Cargo.lock update mode!\n";
763 }
764
765 our $cleanup_cargo_lock;
766 sub makebackups () {
767   foreach my $mf (keys %manifests) {
768     link "$mf", "$mf.unnailed" or $!==EEXIST
769       or die "$self: make backup link $mf.unnailed: $!\n";
770   }
771
772   if (defined($alt_cargo_lock)) {
773     die 'internal error' unless $do_cargo_lock;
774     if (@alt_cargo_lock_stat) {
775       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
776         if $verbose>=3;
777       if (link $alt_cargo_lock, 'Cargo.lock') {
778         print STDERR " linked\n" if $verbose>=3;
779       } elsif ($! != EEXIST) {
780         print STDERR "\n" if $verbose>=3;
781         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
782       } else {
783         print STDERR "checking quality." if $verbose>=3;
784         my @lock_stat = stat 'Cargo.lock'
785           or die "$self: stat Cargo.lock (for alt check: $!\n";
786         same_file(\@alt_cargo_lock_stat, \@lock_stat)
787           or die
788 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
789       }
790       $cleanup_cargo_lock = 1;
791     } else {
792       $cleanup_cargo_lock = 1;
793       # If Cargo.lock exists and alt doesn't, that means either
794       # that a previous run was interrupted, or that the user has
795       # messed up.
796     }
797   }
798 }
799
800 sub nailed ($) {
801   my ($mf) = @_;
802   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
803   $nailed;
804 }    
805
806 sub install () {
807   my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
808     ? (stat _) : ();
809   foreach my $mf (keys %manifests) {
810     if (@our_unfound_stab) {
811       if (stat_exists $mf, "manifest in to-be-nailed directory") {
812         my @mf_stab = stat _ ;
813         if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
814           @our_unfound_stab = ();
815         }
816       }
817     }
818
819     my $nailing = "$mf.nailing~";
820     my $nailed = nailed($mf);
821     my ($use, $rm);
822     my $diff;
823     if (open NN, '<', $nailed) {
824       $diff = compare($nailing, \*NN);
825       die "$self: compare $nailing and $nailed: $!" if $diff<0;
826     } else {
827       $!==ENOENT or die "$self: check previous $nailed: $!\n";
828       $diff = 1;
829     }
830     if ($diff) {
831       $use = $nailing;
832       $rm  = $nailed;
833     } else {
834       $use = $nailed;
835       $rm  = $nailing;
836     }
837     rename $use, $mf or die "$self: install nailed $use: $!\n";
838     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
839     print STDERR "$self: nailed $mf\n" if $verbose>=3;
840   }
841
842   if (@our_unfound_stab && $do_nail) {
843     print STDERR
844  "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
845   }
846 }
847
848 sub invoke () {
849   my $r = system @ARGV;
850   if (!$r) {
851     return 0;
852   } elsif ($r<0) {
853     print STDERR "$self: could not execute $ARGV[0]: $!\n";
854     return 127;
855   } elsif ($r & 0xff00) {
856     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
857     return $r >> 8;
858   } else {
859     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
860     return 125;
861   }
862 }
863
864 sub cargo_lock_update_after () {
865   if ($do_cargo_lock && $cargo_lock_update && !$just_linkfarm) {
866     # avoids importing File::Copy and the error handling is about as good
867     $!=0; $?=0;
868     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
869     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
870     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
871   }
872 }
873
874 sub uninstall1 ($$) {
875   my ($mf, $enoentok) = @_;
876   my $unnailed = "$mf.unnailed";
877   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
878     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
879 }
880
881 sub unaltcargolock ($) {
882   my ($enoentok) = @_;
883   return unless $cleanup_cargo_lock;
884   die 'internal error!' unless $do_cargo_lock && defined $alt_cargo_lock;
885
886   # we ignore $enoentok because we don't know if one was supposed to
887   # have been created.
888
889   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
890  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
891
892   unlink 'Cargo.lock' or $!==ENOENT or die
893  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
894   # ^ this also helps clean up the stupid rename() corner case
895 }
896
897 sub uninstall () {
898   foreach my $mf (keys %manifests) {
899     my $nailed = nailed($mf);
900     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
901     uninstall1($mf,0);
902   }
903   unaltcargolock(0);
904 }
905
906 sub parse_args () {
907   my $is_cargo;
908
909   # Loop exit condition:
910   #   $is_cargo is set
911   #   @ARGV contains
912   #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
913   #    $is_cargo==0   <build-command>...
914
915  OPTS: for (;;) {
916     if (!@ARGV) {
917       die "$self: need cargo subcommand\n"
918         unless $noact || $just_linkfarm;;
919       push @ARGV, "CARGO-SUBCOMMAND"; # dummy, user may see it
920     }
921
922     $_ = shift @ARGV;
923     my $orgopt = $_;
924
925     my $not_a_nailing_opt = sub { # usage 1
926       unshift @ARGV, $orgopt;
927       unshift @ARGV, 'cargo';
928       $is_cargo = 1;
929       no warnings qw(exiting);
930       last OPTS;
931     };
932     $not_a_nailing_opt->() unless m{^-};
933     $not_a_nailing_opt->() if $_ eq '--';
934
935     if ($_ eq '---') { # usage 2 or 3
936       if (!@ARGV) {
937         die "$self: --- must be followed by build command\n" unless $noact;
938         push @ARGV, 'BUILD-COMMAND';
939       }
940       if ($ARGV[0] eq '--') { # usage 3
941         shift;
942         $is_cargo = 0;
943       } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
944         $is_cargo = 1;
945       } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
946         $is_cargo = 1;
947       } else {  # usage 3
948         $is_cargo = 0;
949       }
950       last;
951     }
952     if (m{^-[^-]}) {
953       while (m{^-.}) {
954         if (s{^-h}{-}) {
955           print_usage();
956         } elsif (s{^-v}{-}) {
957           $verbose++;
958         } elsif (s{^-q}{-}) {
959           $verbose=0;
960         } elsif (s{^-n}{-}) {
961           $noact++;
962         } elsif (s{^-s(.+)}{-}s) {
963           $cargo_subcmd = $1;
964         } elsif (s{^-([uU])}{-}) {
965           $cargo_lock_update = $1=~m/[a-z]/;
966         } elsif (s{^-([cC])}{-}) {
967           $pass_options = $1=~m/[a-z]/;
968         } elsif (s{^-D}{-}) {
969           $dump++;
970         } elsif (s{^-T(.+)}{-}s) {
971           $target = $1;
972         } elsif (s{^-([oO])}{-}) {
973           $online = $1=~m/[a-z]/;
974         } else {
975           die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
976           $not_a_nailing_opt->();
977         }
978       }
979     } elsif (s{^--help$}{}) {
980       print_usage();
981     } elsif (s{^--(?:doc|man|manual)?$}{}) {
982       show_manual();
983     } elsif (s{^--target=}{}) {
984       $target = $_;
985     } elsif (m{^--(on|off)line$}) {
986       $online = $1 eq 'on';
987     } elsif (m{^--just-linkfarm(?:=(shallow|git|full))?$}) {
988       $just_linkfarm = 1;
989       $linkfarm_depth = 1 if $1;
990       $cargo_lock_update= 1; # will set $linkfarm_detph to 1 by default
991     } elsif (m{^--linkfarm(?:=(no|shallow|git|full))?$}) {
992       $linkfarm_depth = $1 || 'git';
993     } elsif (m{^--just-run$}) {
994       $do_nail = $do_cargo_lock = $do_lock = 0;
995     } elsif (m{^--(clean|keep)-linkfarm$}) {
996       $oot_clean = $1 eq 'clean';
997     } elsif (m{^--(no)?-nail$}) {
998       $do_nail = !$1;
999     } elsif (m{^--(no)?-cargo-lock-manip$}) {
1000       $do_cargo_lock = !$1;
1001     } elsif (m{^--(no)?-concurrency-lock$}) {
1002       $do_lock = !$1;
1003     } elsif (m{^--leave-nailed$}) {
1004       $leave_nailed = 1;
1005     } elsif (s{^--subcommand-props=}{}) {
1006       my @props = split /\,/, $_;
1007       our %subcmd_prop_ok;
1008       if (!%subcmd_prop_ok) {
1009         foreach my $v (\@subcmd_xprops, values %subcmd_props) {
1010           $subcmd_prop_ok{$_}=1 foreach @$v;
1011         };
1012       }
1013       $subcmd_prop_ok{$_}
1014         or die "$self: unknown subcommand property \`$_'\n"
1015         foreach @props;
1016       $cargo_subcmd = \@props;
1017     } elsif (m{^--(no-)?cargo-lock-update}) {
1018       $cargo_lock_update= !!$1;
1019     } else {
1020       $not_a_nailing_opt->();
1021     }
1022   }
1023
1024   $is_cargo // die;
1025   @ARGV || die;
1026
1027   if ($is_cargo) {
1028     @args_preface = shift @ARGV;
1029     while (defined($_ = shift @ARGV)) {
1030       if (!m{^-}) { unshift @ARGV, $_; last; }
1031       if ($_ eq '--') { last; }
1032       push @args_preface, $_;
1033     }
1034     @ARGV || die "$self: need cargo subcommand\n";
1035     $cargo_subcmd //= $ARGV[0];
1036     $pass_options //= 1;
1037   } else {
1038     $cargo_subcmd //= '';
1039     $pass_options //= 0;
1040   }
1041   push @args_preface, shift @ARGV;
1042
1043   if (!ref($cargo_subcmd)) {
1044     print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
1045     $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
1046   }
1047
1048   print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
1049   my %cargo_subcmd;
1050   $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
1051   $cargo_subcmd = \%cargo_subcmd;
1052 }
1053
1054 parse_args();
1055 loadconfigs();
1056 readnail();
1057 takelock();
1058 consider_alt_cargo_lock();
1059 consider_oot();
1060 readorigs();
1061 calculate();
1062 addargs();
1063 consider_directories();
1064 our @display_cmd = @ARGV;
1065 oot_massage_cmdline();
1066 setenvs();
1067
1068 if ($dump) {
1069   eval '
1070     use Data::Dumper;
1071     print STDERR Dumper(\%manifests) if $dump>=2;
1072     print STDERR Dumper(\%packagemap, \@ARGV,
1073                         { src_absdir => $src_absdir,
1074                           worksphere => $worksphere,
1075                           subdir => $subdir,
1076                           oot_dir => $oot_dir,
1077                           oot_absdir => $oot_absdir,
1078                           build_absdir => $build_absdir });
1079   ' or die $@;
1080 }
1081
1082 exit 0 if $noact;
1083
1084 $want_uninstall = !$leave_nailed;
1085 makebackups();
1086 install();
1087
1088 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
1089   (scalar keys %manifests), (scalar keys %packagemap),
1090   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
1091   if $verbose && $do_nail;
1092
1093 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
1094 my $estatus = invoke();
1095
1096 cargo_lock_update_after();
1097
1098 uninstall() unless $leave_nailed;
1099 $want_uninstall = 0;
1100
1101 print STDERR "$self: ".($do_nail ? "unnailed" : "finished")
1102              .".  status $estatus.\n" if $verbose;
1103
1104 exit $estatus;