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