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