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