nix-actions/modules/workflows.nix

140 lines
3.2 KiB
Nix
Raw Normal View History

2024-11-11 16:29:36 +01:00
{
config,
lib,
pkgs,
...
}:
let
inherit (lib)
attrNames
concatMapStringsSep
concatStringsSep
getExe
getExe'
mapAttrsToList
mkOption
optionalString
;
inherit (lib.types)
attrsOf
bool
enum
path
2024-11-11 16:29:36 +01:00
str
;
inherit (pkgs) action-validator remarshal runCommand;
2024-11-11 16:29:36 +01:00
cfg = config;
generate =
name: value:
runCommand "${name}.yaml"
2024-11-11 16:29:36 +01:00
{
nativeBuildInputs = [
action-validator
remarshal
];
2024-11-11 16:29:36 +01:00
value = builtins.toJSON value;
passAsFile = [ "value" ];
preferLocalBuild = true;
}
''
json2yaml "$valuePath" "$out"
2024-11-11 16:29:36 +01:00
# Check that the workflow is valid
cd "${cfg.rootSrc}" && action-validator "$out"
'';
2024-11-11 16:29:36 +01:00
install =
name: value:
let
result = generate name value;
path = ".${cfg.platform}/workflows/${name}.yaml";
in
''
if [ ! -f "$GIT_WC/${path}" ] || ! ${getExe' pkgs.diffutils "cmp"} -s "$GIT_WC/${path}" ${result} ; then
# Copy the updated workflow definition
cp --no-preserve=mode,ownership ${result} "$GIT_WC/${path}" && echo "nix-actions: Updated ${name}.yaml"
fi
'';
in
{
options = {
platform = mkOption {
type = enum [
"forgejo"
"gitea"
"github"
];
default = "forgejo";
description = ''
The platform where the workflows will run.
This will induce the directory in which the yaml files are installed.
'';
};
workflows = mkOption {
type = attrsOf (pkgs.formats.yaml { }).type;
description = ''
Set of workflows to install.
'';
};
installationScript = mkOption {
type = str;
description = ''
A bash snippet that installs the workflows files in the current project.
'';
readOnly = true;
};
removeUnknown = mkOption {
type = bool;
default = true;
description = ''
Whether to remove unknown workflow files.
'';
};
rootSrc = mkOption {
type = path;
description = ''
The source of the project.
'';
};
2024-11-11 16:29:36 +01:00
};
config = {
installationScript = ''
if ! type -t git >/dev/null; then
# This happens in pure shells, including lorri
echo 1>&2 "WARNING: nix-actions: git command not found; skipping installation."
elif ! git rev-parse --git-dir &> /dev/null; then
echo 1>&2 "WARNING: nix-actions: .git not found; skipping installation."
else
GIT_WC=`git rev-parse --show-toplevel`
# Ensure that the directory exists
mkdir -p "$GIT_WC/.${cfg.platform}/workflows"
# Install the workflow files
${concatStringsSep "\n" (mapAttrsToList install cfg.workflows)}
${optionalString cfg.removeUnknown ''
# Remove unknown workflow files
for file in $(ls "$GIT_WC/.${cfg.platform}/workflows" | ${getExe pkgs.gnugrep} -v '\(${
concatMapStringsSep "\\|" (name: "${name}.yaml") (attrNames cfg.workflows)
2024-11-11 16:29:36 +01:00
}\)'); do
rm "$GIT_WC/.${cfg.platform}/workflows/$file" && echo "nix-actions: Removed $file"
done
''}
fi
'';
};
}