chiark / gitweb /
nailing-carog: Cope if no subdirs specified
[nailing-cargo.git] / nailing-cargo
1 #!/usr/bin/perl -w
2
3 #    nailing-cargo: wrapper to use unpublished local crates
4 #
5 #    Copyright (C) 2019-2020 Ian Jackson
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 # example usages:
21 #   ../nailing-cargo/nailing-cargo make
22 #   ../nailing-cargo/nailing-cargo cargo build
23
24 # Why do we need this ?
25 #
26 #  https://github.com/rust-lang/cargo/issues/6713
27 #  https://stackoverflow.com/questions/33025887/how-to-use-a-local-unpublished-crate
28 #  https://github.com/rust-lang/cargo/issues/1481
29
30 # Options:
31 #    -v   Increase verbosity.  Default is 1.
32 #    -q   Set verbosity ot 0.
33 #    -D   Increase amount of debugging dump.
34 #
35 #    -n   "No action": stop after writing Cargo.toml.nailing~
36 #         everywhere, and do not run any build command.
37 #
38 #    -T<arch> --target=<arch>
39 #         Specify target architecture.  If <arch> starts with a
40 #         capital ascii letter, is an alias for some other arch
41 #         looked up in Cargo.nail and then in the builtin list:
42 #           RPI   arm-unknown-linux-gnueabihf
43 #         Translates to a --target= option to the ultimate command,
44 #         unless that is a cargo subcommand which would reject it.
45 #
46 #    -u | --cargo-lock-update
47 #    -U | --no-cargo-lock-update
48 #         Arranges to do a dance to allow Cargo.lock (or
49 #         alternative) to be updated in the source directory.
50 #
51 #         The Cargo.lock and Cargo.toml are copied to the build
52 #         directory along with a skeleton just big enough to fool
53 #         cargo.  After cargo has run, the resulting Cargo.lock is
54 #         copied back to the source tree.
55 #
56 #         Makes no sense with in-tree builds.
57 #
58 #         Default is no update unless the ultimate command is a
59 #         cargo subcommand which we know needs it.
60 #
61 #    -m | --cargo-manifest-args
62 #    -M | --no-cargo-manifest-args
63 #         Controls whether we add cargo command line options
64 #         relating to finding Cargo.toml, to the command to
65 #         run.
66 #
67 #         Default is true if we are doing an out-of- tree build,
68 #         unless we are updating the Cargo.lock (in which case the
69 #         only relevant files are to be found in the build directory).
70 #
71 #         The arguments are
72 #             --manifest-path=<path/to/Cargo.toml>
73 #             --locked --target-dir=target
74 #
75 # Cargo.nail:
76 #
77 #    # Adds each <subdir> to the list of directories whose
78 #    # Cargo.toml is to be nailed, and also arranges to use
79 #    # the package found there for other directories if
80 #    # no other source of that package is evident in Cargo.nail.
81 #    subdirs = [
82 #      "<subdir>"
83 #      ...
84 #    ]
85 # or:
86 #    subdirs = """
87 #      "<subdir>"
88 #      ...
89 #    """
90 #
91 #    # Adds <subdir> to the list of directories whose Cargo.toml
92 #    # is to be nailed, and overrides any other nailing for <package>
93 #    [packages]
94 #    <package> = <subdir>
95 #    <package> = { <subdir> = ... }
96 #
97 # To control use of alternative Cargo.lock filename:
98 #    [alt_cargolock]
99 #
100 #    file = true               # equivalent to "Cargo.lock.example"
101 #    file = false              # disables this feature
102 #    file = "<some leafname>"
103
104 #    force = false    # default, uses alt file only if it already exists
105 #    force = true     # always uses alt file; creation would make Cargo.lock
106 #
107 # (you can also specify just alt_cargo_lock instead of alt_cargo_lock.file)
108 #
109 # To enable out of tree builds:
110 #    [oot]
111 #    dir = "<build-directory>"    # default is Build, if use is specified
112 # and then
113 #    use = "really"
114 #    user = "<someuser>"
115 #  or
116 #    use = "ssh"
117 #    user = "<user>@host"         # NB must still share a filesystem!
118 #  or
119 #    use = "command_args"
120 #    command = ["<command>", "<which works like>", "nice"]
121 #  or
122 #    use = "command_sh"
123 #    command = ["<command>", "<which work like>", "sh -c"]
124 #  or
125 #    use = "null"
126 #
127 # Limitations:
128 #
129 #   Always dirties everyone's Cargo.toml, but tries to put them
130 #     back (if not, running it again should fix it).  Cannnot be
131 #     fixed without changes to cargo.
132 #
133 #   Out of tree builds require a unified filesystem view: eg,
134 #     different users on the same host, NFS, or something.  This
135 #     could be improved.
136 #
137 #   Alternative Cargo.lock file must currently be a leafname.
138 #     I think this just involves review to check other values work.
139 #
140 #   Alternative Cargo.lock file must be on smae filesystem.
141 #     This is not so easy; we would want the existing algorithm but
142 #     a fallback for this case.
143 #
144 #   Cargo.nail unconditionally looked for in ..
145 #     Ideally should be configurable, and also perhaps be able
146 #     to combine multiple Cargo.nail files ?
147 #
148 # Env vars we pass to the command:
149 #   NAILINGCARGO_WORKSPHERE     absolute path of invocation ..
150 #   NAILINGCARGO_MANIFEST_DIR   absolute path of invocation .
151 #   NAILINGCARGO_BUILDSPHERE    only if out of tree: abs parent of build dir
152 #   NAILINGCARGO_BUILD_DIR      absolute path of build dir (even if = src)
153
154
155 our $self;
156
157 use strict;
158 use POSIX;
159 use Types::Serialiser;
160
161 our %archmap = (
162     RPI => 'arm-unknown-linux-gnueabihf',
163 );
164
165 BEGIN {
166   $self = $0;  $self =~ s{^.*/(?=.)}{};
167   my $deref = $0;
168   while ($deref =~ m{^/}) {
169     my $link = readlink $deref;
170     if (!defined $link) {
171       $! == EINVAL
172         or die "$self: checking our script location $deref: $!\n";
173       $deref =~ s{/[^/]+$}{}
174         or die "$self: unexpected script path: $deref\n";
175       unshift @INC, $deref."/TOML-Tiny/lib";
176       last;
177     }
178     last if $link !~ m{^/};
179     $deref = $link;
180   }
181 }
182
183 use Fcntl qw(LOCK_EX);
184 use File::Compare;
185 use TOML::Tiny::Faithful;
186
187 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
188
189 our $worksphere = $src_absdir;
190 $worksphere =~ s{/([^/]+)$}{}
191   or die "$self: cwd \`$worksphere' unsupported!\n";
192 our $subdir = $1; # leafname
193
194 our $lockfile = "../.nailing-cargo.lock";
195
196 our $cargo_lock_update;
197 our $cargo_manifest_args;
198 our $alt_cargo_lock;
199
200 our @configs;
201 our $verbose=1;
202 our ($noact,$dump);
203 our $target;
204
205 sub read_or_enoent ($) {
206   my ($fn) = @_;
207   if (!open R, '<', $fn) {
208     return undef if $!==ENOENT;
209     die "$self: open $fn: $!\n";
210   }
211   local ($/) = undef;
212   my ($r) = <R> // die "$self: read $fn: $!\n";
213   $r;
214 }
215
216 sub stat_exists ($$) {
217   my ($fn, $what) = @_;
218   if (stat $fn) { return 1; }
219   $!==ENOENT or die "$self: stat $what: $fn: $!\n";
220   return 0;
221 }
222
223 sub toml_or_enoent ($$) {
224   my ($f,$what) = @_;
225   my $toml = read_or_enoent($f) // return;
226   my ($v,$e) = from_toml($toml);
227   if (!defined $v) {
228     chomp $e;
229     die "$self: parse TOML: $what: $f: $e\n";
230   }
231   die "$e ?" if length $e;
232   $v;
233 }
234
235 sub load1config ($) {
236   my ($f) = @_;
237   my $toml = toml_or_enoent($f, "config file");
238   push @configs, $toml if defined $toml;
239 }
240
241 sub loadconfigs () {
242   my $cfgleaf = ".nailing-cargo-cfg.toml";
243   load1config("/etc/nailing-cargo/cfg.toml");
244   load1config("$worksphere/$cfgleaf");
245   load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
246 }
247
248 sub getcfg ($$) {
249   my ($k, $def) = @_;
250   foreach my $cfg (@configs) {
251     my $v = $cfg->{$k};
252     return $v if defined $v;
253   }
254   return $def;
255 }
256
257 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
258
259 sub same_file ($$) {
260   my ($x,$y) = @_;
261   "@$x[0..5]" eq "@$y[0..5]";
262 }
263
264 sub takelock () {
265   for (;;) {
266     open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
267     flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
268     my @fstat = stat LOCK or die "$self: fstat: $!\n";
269     my @stat  = stat $lockfile;
270     if (!@stat) {
271       next if $! == ENOENT;
272       die "$self: stat $lockfile: $!\n";
273     }
274     last if same_file(\@fstat,\@stat);
275   }
276 }
277 sub unlock () {
278   unlink $lockfile or die "$self: removing lockfile: $!\n";
279 }
280
281 our $nail;
282
283 sub badcfg {
284   my $m = pop @_;
285   $" = '.';
286   die "$self: config key \`@_': $m\n";
287 }
288
289 sub cfg_uc {
290   my $v = $nail;
291   foreach my $k (@_) {
292     last unless defined $v;
293     ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
294     $v = $v->{$k};
295   }
296   return $v;
297 }
298
299 sub cfge {
300   my $exp = shift @_;
301   my $v = cfg_uc @_;
302   my $got = ref($v) || 'scalar';
303   return $v if !defined($v) || $got eq $exp;
304   badcfg @_, "found \L$got\E, expected \L$exp\E";
305   # ^ toml doesn't make refs to scalars, so this is unambiguous
306 }
307
308 sub cfgn {
309   my $exp = shift @_;
310   (cfge $exp, @_) // badcfg @_, "missing";
311 }
312
313 sub cfgs  { cfge 'scalar', @_ }
314 sub cfgsn { cfgn 'scalar', @_ }
315
316 sub cfg_bool {
317   my $v = cfg_uc @_;
318   return $v if !defined($v) || Types::Serialiser::is_bool $v;
319   badcfg @_, "expected boolean";
320 }
321
322 sub cfgn_list {
323   my $l = cfge 'ARRAY', @_;
324   foreach my $x (@$l) {
325     !ref $x or badcfg @_, "list contains non-scalar element";
326   }
327   @$l
328 }
329
330 sub readnail () {
331   my $nailfile = "../Cargo.nail";
332   open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
333   local ($/) = undef;
334   my $toml = <N> // die "$self: read $nailfile: $!";
335   my $transformed;
336   if ($toml !~ m{^\s*\[/}m &&
337       $toml !~ m{^[^\n\#]*\=}m &&
338       # old non-toml syntax
339       $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
340     $toml =~ s{^}{[packages\]\n};
341     my @sd;
342     $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
343       push @sd, $1; '';
344     }mige;
345     $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
346     $transformed = 1;
347   }
348   my $e;
349   ($nail,$e) = from_toml($toml);
350   if (!defined $nail) {
351     if ($transformed) {
352       $toml =~ s/^/    /mg;
353       print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
354     }
355     $/="\n"; chomp $e;
356     die "$self: parse $nailfile: $e\n";
357   }
358   die "$e ?" if length $e;
359
360   $nail->{subdirs} //= [ ];
361
362   if (!ref $nail->{subdirs}) {
363     $nail->{subdirs} = [
364       grep /^[^\#]/,
365       map { s/^\s+//; s/\s+$//; $_; }
366       split m{\n},
367       $nail->{subdirs}
368     ];
369   }
370 }
371
372 our @alt_cargo_lock_stat;
373
374 sub consider_alt_cargo_lock () {
375   my @ck = qw(alt_cargo_lock);
376   # User should *either* have Cargo.lock in .gitignore,
377   # or expect to commit Cargo.lock.example ($alt_cargo_lock)
378
379   $alt_cargo_lock = (cfg_uc @ck);
380
381   my $force = 0;
382   if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
383     $force = cfg_bool qw(alt_cargo_lock force);
384     my @ck = qw(alt_cargo_lock file);
385     $alt_cargo_lock = cfg_uc @ck;
386   }
387   $alt_cargo_lock //= Types::Serialiser::true;
388
389   if (Types::Serialiser::is_bool $alt_cargo_lock) {
390     if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
391     $alt_cargo_lock = 'Cargo.lock.example';
392   }
393
394   if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
395     badcfg @ck, "expected boolean, or leafname";
396   }
397
398   if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
399     $alt_cargo_lock = undef unless $force;
400     return;
401   }
402   
403   @alt_cargo_lock_stat = stat _;
404 }
405
406 our $oot_dir;      # oot.dir or "Build"
407
408 sub consider_oot () {
409   $oot_dir = cfgs qw(oot dir);
410   my $use = cfgs qw(oot use);
411   unless (defined($oot_dir) || defined($use)) {
412     die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
413       if $cargo_lock_update;
414     $cargo_lock_update=0;
415     return;
416   }
417   $oot_dir //= 'Build';
418 }
419
420 our %manifests;
421 our %packagemap;
422
423 sub read_manifest ($) {
424   my ($subdir) = @_;
425   my $manifest = "../$subdir/Cargo.toml";
426   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
427   if (defined $manifests{$manifest}) {
428     print STDERR
429  "$self: warning: $subdir: specified more than once!\n";
430     return undef;
431   }
432   foreach my $try ("$manifest.unnailed", "$manifest") {
433     my $toml = toml_or_enoent($try, "package manifest") // next;
434     my $p = $toml->{package}{name};
435     if (!defined $p) {
436       print STDERR
437  "$self: warning: $subdir: missing package.name in $try, ignoring\n";
438       next;
439     }
440     $manifests{$manifest} = $toml;
441     return $p;
442   }
443   return undef;
444 }
445
446 sub readorigs () {
447   foreach my $p (keys %{ $nail->{packages} }) {
448     my $v = $nail->{packages}{$p};
449     my $subdir = ref($v) ? $v->{subdir} : $v;
450     my $gotpackage = read_manifest($subdir) // '<nothing!>';
451     if ($gotpackage ne $p) {
452       print STDERR
453  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
454     }
455     die if defined $packagemap{$p};
456     $packagemap{$p} = $subdir;
457   }
458   foreach my $subdir (@{ $nail->{subdirs} }) {
459     my $gotpackage = read_manifest($subdir);
460     if (!defined $gotpackage) {
461       print STDERR
462  "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
463       next;
464     }
465     $packagemap{$gotpackage} //= $subdir;
466   }
467 }
468
469 sub calculate () {
470   foreach my $p (sort keys %packagemap) {
471     print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
472   }
473   foreach my $mf (keys %manifests) {
474     my $toml = $manifests{$mf};
475     foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
476       my $deps = $toml->{$k};
477       next unless $deps;
478       foreach my $p (keys %packagemap) {
479         my $info = $deps->{$p};
480         next unless defined $info;
481         $deps->{$p} = $info = { } unless ref $info;
482         delete $info->{version};
483         $info->{path} = $worksphere.'/'.$packagemap{$p};
484       }
485     }
486     my $nailing = "$mf.nailing~";
487     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
488     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
489     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
490     close N or die "$self: close new $nailing: $!\n";
491   }
492 }
493
494 sub addargs () {
495   if (@ARGV>=2 &&
496       $ARGV[0] =~ m{\bcargo\b} &&
497       $ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
498     $cargo_lock_update //= 1;
499     $target = undef;
500   } else {
501     $cargo_lock_update //= 0;
502   }
503   $cargo_manifest_args //=
504     (defined $oot_dir) && !$cargo_lock_update;
505
506   if ($cargo_manifest_args) {
507     push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
508       qw(--locked --target-dir=target);
509   }
510
511   if (defined $target) {
512     if ($target =~ m{^[A-Z]}) {
513       $target = (cfgs 'arch', $target) // $archmap{$target}
514         // die "$self: --target=$target alias specified; not in cfg or map\n";
515     }
516     push @ARGV, "--target=$target";
517   }
518 }
519
520 our $oot_absdir;
521 our $build_absdir; # .../Build/<subdir>
522
523 sub oot_massage_cmdline () {
524   return unless defined $oot_dir;
525
526   my $use = cfgs qw(oot use);
527   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
528   $build_absdir = "$oot_absdir/$subdir";
529
530   my ($pre,$post);
531   my @xargs;
532   if (!$cargo_lock_update) {
533     push @xargs, $build_absdir;
534     ($pre, $post) = ('cd "$1"; shift; ', '');
535   } else {
536     push @xargs, $oot_absdir, $subdir, $src_absdir;
537     $pre =  <<'END';
538         cd "$1"; shift;
539         mkdir -p -- "$1"; cd "$1"; shift;
540         cp -- "$1"/Cargo.toml
541 END
542     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
543               "$1"/Cargo.lock
544 ENDLK
545     $pre .= <<'ENDCP';
546                               .;
547 ENDCP
548     $pre .= <<'ENDPRE';
549         shift;
550         mkdir -p src; >src/lib.rs;
551 ENDPRE
552     $post = <<'ENDPOST';
553         rm -r src Cargo.toml;
554 ENDPOST
555   }
556   my $addpath = (cfg_uc qw(oot path_add)) //
557     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
558   $addpath =
559     !Types::Serialiser::is_bool $addpath ? $addpath           :
560     $addpath                             ? '$HOME/.cargo/bin' :
561                                            undef;
562   if (defined $addpath) {
563     $pre .= <<END
564         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
565         export PATH;
566 END
567   }
568   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
569   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
570
571   my $getuser = sub { cfgsn qw(oot user) };
572   my @command;
573   my $xe = $verbose >= 2 ? 'xe' : 'e';
574   my $sh_ec = sub {
575     if (!length $post) {
576       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
577     } else {
578       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
579     }
580     push @command, @ARGV;
581   };
582   my $command_sh = sub {
583     my $quoted = join ' ', map {
584       return $_ if !m/\W/;
585       s/\'/\'\\'\'/g;
586       "'$_'"
587     } @ARGV;
588     @command = @_, "set -${xe}; $pre $quoted; $post";
589   };
590   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
591     if $verbose;
592   if ($use eq 'really') {
593     my $user = $getuser->();
594     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
595     my $homedir = $pw[7];
596     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
597     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
598   } elsif ($use eq 'ssh') {
599     my $user = $getuser->();
600     $user .= '@localhost' unless $user =~ m/\@/;
601     $command_sh->('ssh',$user);
602     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
603   } elsif ($use eq 'command_args') {
604     my @c = cfgn_list qw(oot command);
605     $sh_ec->(@c);
606     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
607   } elsif ($use eq 'command_sh') {
608     my @c = cfgn_list qw(oot command);
609     $command_sh->(@c);
610     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
611   } elsif ($use eq 'null') {
612     $sh_ec->();
613   } else {
614     die "$self: oot.use mode $use not recognised\n";
615   }
616   die unless @command;
617   @ARGV = @command;
618 }
619
620 sub setenvs () {
621   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
622   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
623   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
624   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
625   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
626 }
627
628 our $want_uninstall;
629
630 END {
631   if ($want_uninstall) {
632     local ($?);
633     foreach my $mf (keys %manifests) {
634       eval { uninstall1($mf,1); 1; } or warn "$@";
635     }
636     eval { unaltcargolock(1); 1; } or warn "$@";
637   }
638 }
639
640 our $cleanup_cargo_lock;
641 sub makebackups () {
642   foreach my $mf (keys %manifests) {
643     link "$mf", "$mf.unnailed" or $!==EEXIST
644       or die "$self: make backup link $mf.unnailed: $!\n";
645   }
646
647   if (defined($alt_cargo_lock)) {
648     if (@alt_cargo_lock_stat) {
649       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
650         if $verbose>=3;
651       if (link $alt_cargo_lock, 'Cargo.lock') {
652         print STDERR " linked\n" if $verbose>=3;
653       } elsif ($! != EEXIST) {
654         print STDERR "\n" if $verbose>=3;
655         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
656       } else {
657         print STDERR "checking quality." if $verbose>=3;
658         my @lock_stat = stat 'Cargo.lock'
659           or die "$self: stat Cargo.lock (for alt check: $!\n";
660         same_file(\@alt_cargo_lock_stat, \@lock_stat)
661           or die
662 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
663       }
664       $cleanup_cargo_lock = 1;
665     } else {
666       $cleanup_cargo_lock = 1;
667       # If Cargo.lock exists and alt doesn't, that means either
668       # that a previous run was interrupted, or that the user has
669       # messed up.
670     }
671   }
672 }
673
674 sub nailed ($) {
675   my ($mf) = @_;
676   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
677   $nailed;
678 }    
679
680 sub install () {
681   foreach my $mf (keys %manifests) {
682     my $nailing = "$mf.nailing~";
683     my $nailed = nailed($mf);
684     my ($use, $rm);
685     my $diff;
686     if (open NN, '<', $nailed) {
687       $diff = compare($nailing, \*NN);
688       die "$self: compare $nailing and $nailed: $!" if $diff<0;
689     } else {
690       $!==ENOENT or die "$self: check previous $nailed: $!\n";
691       $diff = 1;
692     }
693     if ($diff) {
694       $use = $nailing;
695       $rm  = $nailed;
696     } else {
697       $use = $nailed;
698       $rm  = $nailing;
699     }
700     rename $use, $mf or die "$self: install nailed $use: $!\n";
701     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
702     print STDERR "$self: nailed $mf\n" if $verbose>=3;
703   }
704 }
705
706 sub invoke () {
707   my $r = system @ARGV;
708   if (!$r) {
709     return 0;
710   } elsif ($r<0) {
711     print STDERR "$self: could not execute $ARGV[0]: $!\n";
712     return 127;
713   } elsif ($r & 0xff00) {
714     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
715     return $r >> 8;
716   } else {
717     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
718     return 125;
719   }
720 }
721
722 sub cargo_lock_update_after () {
723   if ($cargo_lock_update) {
724     # avoids importing File::Copy and the error handling is about as good
725     $!=0; $?=0;
726     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
727     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
728     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
729   }
730 }
731
732 sub uninstall1 ($$) {
733   my ($mf, $enoentok) = @_;
734   my $unnailed = "$mf.unnailed";
735   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
736     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
737 }
738
739 sub unaltcargolock ($) {
740   my ($enoentok) = @_;
741   return unless $cleanup_cargo_lock;
742   die 'internal error!' unless defined $alt_cargo_lock;
743
744   # we ignore $enoentok because we don't know if one was supposed to
745   # have been created.
746
747   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
748  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
749
750   unlink 'Cargo.lock' or $!==ENOENT or die
751  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
752   # ^ this also helps clean up the stupid rename() corner case
753 }
754
755 sub uninstall () {
756   foreach my $mf (keys %manifests) {
757     my $nailed = nailed($mf);
758     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
759     uninstall1($mf,0);
760   }
761   unaltcargolock(0);
762 }
763
764 while (@ARGV && $ARGV[0] =~ m/^-/) {
765   $_ = shift @ARGV;
766   last if m{^--$};
767   if (m{^-[^-]}) {
768     while (m{^-.}) {
769       if (s{^-v}{-}) {
770         $verbose++;
771       } elsif (s{^-q}{-}) {
772         $verbose=0;
773       } elsif (s{^-n}{-}) {
774         $noact++;
775       } elsif (s{^-D}{-}) {
776         $dump++;
777       } elsif (s{^-T(.+)}{-}s) {
778         $target = $1;
779       } elsif (s{^-([uU])}{-}) {
780         $cargo_lock_update= $1=~m/[a-z]/;
781       } elsif (s{^-([mM])}{-}) {
782         $cargo_manifest_args= $1=~m/[a-z]/;
783       } else {
784         die "$self: unknown short option(s) $_\n";
785       }
786     }
787   } elsif (s{^--target=}{}) {
788     $target = $_;
789   } elsif (m{^--(no-)?cargo-lock-update}) {
790     $cargo_lock_update= !!$1;
791   } elsif (m{^--(no-)?cargo-manifest-args}) {
792     $cargo_manifest_args= !!$1;
793   } else {
794     die "$self: unknown long option $_\n";
795   }
796 }
797
798 die "$self: need command to run\n" unless @ARGV || $noact;
799
800 takelock();
801 readnail();
802 consider_alt_cargo_lock();
803 consider_oot();
804 readorigs();
805 calculate();
806 addargs();
807 our @display_cmd = @ARGV;
808 oot_massage_cmdline();
809 setenvs();
810
811 if ($dump) {
812   eval '
813     use Data::Dumper;
814     print STDERR Dumper(\%manifests) if $dump>=2;
815     print STDERR Dumper(\%packagemap, \@ARGV,
816                         { src_absdir => $src_absdir,
817                           worksphere => $worksphere,
818                           subdir => $subdir,
819                           oot_dir => $oot_dir,
820                           oot_absdir => $oot_absdir,
821                           build_absdir => $build_absdir });
822   ' or die $@;
823 }
824
825 exit 0 if $noact;
826
827 $want_uninstall = 1;
828 makebackups();
829 install();
830
831 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
832   (scalar keys %manifests), (scalar keys %packagemap),
833   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
834   if $verbose;
835
836 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
837 my $estatus = invoke();
838
839 cargo_lock_update_after();
840
841 uninstall();
842 $want_uninstall = 0;
843
844 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
845
846 exit $estatus;