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