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