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