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