chiark / gitweb /
nailing-cargo: oot_massage_cmdline: Regularise handling
[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-caretwgo make
22 #   ../nailing-cargo/nailing-cargo cargo build
23 #   CARGO='../nailing-cargo/nailing-cargo cargo' make
24
25 # Why do we need this ?
26 #
27 #  https://github.com/rust-lang/cargo/issues/6713
28 #  https://stackoverflow.com/questions/33025887/how-to-use-a-local-unpublished-crate
29 #  https://github.com/rust-lang/cargo/issues/1481
30
31 # Needs libtoml-perl
32
33 #: Cargo.nail:
34 #
35 #    [packages]
36 #    package = subdir
37 #    package = { subdir = ... }
38 #
39 #    [subdirs]
40 #    subdir
41
42 our $self;
43
44 use strict;
45 use POSIX;
46 use Types::Serialiser;
47
48 our %archmap = (
49     RPI => 'arm-unknown-linux-gnueabihf',
50 );
51
52 BEGIN {
53   $self = $0;  $self =~ s{^.*/(?=.)}{};
54   my $deref = $0;
55   while ($deref =~ m{^/}) {
56     my $link = readlink $deref;
57     if (!defined $link) {
58       $! == EINVAL
59         or die "$self: checking our script location $deref: $!\n";
60       $deref =~ s{/[^/]+$}{}
61         or die "$self: unexpected script path: $deref\n";
62       unshift @INC, $deref."/TOML-Tiny/lib";
63       last;
64     }
65     last if $link !~ m{^/};
66     $deref = $link;
67   }
68 }
69
70 use Fcntl qw(LOCK_EX);
71 use File::Compare;
72 use TOML::Tiny::Faithful;
73
74 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
75
76 our $worksphere = $src_absdir;
77 $worksphere =~ s{/([^/]+)$}{}
78   or die "$self: cwd \`$worksphere' unsupported!\n";
79 our $subdir = $1; # leafname
80
81 our $lockfile = "../.nailing-cargo.lock";
82
83 our $cargo_lock_update;
84 our $cargo_manifest_args;
85
86 our @configs;
87 our $verbose=1;
88 our ($noact,$dump);
89 our $target;
90
91 sub read_or_enoent ($) {
92   my ($fn) = @_;
93   if (!open R, '<', $fn) {
94     return undef if $!==ENOENT;
95     die "$self: open $fn: $!\n";
96   }
97   local ($/) = undef;
98   my ($r) = <R> // die "$self: read $fn: $!\n";
99   $r;
100 }
101
102 sub stat_exists ($$) {
103   my ($fn, $what) = @_;
104   if (stat $fn) { return 1; }
105   $!==ENOENT or die "$self: stat $what: $fn: $!\n";
106   return 0;
107 }
108
109 sub toml_or_enoent ($$) {
110   my ($f,$what) = @_;
111   my $toml = read_or_enoent($f) // return;
112   my ($v,$e) = from_toml($toml);
113   if (!defined $v) {
114     chomp $e;
115     die "$self: parse TOML: $what: $f: $e\n";
116   }
117   die "$e ?" if length $e;
118   $v;
119 }
120
121 sub load1config ($) {
122   my ($f) = @_;
123   my $toml = toml_or_enoent($f, "config file");
124   push @configs, $toml if defined $toml;
125 }
126
127 sub loadconfigs () {
128   my $cfgleaf = ".nailing-cargo-cfg.toml";
129   load1config("/etc/nailing-cargo/cfg.toml");
130   load1config("$worksphere/$cfgleaf");
131   load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
132 }
133
134 sub getcfg ($$) {
135   my ($k, $def) = @_;
136   foreach my $cfg (@configs) {
137     my $v = $cfg->{$k};
138     return $v if defined $v;
139   }
140   return $def;
141 }
142
143 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
144
145 sub same_file ($$) {
146   my ($x,$y) = @_;
147   "@$x[0..5]" eq "@$y[0..5]";
148 }
149
150 sub takelock () {
151   for (;;) {
152     open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
153     flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
154     my @fstat = stat LOCK or die "$self: fstat: $!\n";
155     my @stat  = stat $lockfile;
156     if (!@stat) {
157       next if $! == ENOENT;
158       die "$self: stat $lockfile: $!\n";
159     }
160     last if same_file(\@fstat,\@stat);
161   }
162 }
163 sub unlock () {
164   unlink $lockfile or die "$self: removing lockfile: $!\n";
165 }
166
167 our $nail;
168
169 sub badcfg {
170   my $m = pop @_;
171   $" = '.';
172   die "$self: config key \`@_': $m\n";
173 }
174
175 sub cfg_uc {
176   my $v = $nail;
177   foreach my $k (@_) {
178     last unless defined $v;
179     ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
180     $v = $v->{$k};
181   }
182   return $v;
183 }
184
185 sub cfge {
186   my $exp = shift @_;
187   my $v = cfg_uc @_;
188   my $got = ref($v) || 'scalar';
189   return $v if !defined($v) || $got eq $exp;
190   badcfg @_, "found \L$got\E, expected \L$exp\E";
191   # ^ toml doesn't make refs to scalars, so this is unambiguous
192 }
193
194 sub cfgn {
195   my $exp = shift @_;
196   (cfge $exp, @_) // badcfg @_, "missing";
197 }
198
199 sub cfgs  { cfge 'scalar', @_ }
200 sub cfgsn { cfgn 'scalar', @_ }
201
202 sub cfgn_list {
203   my $l = cfge 'ARRAY', @_;
204   foreach my $x (@$l) {
205     !ref $x or badcfg @_, "list contains non-scalar element";
206   }
207   @$l
208 }
209
210 sub readnail () {
211   my $nailfile = "../Cargo.nail";
212   open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
213   local ($/) = undef;
214   my $toml = <N> // die "$self: read $nailfile: $!";
215   my $transformed;
216   if ($toml !~ m{^\s*\[/}m &&
217       $toml !~ m{^[^\n\#]*\=}m &&
218       # old non-toml syntax
219       $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
220     $toml =~ s{^}{[packages\]\n};
221     my @sd;
222     $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
223       push @sd, $1; '';
224     }mige;
225     $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
226     $transformed = 1;
227   }
228   my $e;
229   ($nail,$e) = from_toml($toml);
230   if (!defined $nail) {
231     if ($transformed) {
232       $toml =~ s/^/    /mg;
233       print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
234     }
235     $/="\n"; chomp $e;
236     die "$self: parse $nailfile: $e\n";
237   }
238   die "$e ?" if length $e;
239
240   if (!ref $nail->{subdirs}) {
241     $nail->{subdirs} = [
242       grep /^[^\#]/,
243       map { s/^\s+//; s/\s+$//; $_; }
244       split m{\n},
245       $nail->{subdirs}
246     ];
247   }
248 }
249
250 our $oot_dir;      # oot.dir or "Build"
251
252 sub consider_oot () {
253   $oot_dir = cfgs qw(oot dir);
254   my $use = cfgs qw(oot use);
255   unless (defined($oot_dir) || defined($use)) {
256     $cargo_lock_update//=0;
257     return;
258   }
259   $oot_dir //= 'Build';
260 }
261
262 our %manifests;
263 our %packagemap;
264
265 sub read_manifest ($) {
266   my ($subdir) = @_;
267   my $manifest = "../$subdir/Cargo.toml";
268   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
269   if (defined $manifests{$manifest}) {
270     print STDERR
271  "$self: warning: $subdir: specified more than once!\n";
272     return undef;
273   }
274   foreach my $try ("$manifest.unnailed", "$manifest") {
275     my $toml = toml_or_enoent($try, "package manifest") // next;
276     my $p = $toml->{package}{name};
277     if (!defined $p) {
278       print STDERR
279  "$self: warning: $subdir: missing package.name in $try, ignoring\n";
280       next;
281     }
282     $manifests{$manifest} = $toml;
283     return $p;
284   }
285   return undef;
286 }
287
288 sub readorigs () {
289   foreach my $p (keys %{ $nail->{packages} }) {
290     my $v = $nail->{packages}{$p};
291     my $subdir = ref($v) ? $v->{subdir} : $v;
292     my $gotpackage = read_manifest($subdir) // '<nothing!>';
293     if ($gotpackage ne $p) {
294       print STDERR
295  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
296     }
297     die if defined $packagemap{$p};
298     $packagemap{$p} = $subdir;
299   }
300   foreach my $subdir (@{ $nail->{subdirs} }) {
301     my $gotpackage = read_manifest($subdir);
302     if (!defined $gotpackage) {
303       print STDERR
304  "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
305       next;
306     }
307     $packagemap{$gotpackage} //= $subdir;
308   }
309 }
310
311 sub calculate () {
312   foreach my $p (sort keys %packagemap) {
313     print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
314   }
315   foreach my $mf (keys %manifests) {
316     my $toml = $manifests{$mf};
317     foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
318       my $deps = $toml->{$k};
319       next unless $deps;
320       foreach my $p (keys %packagemap) {
321         my $info = $deps->{$p};
322         next unless defined $info;
323         $deps->{$p} = $info = { } unless ref $info;
324         delete $info->{version};
325         $info->{path} = $worksphere.'/'.$packagemap{$p};
326       }
327     }
328     my $nailing = "$mf.nailing~";
329     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
330     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
331     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
332     close N or die "$self: close new $nailing: $!\n";
333   }
334 }
335
336 sub addargs () {
337   if (@ARGV>=2 &&
338       $ARGV[0] =~ m{\bcargo\b} &&
339       $ARGV[1] =~ m/generate-lockfile|update/) {
340     $cargo_lock_update //= 1;
341   } else {
342     $cargo_lock_update //= 0;
343   }
344   $cargo_manifest_args //=
345     (defined $oot_dir) && !$cargo_lock_update;
346
347   if ($cargo_manifest_args) {
348     push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
349       qw(--locked --target-dir=target);
350   }
351
352   if (defined $target) {
353     if ($target =~ m{^[A-Z]}) {
354       $target = (cfgs 'arch', $target) // $archmap{$target}
355         // die "$self: --target=$target alias specified; not in cfg or map\n";
356     }
357     push @ARGV, "--target=$target";
358   }
359 }
360
361 our $oot_absdir;
362 our $build_absdir; # .../Build/<subdir>
363
364 sub oot_massage_cmdline () {
365   return unless defined $oot_dir;
366
367   my $use = cfgs qw(oot use);
368   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
369   $build_absdir = "$oot_absdir/$subdir";
370
371   my ($pre,$post);
372   my @xargs;
373   if (!$cargo_lock_update) {
374     push @xargs, $build_absdir;
375     ($pre, $post) = ('cd "$1"; shift; ', '');
376   } else {
377     push @xargs, $oot_absdir, $subdir, $src_absdir;
378     $pre =  <<'END';
379         cd "$1"; shift;
380         mkdir -p -- "$1"; cd "$1"; shift;
381         cp -- "$1"/Cargo.toml .;
382 END
383     $pre .= <<'END';
384         cp -- "$1"/Cargo.lock .;
385 END
386     $pre .= <<'ENDLK';
387         cp -- "$1"/Cargo.lock .;
388 ENDLK
389     $pre .= <<'ENDPRE';
390         shift;
391         mkdir -p src; >src/lib.rs;
392 ENDPRE
393     $post = <<'ENDPOST';
394         rm -r src Cargo.toml;
395 ENDPOST
396   }
397   my $addpath = (cfg_uc qw(oot path_add)) //
398     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
399   $addpath =
400     !Types::Serialiser::is_bool $addpath ? $addpath           :
401     $addpath                             ? '$HOME/.cargo/bin' :
402                                            undef;
403   if (defined $addpath) {
404     $pre .= <<END
405         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
406         export PATH;
407 END
408   }
409   $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
410   $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
411
412   my $getuser = sub { cfgsn qw(oot user) };
413   my @command;
414   my $xe = $verbose >= 2 ? 'xe' : 'e';
415   my $sh_ec = sub {
416     if (!length $post) {
417       @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
418     } else {
419       @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
420     }
421     push @command, @ARGV;
422   };
423   my $command_sh = sub {
424     my $quoted = join ' ', map {
425       return $_ if !m/\W/;
426       s/\'/\'\\'\'/g;
427       "'$_'"
428     } @ARGV;
429     @command = @_, "set -${xe}; $pre $quoted; $post";
430   };
431   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
432     if $verbose;
433   if ($use eq 'really') {
434     my $user = $getuser->();
435     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
436     my $homedir = $pw[7];
437     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
438     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
439   } elsif ($use eq 'ssh') {
440     my $user = $getuser->();
441     $user .= '@localhost' unless $user =~ m/\@/;
442     $command_sh->('ssh',$user);
443     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
444   } elsif ($use eq 'command_args') {
445     my @c = cfgn_list qw(oot command);
446     $sh_ec->(@c);
447     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
448   } elsif ($use eq 'command_sh') {
449     my @c = cfgn_list qw(oot command);
450     $command_sh->(@c);
451     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
452   } elsif ($use eq 'null') {
453     $sh_ec->();
454   } else {
455     die "$self: oot.use mode $use not recognised\n";
456   }
457   die unless @command;
458   @ARGV = @command;
459 }
460
461 sub setenvs () {
462   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
463   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
464   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
465   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
466   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
467 }
468
469 our $want_uninstall;
470
471 END {
472   if ($want_uninstall) {
473     local ($?);
474     foreach my $mf (keys %manifests) {
475       eval { uninstall1($mf,1); 1; } or warn "$@";
476     }
477   }
478 }
479
480 sub makebackups () {
481   foreach my $mf (keys %manifests) {
482     link "$mf", "$mf.unnailed" or $!==EEXIST
483       or die "$self: make backup link $mf.unnailed: $!\n";
484   }
485 }
486
487 sub nailed ($) {
488   my ($mf) = @_;
489   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
490   $nailed;
491 }    
492
493 sub install () {
494   foreach my $mf (keys %manifests) {
495     my $nailing = "$mf.nailing~";
496     my $nailed = nailed($mf);
497     my ($use, $rm);
498     my $diff;
499     if (open NN, '<', $nailed) {
500       $diff = compare($nailing, \*NN);
501       die "$self: compare $nailing and $nailed: $!" if $diff<0;
502     } else {
503       $!==ENOENT or die "$self: check previous $nailed: $!\n";
504       $diff = 1;
505     }
506     if ($diff) {
507       $use = $nailing;
508       $rm  = $nailed;
509     } else {
510       $use = $nailed;
511       $rm  = $nailing;
512     }
513     rename $use, $mf or die "$self: install nailed $use: $!\n";
514     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
515     print STDERR "$self: nailed $mf\n" if $verbose>=3;
516   }
517 }
518
519 sub invoke () {
520   my $r = system @ARGV;
521   if (!$r) {
522     return 0;
523   } elsif ($r<0) {
524     print STDERR "$self: could not execute $ARGV[0]: $!\n";
525     return 127;
526   } elsif ($r & 0xff00) {
527     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
528     return $r >> 8;
529   } else {
530     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
531     return 125;
532   }
533 }
534
535 sub cargo_lock_update_after () {
536   return unless $cargo_lock_update;
537   # avoids importing File::Copy and the error handling is about as good
538   $!=0; $?=0;
539   my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
540   die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
541   die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
542 }
543
544 sub uninstall1 ($$) {
545   my ($mf, $enoentok) = @_;
546   my $unnailed = "$mf.unnailed";
547   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
548     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
549 }
550
551 sub uninstall () {
552   foreach my $mf (keys %manifests) {
553     my $nailed = nailed($mf);
554     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
555     uninstall1($mf,0);
556   }
557 }
558
559 while (@ARGV && $ARGV[0] =~ m/^-/) {
560   $_ = shift @ARGV;
561   last if m{^--$};
562   if (m{^-[^-]}) {
563     while (m{^-.}) {
564       if (s{^-v}{-}) {
565         $verbose++;
566       } elsif (s{^-q}{-}) {
567         $verbose=0;
568       } elsif (s{^-n}{-}) {
569         $noact++;
570       } elsif (s{^-D}{-}) {
571         $dump++;
572       } elsif (s{^-T(.+)}{-}s) {
573         $target = $1;
574       } elsif (s{^-([uU])}{-}) {
575         $cargo_lock_update= $1=~m/[a-z]/;
576       } elsif (s{^-([mM])}{-}) {
577         $cargo_manifest_args= $1=~m/[a-z]/;
578       } else {
579         die "$self: unknown short option(s) $_\n";
580       }
581     }
582   } elsif (s{^--target=}{}) {
583     $target = $_;
584   } elsif (m{^--(no-)?cargo-lock-update}) {
585     $cargo_lock_update= !!$1;
586   } elsif (m{^--(no-)?cargo-manifest-args}) {
587     $cargo_manifest_args= !!$1;
588   } else {
589     die "$self: unknown long option $_\n";
590   }
591 }
592
593 die "$self: need command to run\n" unless @ARGV || $noact;
594
595 takelock();
596 readnail();
597 consider_oot();
598 readorigs();
599 calculate();
600 addargs();
601 our @display_cmd = @ARGV;
602 oot_massage_cmdline();
603 setenvs();
604
605 if ($dump) {
606   eval '
607     use Data::Dumper;
608     print STDERR Dumper(\%manifests) if $dump>=2;
609     print STDERR Dumper(\%packagemap, \@ARGV,
610                         { src_absdir => $src_absdir,
611                           worksphere => $worksphere,
612                           subdir => $subdir,
613                           oot_dir => $oot_dir,
614                           oot_absdir => $oot_absdir,
615                           build_absdir => $build_absdir });
616   ' or die $@;
617 }
618
619 exit 0 if $noact;
620
621 $want_uninstall = 1;
622 makebackups();
623 install();
624
625 printf STDERR "$self: nailed (%s manifests, %s packages)\n",
626   (scalar keys %manifests), (scalar keys %packagemap)
627   if $verbose;
628
629 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
630 my $estatus = invoke();
631
632 uninstall();
633 $want_uninstall = 1;
634
635 cargo_lock_update_after();
636
637 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
638
639 exit $estatus;