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