chiark / gitweb /
nailing-cargo: Docs.
[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   if (!ref $nail->{subdirs}) {
361     $nail->{subdirs} = [
362       grep /^[^\#]/,
363       map { s/^\s+//; s/\s+$//; $_; }
364       split m{\n},
365       $nail->{subdirs}
366     ];
367   }
368 }
369
370 our @alt_cargo_lock_stat;
371
372 sub consider_alt_cargo_lock () {
373   my @ck = qw(alt_cargo_lock);
374   # User should *either* have Cargo.lock in .gitignore,
375   # or expect to commit Cargo.lock.example ($alt_cargo_lock)
376
377   $alt_cargo_lock = (cfg_uc @ck);
378
379   my $force = 0;
380   if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
381     $force = cfg_bool qw(alt_cargo_lock force);
382     my @ck = qw(alt_cargo_lock file);
383     $alt_cargo_lock = cfg_uc @ck;
384   }
385   $alt_cargo_lock //= Types::Serialiser::true;
386
387   if (Types::Serialiser::is_bool $alt_cargo_lock) {
388     if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
389     $alt_cargo_lock = 'Cargo.lock.example';
390   }
391
392   if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
393     badcfg @ck, "expected boolean, or leafname";
394   }
395
396   if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
397     $alt_cargo_lock = undef unless $force;
398     return;
399   }
400   
401   @alt_cargo_lock_stat = stat _;
402 }
403
404 our $oot_dir;      # oot.dir or "Build"
405
406 sub consider_oot () {
407   $oot_dir = cfgs qw(oot dir);
408   my $use = cfgs qw(oot use);
409   unless (defined($oot_dir) || defined($use)) {
410     die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
411       if $cargo_lock_update;
412     $cargo_lock_update=0;
413     return;
414   }
415   $oot_dir //= 'Build';
416 }
417
418 our %manifests;
419 our %packagemap;
420
421 sub read_manifest ($) {
422   my ($subdir) = @_;
423   my $manifest = "../$subdir/Cargo.toml";
424   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
425   if (defined $manifests{$manifest}) {
426     print STDERR
427  "$self: warning: $subdir: specified more than once!\n";
428     return undef;
429   }
430   foreach my $try ("$manifest.unnailed", "$manifest") {
431     my $toml = toml_or_enoent($try, "package manifest") // next;
432     my $p = $toml->{package}{name};
433     if (!defined $p) {
434       print STDERR
435  "$self: warning: $subdir: missing package.name in $try, ignoring\n";
436       next;
437     }
438     $manifests{$manifest} = $toml;
439     return $p;
440   }
441   return undef;
442 }
443
444 sub readorigs () {
445   foreach my $p (keys %{ $nail->{packages} }) {
446     my $v = $nail->{packages}{$p};
447     my $subdir = ref($v) ? $v->{subdir} : $v;
448     my $gotpackage = read_manifest($subdir) // '<nothing!>';
449     if ($gotpackage ne $p) {
450       print STDERR
451  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
452     }
453     die if defined $packagemap{$p};
454     $packagemap{$p} = $subdir;
455   }
456   foreach my $subdir (@{ $nail->{subdirs} }) {
457     my $gotpackage = read_manifest($subdir);
458     if (!defined $gotpackage) {
459       print STDERR
460  "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
461       next;
462     }
463     $packagemap{$gotpackage} //= $subdir;
464   }
465 }
466
467 sub calculate () {
468   foreach my $p (sort keys %packagemap) {
469     print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
470   }
471   foreach my $mf (keys %manifests) {
472     my $toml = $manifests{$mf};
473     foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
474       my $deps = $toml->{$k};
475       next unless $deps;
476       foreach my $p (keys %packagemap) {
477         my $info = $deps->{$p};
478         next unless defined $info;
479         $deps->{$p} = $info = { } unless ref $info;
480         delete $info->{version};
481         $info->{path} = $worksphere.'/'.$packagemap{$p};
482       }
483     }
484     my $nailing = "$mf.nailing~";
485     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
486     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
487     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
488     close N or die "$self: close new $nailing: $!\n";
489   }
490 }
491
492 sub addargs () {
493   if (@ARGV>=2 &&
494       $ARGV[0] =~ m{\bcargo\b} &&
495       $ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
496     $cargo_lock_update //= 1;
497     $target = undef;
498   } else {
499     $cargo_lock_update //= 0;
500   }
501   $cargo_manifest_args //=
502     (defined $oot_dir) && !$cargo_lock_update;
503
504   if ($cargo_manifest_args) {
505     push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
506       qw(--locked --target-dir=target);
507   }
508
509   if (defined $target) {
510     if ($target =~ m{^[A-Z]}) {
511       $target = (cfgs 'arch', $target) // $archmap{$target}
512         // die "$self: --target=$target alias specified; not in cfg or map\n";
513     }
514     push @ARGV, "--target=$target";
515   }
516 }
517
518 our $oot_absdir;
519 our $build_absdir; # .../Build/<subdir>
520
521 sub oot_massage_cmdline () {
522   return unless defined $oot_dir;
523
524   my $use = cfgs qw(oot use);
525   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
526   $build_absdir = "$oot_absdir/$subdir";
527
528   my ($pre,$post);
529   my @xargs;
530   if (!$cargo_lock_update) {
531     push @xargs, $build_absdir;
532     ($pre, $post) = ('cd "$1"; shift; ', '');
533   } else {
534     push @xargs, $oot_absdir, $subdir, $src_absdir;
535     $pre =  <<'END';
536         cd "$1"; shift;
537         mkdir -p -- "$1"; cd "$1"; shift;
538         cp -- "$1"/Cargo.toml
539 END
540     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
541               "$1"/Cargo.lock
542 ENDLK
543     $pre .= <<'ENDCP';
544                               .;
545 ENDCP
546     $pre .= <<'ENDPRE';
547         shift;
548         mkdir -p src; >src/lib.rs;
549 ENDPRE
550     $post = <<'ENDPOST';
551         rm -r src Cargo.toml;
552 ENDPOST
553   }
554   my $addpath = (cfg_uc qw(oot path_add)) //
555     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
556   $addpath =
557     !Types::Serialiser::is_bool $addpath ? $addpath           :
558     $addpath                             ? '$HOME/.cargo/bin' :
559                                            undef;
560   if (defined $addpath) {
561     $pre .= <<END
562         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
563         export PATH;
564 END
565   }
566   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
567   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
568
569   my $getuser = sub { cfgsn qw(oot user) };
570   my @command;
571   my $xe = $verbose >= 2 ? 'xe' : 'e';
572   my $sh_ec = sub {
573     if (!length $post) {
574       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
575     } else {
576       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
577     }
578     push @command, @ARGV;
579   };
580   my $command_sh = sub {
581     my $quoted = join ' ', map {
582       return $_ if !m/\W/;
583       s/\'/\'\\'\'/g;
584       "'$_'"
585     } @ARGV;
586     @command = @_, "set -${xe}; $pre $quoted; $post";
587   };
588   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
589     if $verbose;
590   if ($use eq 'really') {
591     my $user = $getuser->();
592     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
593     my $homedir = $pw[7];
594     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
595     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
596   } elsif ($use eq 'ssh') {
597     my $user = $getuser->();
598     $user .= '@localhost' unless $user =~ m/\@/;
599     $command_sh->('ssh',$user);
600     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
601   } elsif ($use eq 'command_args') {
602     my @c = cfgn_list qw(oot command);
603     $sh_ec->(@c);
604     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
605   } elsif ($use eq 'command_sh') {
606     my @c = cfgn_list qw(oot command);
607     $command_sh->(@c);
608     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
609   } elsif ($use eq 'null') {
610     $sh_ec->();
611   } else {
612     die "$self: oot.use mode $use not recognised\n";
613   }
614   die unless @command;
615   @ARGV = @command;
616 }
617
618 sub setenvs () {
619   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
620   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
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 our $cleanup_cargo_lock;
639 sub makebackups () {
640   foreach my $mf (keys %manifests) {
641     link "$mf", "$mf.unnailed" or $!==EEXIST
642       or die "$self: make backup link $mf.unnailed: $!\n";
643   }
644
645   if (defined($alt_cargo_lock)) {
646     if (@alt_cargo_lock_stat) {
647       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
648         if $verbose>=3;
649       if (link $alt_cargo_lock, 'Cargo.lock') {
650         print STDERR " linked\n" if $verbose>=3;
651       } elsif ($! != EEXIST) {
652         print STDERR "\n" if $verbose>=3;
653         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
654       } else {
655         print STDERR "checking quality." if $verbose>=3;
656         my @lock_stat = stat 'Cargo.lock'
657           or die "$self: stat Cargo.lock (for alt check: $!\n";
658         same_file(\@alt_cargo_lock_stat, \@lock_stat)
659           or die
660 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
661       }
662       $cleanup_cargo_lock = 1;
663     } else {
664       $cleanup_cargo_lock = 1;
665       # If Cargo.lock exists and alt doesn't, that means either
666       # that a previous run was interrupted, or that the user has
667       # messed up.
668     }
669   }
670 }
671
672 sub nailed ($) {
673   my ($mf) = @_;
674   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
675   $nailed;
676 }    
677
678 sub install () {
679   foreach my $mf (keys %manifests) {
680     my $nailing = "$mf.nailing~";
681     my $nailed = nailed($mf);
682     my ($use, $rm);
683     my $diff;
684     if (open NN, '<', $nailed) {
685       $diff = compare($nailing, \*NN);
686       die "$self: compare $nailing and $nailed: $!" if $diff<0;
687     } else {
688       $!==ENOENT or die "$self: check previous $nailed: $!\n";
689       $diff = 1;
690     }
691     if ($diff) {
692       $use = $nailing;
693       $rm  = $nailed;
694     } else {
695       $use = $nailed;
696       $rm  = $nailing;
697     }
698     rename $use, $mf or die "$self: install nailed $use: $!\n";
699     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
700     print STDERR "$self: nailed $mf\n" if $verbose>=3;
701   }
702 }
703
704 sub invoke () {
705   my $r = system @ARGV;
706   if (!$r) {
707     return 0;
708   } elsif ($r<0) {
709     print STDERR "$self: could not execute $ARGV[0]: $!\n";
710     return 127;
711   } elsif ($r & 0xff00) {
712     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
713     return $r >> 8;
714   } else {
715     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
716     return 125;
717   }
718 }
719
720 sub cargo_lock_update_after () {
721   if ($cargo_lock_update) {
722     # avoids importing File::Copy and the error handling is about as good
723     $!=0; $?=0;
724     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
725     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
726     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
727   }
728 }
729
730 sub uninstall1 ($$) {
731   my ($mf, $enoentok) = @_;
732   my $unnailed = "$mf.unnailed";
733   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
734     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
735 }
736
737 sub unaltcargolock ($) {
738   my ($enoentok) = @_;
739   return unless $cleanup_cargo_lock;
740   die 'internal error!' unless defined $alt_cargo_lock;
741
742   # we ignore $enoentok because we don't know if one was supposed to
743   # have been created.
744
745   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
746  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
747
748   unlink 'Cargo.lock' or $!==ENOENT or die
749  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
750   # ^ this also helps clean up the stupid rename() corner case
751 }
752
753 sub uninstall () {
754   foreach my $mf (keys %manifests) {
755     my $nailed = nailed($mf);
756     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
757     uninstall1($mf,0);
758   }
759   unaltcargolock(0);
760 }
761
762 while (@ARGV && $ARGV[0] =~ m/^-/) {
763   $_ = shift @ARGV;
764   last if m{^--$};
765   if (m{^-[^-]}) {
766     while (m{^-.}) {
767       if (s{^-v}{-}) {
768         $verbose++;
769       } elsif (s{^-q}{-}) {
770         $verbose=0;
771       } elsif (s{^-n}{-}) {
772         $noact++;
773       } elsif (s{^-D}{-}) {
774         $dump++;
775       } elsif (s{^-T(.+)}{-}s) {
776         $target = $1;
777       } elsif (s{^-([uU])}{-}) {
778         $cargo_lock_update= $1=~m/[a-z]/;
779       } elsif (s{^-([mM])}{-}) {
780         $cargo_manifest_args= $1=~m/[a-z]/;
781       } else {
782         die "$self: unknown short option(s) $_\n";
783       }
784     }
785   } elsif (s{^--target=}{}) {
786     $target = $_;
787   } elsif (m{^--(no-)?cargo-lock-update}) {
788     $cargo_lock_update= !!$1;
789   } elsif (m{^--(no-)?cargo-manifest-args}) {
790     $cargo_manifest_args= !!$1;
791   } else {
792     die "$self: unknown long option $_\n";
793   }
794 }
795
796 die "$self: need command to run\n" unless @ARGV || $noact;
797
798 takelock();
799 readnail();
800 consider_alt_cargo_lock();
801 consider_oot();
802 readorigs();
803 calculate();
804 addargs();
805 our @display_cmd = @ARGV;
806 oot_massage_cmdline();
807 setenvs();
808
809 if ($dump) {
810   eval '
811     use Data::Dumper;
812     print STDERR Dumper(\%manifests) if $dump>=2;
813     print STDERR Dumper(\%packagemap, \@ARGV,
814                         { src_absdir => $src_absdir,
815                           worksphere => $worksphere,
816                           subdir => $subdir,
817                           oot_dir => $oot_dir,
818                           oot_absdir => $oot_absdir,
819                           build_absdir => $build_absdir });
820   ' or die $@;
821 }
822
823 exit 0 if $noact;
824
825 $want_uninstall = 1;
826 makebackups();
827 install();
828
829 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
830   (scalar keys %manifests), (scalar keys %packagemap),
831   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
832   if $verbose;
833
834 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
835 my $estatus = invoke();
836
837 cargo_lock_update_after();
838
839 uninstall();
840 $want_uninstall = 0;
841
842 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
843
844 exit $estatus;