nix(feat): Add argbash support to checked-shell-script

Each postgrest- script now has a -h/--help option showing the
checked-shell-script.docs argument.

Additional CLI arguments can be defined through the
checked-shell-script.args argument using the argbash template syntax:
https://argbash.readthedocs.io/en/stable/guide.html
This commit is contained in:
Wolfgang Walther
2021-04-18 13:51:39 +02:00
committed by Wolfgang Walther
parent 39d4646a4c
commit c8edfac39e
4 changed files with 82 additions and 23 deletions
@@ -1,23 +1,51 @@
# Create a bash script that is checked with shellcheck. You can either use it
# directly, or use the .bin attribute to get the script in a bin/ directory,
# to be used in a path for example.
{ git
{ argbash
, bash_5
, git
, lib
, runCommand
, runtimeShell
, shellcheck
, stdenv
, writeTextFile
}:
# TODO: do something sensible with docs, e.g. provide automated --help
{ name
, docs
, args ? [ ]
, inRootDir ? false
, redirectTixFiles ? true
, withEnv ? null
, withTmpDir ? false
}: text:
let
argsTemplate =
let
# square brackets are a pain to escape - if even possible. just don't use them...
escapedDocs = builtins.replaceStrings [ "\n" ] [ " \\n" ] docs;
in
writeTextFile {
inherit name;
destination = "/${name}.m4"; # destination is needed to have the proper basename for completion
text =
''
# BASH_ARGV0 sets $0 - which is used in parser.sh for usage information
# stripping the /nix/store/... path for nicer display
BASH_ARGV0="$(basename "$0")"
# ARG_HELP([${name}], [${escapedDocs}])
${lib.strings.concatMapStrings (arg: "# " + arg) args}
# ARG_DEFAULTS_POS()
# ARGBASH_GO
'';
};
argsParser =
runCommand "${name}-parser" { }
"${argbash}/bin/argbash -o $out ${argsTemplate}/${name}.m4";
bin =
writeTextFile {
inherit name;
@@ -26,15 +54,19 @@ let
text =
''
#!${runtimeShell}
#!${bash_5}/bin/bash
set -euo pipefail
source ${argsParser}
''
+ lib.optionalString redirectTixFiles ''
# storing tix files in a temporary throw away directory avoids mix/tix conflicts after changes
hpctixdir=$(mktemp -d)
export HPCTIXFILE="$hpctixdir"/postgrest.tix
trap 'rm -rf $hpctixdir' EXIT
''
+ lib.optionalString inRootDir ''
cd "$(${git}/bin/git rev-parse --show-toplevel)"
@@ -44,6 +76,7 @@ let
exit 1
fi
''
+ lib.optionalString withTmpDir ''
tmpdir="$(mktemp -d)"
@@ -52,11 +85,14 @@ let
# remove the tmpdir when cancelled (postgrest-watch)
trap 'rm -rf "$tmpdir"' SIGINT SIGTERM
''
+ lib.optionalString (withEnv != null) ''
env="$(cat ${withEnv})"
export PATH="$env/bin:$PATH"
''
+ "(${text})"
+ lib.optionalString withTmpDir ''
rm -rf "$tmpdir"
@@ -68,7 +104,7 @@ let
${stdenv.shell} -n $out/bin/${name}
# check for shellcheck recommendations
${shellcheck}/bin/shellcheck $out/bin/${name}
${shellcheck}/bin/shellcheck -x $out/bin/${name}
'';
};