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