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