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     if ($ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
505       $cargo_lock_update //= 1;
506       $target = undef;
507     }
508   }
509   $cargo_lock_update //= 0;
510   $cargo_manifest_args //=
511     (defined $oot_dir) && !$cargo_lock_update;
512
513   if ($cargo_manifest_args) {
514     push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
515       qw(--locked);
516     push @ARGV, qw(--target-dir=target) if $cargo_target_arg;
517   }
518
519   if (defined $target) {
520     if ($target =~ m{^[A-Z]}) {
521       $target = (cfgs 'arch', $target) // $archmap{$target}
522         // die "$self: --target=$target alias specified; not in cfg or map\n";
523     }
524     push @ARGV, "--target=$target";
525   }
526 }
527
528 our $oot_absdir;
529 our $build_absdir; # .../Build/<subdir>
530
531 sub oot_massage_cmdline () {
532   return unless defined $oot_dir;
533
534   my $use = cfgs qw(oot use);
535   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
536   $build_absdir = "$oot_absdir/$subdir";
537
538   my ($pre,$post);
539   my @xargs;
540   if (!$cargo_lock_update) {
541     push @xargs, $build_absdir;
542     ($pre, $post) = ('cd "$1"; shift; ', '');
543   } else {
544     push @xargs, $oot_absdir, $subdir, $src_absdir;
545     $pre =  <<'END';
546         cd "$1"; shift;
547         mkdir -p -- "$1"; cd "$1"; shift;
548         cp -- "$1"/Cargo.toml
549 END
550     $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
551               "$1"/Cargo.lock
552 ENDLK
553     $pre .= <<'ENDCP';
554                               .;
555 ENDCP
556     $pre .= <<'ENDPRE';
557         shift;
558         mkdir -p src; >src/lib.rs; >build.rs
559 ENDPRE
560     $post = <<'ENDPOST';
561         rm -r src Cargo.toml build.rs;
562 ENDPOST
563   }
564   my $addpath = (cfg_uc qw(oot path_add)) //
565     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
566   $addpath =
567     !Types::Serialiser::is_bool $addpath ? $addpath           :
568     $addpath                             ? '$HOME/.cargo/bin' :
569                                            undef;
570   if (defined $addpath) {
571     $pre .= <<END
572         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
573         export PATH;
574 END
575   }
576   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
577   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
578
579   my $getuser = sub { cfgsn qw(oot user) };
580   my @command;
581   my $xe = $verbose >= 2 ? 'xe' : 'e';
582   my $sh_ec = sub {
583     if (!length $post) {
584       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
585     } else {
586       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
587     }
588     push @command, @ARGV;
589   };
590   my $command_sh = sub {
591     my $quoted = join ' ', map {
592       return $_ if !m/\W/;
593       s/\'/\'\\'\'/g;
594       "'$_'"
595     } @ARGV;
596     @command = @_, "set -${xe}; $pre $quoted; $post";
597   };
598   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
599     if $verbose;
600   if ($use eq 'really') {
601     my $user = $getuser->();
602     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
603     my $homedir = $pw[7];
604     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
605     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
606   } elsif ($use eq 'ssh') {
607     my $user = $getuser->();
608     $user .= '@localhost' unless $user =~ m/\@/;
609     $command_sh->('ssh',$user);
610     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
611   } elsif ($use eq 'command_args') {
612     my @c = cfgn_list qw(oot command);
613     $sh_ec->(@c);
614     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
615   } elsif ($use eq 'command_sh') {
616     my @c = cfgn_list qw(oot command);
617     $command_sh->(@c);
618     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
619   } elsif ($use eq 'null') {
620     $sh_ec->();
621   } else {
622     die "$self: oot.use mode $use not recognised\n";
623   }
624   die unless @command;
625   @ARGV = @command;
626 }
627
628 sub setenvs () {
629   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
630   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
631   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
632   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
633   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
634 }
635
636 our $want_uninstall;
637
638 END {
639   if ($want_uninstall) {
640     local ($?);
641     foreach my $mf (keys %manifests) {
642       eval { uninstall1($mf,1); 1; } or warn "$@";
643     }
644     eval { unaltcargolock(1); 1; } or warn "$@";
645   }
646 }
647
648 our $cleanup_cargo_lock;
649 sub makebackups () {
650   foreach my $mf (keys %manifests) {
651     link "$mf", "$mf.unnailed" or $!==EEXIST
652       or die "$self: make backup link $mf.unnailed: $!\n";
653   }
654
655   if (defined($alt_cargo_lock)) {
656     if (@alt_cargo_lock_stat) {
657       print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
658         if $verbose>=3;
659       if (link $alt_cargo_lock, 'Cargo.lock') {
660         print STDERR " linked\n" if $verbose>=3;
661       } elsif ($! != EEXIST) {
662         print STDERR "\n" if $verbose>=3;
663         die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
664       } else {
665         print STDERR "checking quality." if $verbose>=3;
666         my @lock_stat = stat 'Cargo.lock'
667           or die "$self: stat Cargo.lock (for alt check: $!\n";
668         same_file(\@alt_cargo_lock_stat, \@lock_stat)
669           or die
670 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
671       }
672       $cleanup_cargo_lock = 1;
673     } else {
674       $cleanup_cargo_lock = 1;
675       # If Cargo.lock exists and alt doesn't, that means either
676       # that a previous run was interrupted, or that the user has
677       # messed up.
678     }
679   }
680 }
681
682 sub nailed ($) {
683   my ($mf) = @_;
684   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
685   $nailed;
686 }    
687
688 sub install () {
689   foreach my $mf (keys %manifests) {
690     my $nailing = "$mf.nailing~";
691     my $nailed = nailed($mf);
692     my ($use, $rm);
693     my $diff;
694     if (open NN, '<', $nailed) {
695       $diff = compare($nailing, \*NN);
696       die "$self: compare $nailing and $nailed: $!" if $diff<0;
697     } else {
698       $!==ENOENT or die "$self: check previous $nailed: $!\n";
699       $diff = 1;
700     }
701     if ($diff) {
702       $use = $nailing;
703       $rm  = $nailed;
704     } else {
705       $use = $nailed;
706       $rm  = $nailing;
707     }
708     rename $use, $mf or die "$self: install nailed $use: $!\n";
709     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
710     print STDERR "$self: nailed $mf\n" if $verbose>=3;
711   }
712 }
713
714 sub invoke () {
715   my $r = system @ARGV;
716   if (!$r) {
717     return 0;
718   } elsif ($r<0) {
719     print STDERR "$self: could not execute $ARGV[0]: $!\n";
720     return 127;
721   } elsif ($r & 0xff00) {
722     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
723     return $r >> 8;
724   } else {
725     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
726     return 125;
727   }
728 }
729
730 sub cargo_lock_update_after () {
731   if ($cargo_lock_update) {
732     # avoids importing File::Copy and the error handling is about as good
733     $!=0; $?=0;
734     my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
735     die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
736     die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
737   }
738 }
739
740 sub uninstall1 ($$) {
741   my ($mf, $enoentok) = @_;
742   my $unnailed = "$mf.unnailed";
743   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
744     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
745 }
746
747 sub unaltcargolock ($) {
748   my ($enoentok) = @_;
749   return unless $cleanup_cargo_lock;
750   die 'internal error!' unless defined $alt_cargo_lock;
751
752   # we ignore $enoentok because we don't know if one was supposed to
753   # have been created.
754
755   rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
756  "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
757
758   unlink 'Cargo.lock' or $!==ENOENT or die
759  "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
760   # ^ this also helps clean up the stupid rename() corner case
761 }
762
763 sub uninstall () {
764   foreach my $mf (keys %manifests) {
765     my $nailed = nailed($mf);
766     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
767     uninstall1($mf,0);
768   }
769   unaltcargolock(0);
770 }
771
772 while (@ARGV && $ARGV[0] =~ m/^-/) {
773   $_ = shift @ARGV;
774   last if m{^--$};
775   if (m{^-[^-]}) {
776     while (m{^-.}) {
777       if (s{^-v}{-}) {
778         $verbose++;
779       } elsif (s{^-q}{-}) {
780         $verbose=0;
781       } elsif (s{^-n}{-}) {
782         $noact++;
783       } elsif (s{^-D}{-}) {
784         $dump++;
785       } elsif (s{^-T(.+)}{-}s) {
786         $target = $1;
787       } elsif (s{^-([uU])}{-}) {
788         $cargo_lock_update= $1=~m/[a-z]/;
789       } elsif (s{^-([mM])}{-}) {
790         $cargo_manifest_args= $1=~m/[a-z]/;
791       } elsif (s{^-([tT])}{-}) {
792         $cargo_target_arg= $1=~m/[a-z]/;
793       } else {
794         die "$self: unknown short option(s) $_\n";
795       }
796     }
797   } elsif (s{^--target=}{}) {
798     $target = $_;
799   } elsif (m{^--(no-)?cargo-lock-update}) {
800     $cargo_lock_update= !!$1;
801   } elsif (m{^--(no-)?cargo-manifest-args}) {
802     $cargo_manifest_args= !!$1;
803   } elsif (m{^--(no-)?cargo-target-arg}) {
804     $cargo_target_arg= !!$1;
805   } else {
806     die "$self: unknown long option $_\n";
807   }
808 }
809
810 die "$self: need command to run\n" unless @ARGV || $noact;
811
812 takelock();
813 readnail();
814 consider_alt_cargo_lock();
815 consider_oot();
816 readorigs();
817 calculate();
818 addargs();
819 our @display_cmd = @ARGV;
820 oot_massage_cmdline();
821 setenvs();
822
823 if ($dump) {
824   eval '
825     use Data::Dumper;
826     print STDERR Dumper(\%manifests) if $dump>=2;
827     print STDERR Dumper(\%packagemap, \@ARGV,
828                         { src_absdir => $src_absdir,
829                           worksphere => $worksphere,
830                           subdir => $subdir,
831                           oot_dir => $oot_dir,
832                           oot_absdir => $oot_absdir,
833                           build_absdir => $build_absdir });
834   ' or die $@;
835 }
836
837 exit 0 if $noact;
838
839 $want_uninstall = 1;
840 makebackups();
841 install();
842
843 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
844   (scalar keys %manifests), (scalar keys %packagemap),
845   (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
846   if $verbose;
847
848 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
849 my $estatus = invoke();
850
851 cargo_lock_update_after();
852
853 uninstall();
854 $want_uninstall = 0;
855
856 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
857
858 exit $estatus;