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