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