chiark / gitweb /
nailing-cargo: Chase path dependencies
[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     foreach my $dep (get_dependency_tables $toml) {
341       next unless defined $dep->{path};
342       queue_referenced_path($dep->{path}, $org_subdir,
343                             "dependency of $subdir, $why");
344     }
345     return ($p, $ws);
346   }
347   return undef;
348 }
349
350 sub queue_workspace_members ($$) {
351   my ($subdir, $org_subdir, $ws_toml, $what) = @_;
352   # We need to (more or less) reimplement the cargo workspace
353   # membership algorithm (see the "workspaces" section of the cargo
354   # reference).  How tiresome.
355   #
356   # It's not quite the same for us because we aren't interested in
357   # whether cargo thinks things are "in the workspace".  But we do
358   # need to do the automatic discover.
359
360   my @include = @{ $ws_toml->{members} // [ ] };
361   my $exclude = $ws_toml->{exclude} // [ ];
362
363   my @exclude = map {
364     s/[^*?0-9a-zA-Z_]/\\$&/g;
365     s/\?/./g;
366     s/\*/.*/g;
367   } @$exclude;
368
369   foreach my $spec (@include) {
370     if ($spec =~ m{^/}) {
371       print STDERR
372         "$self: warning: absolute workspace member $spec in $what (not nailing, but cargo will probably use it)\n";
373       next;
374     }
375     my $spec_glob = "../$subdir/$spec";
376     my $globflags = GLOB_ERR|GLOB_BRACE|GLOB_NOMAGIC;
377     foreach my $globent (bsd_glob($spec_glob, $globflags)) {
378       next if grep { $globent =~ m{^$_$} } @exclude;
379       queue_referenced_path($globent, $org_subdir,
380                             "member of workspace $what");
381     }
382   }
383 }
384
385 sub queue_referenced_path ($$$) {
386   my ($spec_path, $org_subdir, $why) = @_;
387   open REALPATH, "-|",
388     qw(realpath), "--relative-to=../$org_subdir", "--", $spec_path
389     or die "$self: fork/pipe/exec for realpath(1)\n";
390   my $rel_path = do { local $/=undef; <REALPATH>; };
391   $?=0; $!=0;
392   my $r = close(REALPATH);
393   die "$self: reap realpath: $!\n" if $!;
394   if (!chomp($rel_path) or $?) {
395     print STDERR
396  "$self: warning: failed to determine realpath for $spec_path in $org_subdir (exit code $?)\n";
397     return;
398   }
399   if ($rel_path =~ m{^\.\./} or $rel_path eq '..') {
400     print STDERR
401       "$self: warning: $spec_path ($why) points outside $org_subdir, not following so not nailing (although cargo probably will follow it)\n";
402     return;
403   }
404
405   my $q_subdir = "$org_subdir/$rel_path";
406   print STDERR "$self: making a note to look at $q_subdir, $why)\n"
407     if $verbose >= 4;
408
409   push @queued_paths, [ "$q_subdir", $org_subdir, $why ];
410 }
411
412 sub readorigs () {
413   foreach my $p (keys %{ $nail->{packages} }) {
414     my $v = $nail->{packages}{$p};
415     my $subdir = ref($v) ? $v->{subdir} : $v;
416     my ($gotpackage, $ws) = read_manifest($subdir, $subdir, "from [packages]");
417     $gotpackage //= '<nothing!>';
418     if ($gotpackage ne $p) {
419       print STDERR
420  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
421     }
422     die if defined $packagemap{$p};
423     $packagemap{$p} = [ $subdir, $subdir ];
424   }
425   foreach my $subdir (@{ $nail->{subdirs} }) {
426     my ($gotpackage,$ws) = read_manifest($subdir, $subdir, "from [subdirs]");
427     if (!defined $gotpackage) {
428       print STDERR
429  "$self: warning: ignoring subdir $subdir which has no (suitable) Cargo.toml\n"
430         unless $ws;
431       next;
432     }
433     $packagemap{$gotpackage} //= [ $subdir, $subdir ];
434   }
435   while (my ($subdir, $org_subdir, $why) = @{ shift @queued_paths or [] }) {
436     next if $manifests{"../$subdir/Cargo.toml"};
437     my ($gotpackage, $ws) = read_manifest($subdir, $org_subdir, $why);
438     next unless $gotpackage;
439     $packagemap{$gotpackage} //= [ $subdir, $org_subdir ];
440   }
441 }
442
443 sub calculate () {
444   foreach my $p (sort keys %packagemap) {
445     print STDERR "$self: package $p in $packagemap{$p}[0]\n" if $verbose>=2;
446   }
447   foreach my $mf (keys %manifests) {
448     my ($toml, $mf_org_subdir) = @{ $manifests{$mf} };
449     foreach my $deps (get_dependency_tables $toml) {
450       next unless $deps;
451       foreach my $p (keys %packagemap) {
452         my $info = $deps->{$p};
453         next unless defined $info;
454         next if $packagemap{$p}[1] eq $mf_org_subdir;
455         $deps->{$p} = $info = { } unless ref $info;
456         my $oldpath = $info->{path};
457         delete $info->{version};
458         my $newpath = $worksphere.'/'.$packagemap{$p}[0];
459         print STDERR "in $mf set $p path=$newpath (was ".
460           ($oldpath // '<unset>').")\n"
461           if $verbose >= 4;
462         $info->{path} = $newpath;
463         delete $info->{git};
464         delete $info->{branch};
465       }
466     }
467     my $nailing = "$mf.nailing~";
468     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
469     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
470     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
471     close N or die "$self: close new $nailing: $!\n";
472   }
473 }
474
475 sub addargs () {
476   if (!defined $online) {
477     $_ = cfg_uc qw(misc online);
478     if (!defined $_) {
479     } elsif (Types::Serialiser::is_bool $_) {
480       $online = $_;
481     } elsif (ref $_) {
482     } elsif (m/^a/) {
483       $online = undef;
484     } elsif (m/^[1ty]/) { # allow booleanish strings
485       $online = 1;        # for less user frustration
486     } elsif (m/^[0fn]/) {
487       $online = 0;
488     } else {
489       badcfg qw(misc online), "expected boolean or 'auto', found '$_'";
490     }
491   }
492   $online //= 1 if subcmd_p('online');
493   $online //= 0;
494
495   $cargo_lock_update //= subcmd_p('lock-update');
496
497   our @add;
498
499   if (!$cargo_lock_update) {
500     push @add, qw(--locked) unless subcmd_p('!locked');
501     if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
502       my $cargotoml = "${src_absdir}/Cargo.toml";
503       push @args_preface, "--manifest-path=$cargotoml" if $pass_options;
504       push @add, qw(--target-dir=target) unless subcmd_p('!target-dir');
505     }
506   }
507
508   if (defined($target) && !subcmd_p('!target')) {
509     if ($target =~ m{^[A-Z]}) {
510       $target = (cfgs 'arch', $target) // $archmap{$target}
511         // die "$self: --target=$target alias specified; not in cfg or map\n";
512     }
513     push @add, "--target=$target";
514   }
515
516   push @add, "--offline" unless $online || subcmd_p('!offline');
517
518   push @args_preface, @add if $pass_options;
519   die if grep { m/ / } @add;
520   $ENV{NAILINGCARGO_CARGO_OPTIONS} = "@add";
521
522   unshift @ARGV, @args_preface;
523 }
524
525 our $build_absdir; # .../Build/<subdir>
526
527 sub oot_massage_cmdline () {
528   return unless defined $oot_dir;
529
530   my $use = cfgs qw(oot use);
531   $use // die "$self: out-of-tree build, but \`oot.use' not configured\n";
532   $build_absdir = "$oot_absdir/$subdir";
533
534   my ($pre,$post) = ('','');
535   my @xargs;
536   if (!$cargo_lock_update) {
537     push @xargs, $build_absdir;
538     ($pre, $post) = ('cd "$1"; shift; ', '');
539   } else {
540     push @xargs, $oot_absdir, $subdir, $src_absdir;
541     $pre =  <<'END';
542         cd "$1"; shift;
543         mkdir -p -- "$1"; cd "$1"; shift;
544         clean () { find -lname "$1/*" -print0 | xargs -0r rm --; }; clean;
545         find "$1" -maxdepth 1 \! -name Cargo.lock -print0 | xargs -0r -I_ ln -sf -- _ .;
546 END
547     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
548         rm -f Cargo.lock;
549         cp -- "$1"/Cargo.lock .;
550 ENDLK
551     $pre .= <<'ENDPRE';
552         shift;
553 ENDPRE
554 #    $post = <<'ENDCLEAN';
555 #        clean;
556 #ENDCLEAN
557   }
558   my $addpath = (cfg_uc qw(oot path_add)) //
559     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
560   $addpath =
561     !Types::Serialiser::is_bool $addpath ? $addpath           :
562     $addpath                             ? '$HOME/.cargo/bin' :
563                                            undef;
564   if (defined $addpath) {
565     $pre .= <<END
566         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
567         export PATH;
568 END
569   }
570   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
571   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
572
573   my $getuser = sub { cfgsn qw(oot user) };
574   my @command;
575   my $xe = $verbose >= 2 ? 'xe' : 'e';
576   my $sh_ec = sub {
577     if (!length $post) {
578       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
579     } else {
580       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
581     }
582     push @command, @ARGV;
583   };
584   my $command_sh = sub {
585     my $quoted = join ' ', map {
586       return $_ if !m/\W/;
587       s/\'/\'\\'\'/g;
588       "'$_'"
589     } @ARGV;
590     @command = @_, "set -${xe}; $pre $quoted; $post";
591   };
592   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
593     if $verbose;
594   if ($use eq 'really') {
595     my $user = $getuser->();
596     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
597     my $homedir = $pw[7];
598     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
599     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
600   } elsif ($use eq 'ssh') {
601     my $user = $getuser->();
602     $user .= '@localhost' unless $user =~ m/\@/;
603     $command_sh->('ssh',$user);
604     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
605   } elsif ($use eq 'command_args') {
606     my @c = cfgn_list qw(oot command);
607     $sh_ec->(@c);
608     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
609   } elsif ($use eq 'command_sh') {
610     my @c = cfgn_list qw(oot command);
611     $command_sh->(@c);
612     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
613   } elsif ($use eq 'null') {
614     $sh_ec->();
615   } else {
616     die "$self: oot.use mode $use not recognised\n";
617   }
618   die unless @command;
619   @ARGV = @command;
620 }
621
622 sub setenvs () {
623   $ENV{CARGO_MANIFEST_DIR} = $src_absdir;
624   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
625   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
626   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
627   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
628   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
629 }
630
631 our $want_uninstall;
632
633 END {
634   if ($want_uninstall) {
635     local ($?);
636     foreach my $mf (keys %manifests) {
637       eval { uninstall1($mf,1); 1; } or warn "$@";
638     }
639     eval { unaltcargolock(1); 1; } or warn "$@";
640   }
641 }
642
643 sub consider_directories () {
644   return unless defined $oot_dir;
645   my $bsubdir = "../$oot_dir/$subdir";
646   return if stat $bsubdir;
647   die "$0: build directory $bsubdir inaccessible\n"
648     unless $!==ENOENT;
649   return if $cargo_lock_update; # will make it
650   die "$0: build directory $bsubdir does not exist, and not in Cargo.lock update mode!\n";
651 }
652
653 our $cleanup_cargo_lock;
654 sub makebackups () {
655   foreach my $mf (keys %manifests) {
656     link "$mf", "$mf.unnailed" or $!==EEXIST
657       or die "$self: make backup link $mf.unnailed: $!\n";
658   }
659
660   if (defined($alt_cargo_lock)) {
661     if (@alt_cargo_lock_stat) {
662       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
663         if $verbose>=3;
664       if (link $alt_cargo_lock, 'Cargo.lock') {
665         print STDERR " linked\n" if $verbose>=3;
666       } elsif ($! != EEXIST) {
667         print STDERR "\n" if $verbose>=3;
668         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
669       } else {
670         print STDERR "checking quality." if $verbose>=3;
671         my @lock_stat = stat 'Cargo.lock'
672           or die "$self: stat Cargo.lock (for alt check: $!\n";
673         same_file(\@alt_cargo_lock_stat, \@lock_stat)
674           or die
675 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
676       }
677       $cleanup_cargo_lock = 1;
678     } else {
679       $cleanup_cargo_lock = 1;
680       # If Cargo.lock exists and alt doesn't, that means either
681       # that a previous run was interrupted, or that the user has
682       # messed up.
683     }
684   }
685 }
686
687 sub nailed ($) {
688   my ($mf) = @_;
689   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
690   $nailed;
691 }    
692
693 sub install () {
694   my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
695     ? (stat _) : ();
696   foreach my $mf (keys %manifests) {
697     if (@our_unfound_stab) {
698       if (stat_exists $mf, "manifest in to-be-nailed directory") {
699         my @mf_stab = stat _ ;
700         if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
701           @our_unfound_stab = ();
702         }
703       }
704     }
705
706     my $nailing = "$mf.nailing~";
707     my $nailed = nailed($mf);
708     my ($use, $rm);
709     my $diff;
710     if (open NN, '<', $nailed) {
711       $diff = compare($nailing, \*NN);
712       die "$self: compare $nailing and $nailed: $!" if $diff<0;
713     } else {
714       $!==ENOENT or die "$self: check previous $nailed: $!\n";
715       $diff = 1;
716     }
717     if ($diff) {
718       $use = $nailing;
719       $rm  = $nailed;
720     } else {
721       $use = $nailed;
722       $rm  = $nailing;
723     }
724     rename $use, $mf or die "$self: install nailed $use: $!\n";
725     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
726     print STDERR "$self: nailed $mf\n" if $verbose>=3;
727   }
728
729   if (@our_unfound_stab) {
730     print STDERR
731  "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
732   }
733 }
734
735 sub invoke () {
736   my $r = system @ARGV;
737   if (!$r) {
738     return 0;
739   } elsif ($r<0) {
740     print STDERR "$self: could not execute $ARGV[0]: $!\n";
741     return 127;
742   } elsif ($r & 0xff00) {
743     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
744     return $r >> 8;
745   } else {
746     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
747     return 125;
748   }
749 }
750
751 sub cargo_lock_update_after () {
752   if ($cargo_lock_update) {
753     # avoids importing File::Copy and the error handling is about as good
754     $!=0; $?=0;
755     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
756     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
757     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
758   }
759 }
760
761 sub uninstall1 ($$) {
762   my ($mf, $enoentok) = @_;
763   my $unnailed = "$mf.unnailed";
764   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
765     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
766 }
767
768 sub unaltcargolock ($) {
769   my ($enoentok) = @_;
770   return unless $cleanup_cargo_lock;
771   die 'internal error!' unless defined $alt_cargo_lock;
772
773   # we ignore $enoentok because we don't know if one was supposed to
774   # have been created.
775
776   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
777  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
778
779   unlink 'Cargo.lock' or $!==ENOENT or die
780  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
781   # ^ this also helps clean up the stupid rename() corner case
782 }
783
784 sub uninstall () {
785   foreach my $mf (keys %manifests) {
786     my $nailed = nailed($mf);
787     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
788     uninstall1($mf,0);
789   }
790   unaltcargolock(0);
791 }
792
793 sub parse_args () {
794   my $is_cargo;
795
796   # Loop exit condition:
797   #   $is_cargo is set
798   #   @ARGV contains
799   #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
800   #    $is_cargo==0   <build-command>...
801
802  OPTS: for (;;) {
803     @ARGV or die "$self: need cargo subcommand\n";
804
805     $_ = shift @ARGV;
806     my $orgopt = $_;
807
808     my $not_a_nailing_opt = sub { # usage 1
809       unshift @ARGV, $orgopt;
810       unshift @ARGV, 'cargo';
811       $is_cargo = 1;
812       no warnings qw(exiting);
813       last OPTS;
814     };
815     $not_a_nailing_opt->() unless m{^-};
816     $not_a_nailing_opt->() if $_ eq '--';
817
818     if ($_ eq '---') { # usage 2 or 3
819       die "$self: --- must be followed by build command\n" unless @ARGV;
820       if ($ARGV[0] eq '--') { # usage 3
821         shift;
822         $is_cargo = 0;
823       } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
824         $is_cargo = 1;
825       } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
826         $is_cargo = 1;
827       } else {  # usage 3
828         $is_cargo = 0;
829       }
830       last;
831     }
832     if (m{^-[^-]}) {
833       while (m{^-.}) {
834         if (s{^-v}{-}) {
835           $verbose++;
836         } elsif (s{^-q}{-}) {
837           $verbose=0;
838         } elsif (s{^-n}{-}) {
839           $noact++;
840         } elsif (s{^-s(.+)}{-}s) {
841           $cargo_subcmd = $1;
842         } elsif (s{^-([uU])}{-}) {
843           $cargo_lock_update = $1=~m/[a-z]/;
844         } elsif (s{^-([cC])}{-}) {
845           $pass_options = $1=~m/[a-z]/;
846         } elsif (s{^-D}{-}) {
847           $dump++;
848         } elsif (s{^-T(.+)}{-}s) {
849           $target = $1;
850         } elsif (s{^-([oO])}{-}) {
851           $online = $1=~m/[a-z]/;
852         } else {
853           die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
854           $not_a_nailing_opt->();
855         }
856       }
857     } elsif (s{^--target=}{}) {
858       $target = $_;
859     } elsif (m{^--(on|off)line$}) {
860       $online = $1 eq 'on';
861     } elsif (s{^--subcommand-props=}{}) {
862       my @props = split /\,/, $_;
863       our %subcmd_prop_ok;
864       if (!%subcmd_prop_ok) {
865         foreach my $v (\@subcmd_xprops, values %subcmd_props) {
866           $subcmd_prop_ok{$_}=1 foreach @$v;
867         };
868       }
869       $subcmd_prop_ok{$_}
870         or die "$self: unknown subcommand property \`$_'\n"
871         foreach @props;
872       $cargo_subcmd = \@props;
873     } elsif (m{^--(no-)?cargo-lock-update}) {
874       $cargo_lock_update= !!$1;
875     } else {
876       $not_a_nailing_opt->();
877     }
878   }
879
880   $is_cargo // die;
881   @ARGV || die;
882
883   if ($is_cargo) {
884     @args_preface = shift @ARGV;
885     while (defined($_ = shift @ARGV)) {
886       if (!m{^-}) { unshift @ARGV, $_; last; }
887       if ($_ eq '--') { last; }
888       push @args_preface, $_;
889     }
890     @ARGV || die "$self: need cargo subcommand\n";
891     $cargo_subcmd //= $ARGV[0];
892     $pass_options //= 1;
893   } else {
894     $cargo_subcmd //= '';
895     $pass_options //= 0;
896   }
897   push @args_preface, shift @ARGV;
898
899   if (!ref($cargo_subcmd)) {
900     print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
901     $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
902   }
903
904   print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
905   my %cargo_subcmd;
906   $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
907   $cargo_subcmd = \%cargo_subcmd;
908 }
909
910 parse_args();
911 loadconfigs();
912 takelock();
913 readnail();
914 consider_alt_cargo_lock();
915 consider_oot();
916 readorigs();
917 calculate();
918 addargs();
919 consider_directories();
920 our @display_cmd = @ARGV;
921 oot_massage_cmdline();
922 setenvs();
923
924 if ($dump) {
925   eval '
926     use Data::Dumper;
927     print STDERR Dumper(\%manifests) if $dump>=2;
928     print STDERR Dumper(\%packagemap, \@ARGV,
929                         { src_absdir => $src_absdir,
930                           worksphere => $worksphere,
931                           subdir => $subdir,
932                           oot_dir => $oot_dir,
933                           oot_absdir => $oot_absdir,
934                           build_absdir => $build_absdir });
935   ' or die $@;
936 }
937
938 exit 0 if $noact;
939
940 $want_uninstall = 1;
941 makebackups();
942 install();
943
944 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
945   (scalar keys %manifests), (scalar keys %packagemap),
946   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
947   if $verbose;
948
949 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
950 my $estatus = invoke();
951
952 cargo_lock_update_after();
953
954 uninstall();
955 $want_uninstall = 0;
956
957 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
958
959 exit $estatus;