lib: reformat code

This commit is contained in:
Gabriel Arazas 2025-01-12 17:57:14 +08:00
parent 2f93b33e0c
commit 171d8f797d
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
18 changed files with 393 additions and 543 deletions

View File

@ -4,6 +4,5 @@
{ dir, name ? baseNameOf dir, keyfiles, profile }@args: { dir, name ? baseNameOf dir, keyfiles, profile }@args:
runCommand "dconf-${name}" { runCommand "dconf-${name}" { nativeBuildInputs = [ (lib.getBin dconf) ]; }
nativeBuildInputs = [ (lib.getBin dconf) ]; "dconf compile $out ${dir}"
} "dconf compile $out ${dir}"

View File

@ -18,14 +18,7 @@
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{ { hugo, go, cacert, git, lib, stdenv, }:
hugo,
go,
cacert,
git,
lib,
stdenv,
}:
# A modified Go builder for generating a website with Hugo. Since it relies on # A modified Go builder for generating a website with Hugo. Since it relies on
# Hugo modules (which is basically wrapper around Go modules), this can be used # Hugo modules (which is basically wrapper around Go modules), this can be used
@ -34,297 +27,227 @@
# Take note, this doesn't work for Hugo projects with remote resources # Take note, this doesn't work for Hugo projects with remote resources
# right in the content since Hugo allows network access when generating # right in the content since Hugo allows network access when generating
# the website. # the website.
{ { name ? "${args'.pname}-${args'.version}",
name ? "${args'.pname}-${args'.version}",
nativeBuildInputs ? [ ], nativeBuildInputs ? [ ], passthru ? { },
passthru ? { },
# A function to override the goModules derivation # A function to override the goModules derivation
overrideModAttrs ? (_oldAttrs: { }), overrideModAttrs ? (_oldAttrs: { }),
# path to go.mod and go.sum directory # path to go.mod and go.sum directory
modRoot ? "./", modRoot ? "./",
# vendorHash is the SRI hash of the vendored dependencies # vendorHash is the SRI hash of the vendored dependencies
# #
# if vendorHash is null, then we won't fetch any dependencies and # if vendorHash is null, then we won't fetch any dependencies and
# rely on the vendor folder within the source. # rely on the vendor folder within the source.
vendorHash ? throw ( vendorHash ? throw (if args' ? vendorSha256 then
if args' ? vendorSha256 then "buildHugoSite: Expect vendorHash instead of vendorSha256"
"buildHugoSite: Expect vendorHash instead of vendorSha256" else
else "buildHugoSite: vendorHash is missing"),
"buildHugoSite: vendorHash is missing"
),
# Whether to delete the vendor folder supplied with the source. # Whether to delete the vendor folder supplied with the source.
deleteVendor ? false, deleteVendor ? false,
# Whether to fetch (go mod download) and proxy the vendor directory. # Whether to fetch (go mod download) and proxy the vendor directory.
# This is useful if your code depends on c code and go mod tidy does not # This is useful if your code depends on c code and go mod tidy does not
# include the needed sources to build or if any dependency has case-insensitive # include the needed sources to build or if any dependency has case-insensitive
# conflicts which will produce platform dependant `vendorHash` checksums. # conflicts which will produce platform dependant `vendorHash` checksums.
proxyVendor ? false, proxyVendor ? false,
# We want parallel builds by default # We want parallel builds by default
enableParallelBuilding ? true, enableParallelBuilding ? true,
# Do not enable this without good reason # Do not enable this without good reason
# IE: programs coupled with the compiler # IE: programs coupled with the compiler
allowGoReference ? false, allowGoReference ? false,
CGO_ENABLED ? go.CGO_ENABLED, CGO_ENABLED ? go.CGO_ENABLED,
meta ? { }, meta ? { },
ldflags ? [ ], ldflags ? [ ],
GOFLAGS ? [ ], GOFLAGS ? [ ],
... ... }@args':
}@args':
let let
args = removeAttrs args' [ args = removeAttrs args' [ "overrideModAttrs" "vendorSha256" "vendorHash" ];
"overrideModAttrs"
"vendorSha256"
"vendorHash"
];
GO111MODULE = "on"; GO111MODULE = "on";
GOTOOLCHAIN = "local"; GOTOOLCHAIN = "local";
hugoModules = hugoModules = if (vendorHash == null) then
if (vendorHash == null) then ""
"" else
else (stdenv.mkDerivation {
(stdenv.mkDerivation { name = "${name}-hugo-modules";
name = "${name}-hugo-modules";
nativeBuildInputs = (args.nativeBuildInputs or [ ]) ++ [ nativeBuildInputs = (args.nativeBuildInputs or [ ])
hugo ++ [ hugo go git cacert ];
go
git
cacert
];
inherit (args) src;
inherit (go) GOOS GOARCH;
inherit GO111MODULE GOTOOLCHAIN;
# The following inheritence behavior is not trivial to expect, and some may
# argue it's not ideal. Changing it may break vendor hashes in Nixpkgs and
# out in the wild. In anycase, it's documented in:
# doc/languages-frameworks/go.section.md
prePatch = args.prePatch or "";
patches = args.patches or [ ];
patchFlags = args.patchFlags or [ ];
postPatch = args.postPatch or "";
preBuild = args.preBuild or "";
postBuild = args.modPostBuild or "";
sourceRoot = args.sourceRoot or "";
setSourceRoot = args.setSourceRoot or "";
env = args.env or { };
impureEnvVars = lib.fetchers.proxyImpureEnvVars ++ [
"GIT_PROXY_COMMAND"
"SOCKS_SERVER"
"GOPROXY"
];
configurePhase =
args.modConfigurePhase or ''
runHook preConfigure
export GOCACHE=$TMPDIR/go-cache
export GOPATH="$TMPDIR/go"
cd "${modRoot}"
runHook postConfigure
'';
buildPhase =
args.modBuildPhase or (
''
runHook preBuild
''
+ lib.optionalString deleteVendor ''
if [ ! -d _vendor ]; then
echo "_vendor folder does not exist, 'deleteVendor' is not needed"
exit 10
else
rm -rf _vendor
fi
''
+ ''
if [ -d _vendor ]; then
echo "_vendor folder exists, please set 'vendorHash = null;' in your expression"
exit 10
fi
${
if proxyVendor then
''
mkdir -p "''${GOPATH}/pkg/mod/cache/download"
hugo mod vendor
''
else
''
if (( "''${NIX_DEBUG:-0}" >= 1 )); then
hugoModVendorFlags+=(-v)
fi
hugo mod vendor "''${hugoModVendorFlags[@]}"
''
}
mkdir -p _vendor
runHook postBuild
''
);
installPhase =
args.modInstallPhase or ''
runHook preInstall
${
if proxyVendor then
''
rm -rf "''${GOPATH}/pkg/mod/cache/download/sumdb"
cp -r --reflink=auto "''${GOPATH}/pkg/mod/cache/download" $out
''
else
''
cp -r --reflink=auto _vendor $out
''
}
if ! [ "$(ls -A $out)" ]; then
echo "_vendor folder is empty, please set 'vendorHash = null;' in your expression"
exit 10
fi
runHook postInstall
'';
dontFixup = true;
outputHashMode = "recursive";
outputHash = vendorHash;
# Handle empty vendorHash; avoid
# error: empty hash requires explicit hash algorithm
outputHashAlgo = if vendorHash == "" then "sha256" else null;
}).overrideAttrs
overrideModAttrs;
package = stdenv.mkDerivation (
args
// {
nativeBuildInputs = [
hugo
git
go
] ++ nativeBuildInputs;
inherit (args) src;
inherit (go) GOOS GOARCH; inherit (go) GOOS GOARCH;
inherit GO111MODULE GOTOOLCHAIN;
GOFLAGS = # The following inheritence behavior is not trivial to expect, and some may
GOFLAGS # argue it's not ideal. Changing it may break vendor hashes in Nixpkgs and
++ # out in the wild. In anycase, it's documented in:
lib.warnIf (lib.any (lib.hasPrefix "-mod=") GOFLAGS) # doc/languages-frameworks/go.section.md
"use `proxyVendor` to control Go module/vendor behavior instead of setting `-mod=` in GOFLAGS" prePatch = args.prePatch or "";
(lib.optional (!proxyVendor) "-mod=vendor") patches = args.patches or [ ];
++ patchFlags = args.patchFlags or [ ];
lib.warnIf (builtins.elem "-trimpath" GOFLAGS) postPatch = args.postPatch or "";
"`-trimpath` is added by default to GOFLAGS by buildHugoSite when allowGoReference isn't set to true" preBuild = args.preBuild or "";
(lib.optional (!allowGoReference) "-trimpath"); postBuild = args.modPostBuild or "";
inherit sourceRoot = args.sourceRoot or "";
CGO_ENABLED setSourceRoot = args.setSourceRoot or "";
enableParallelBuilding env = args.env or { };
GO111MODULE
GOTOOLCHAIN
;
# If not set to an explicit value, set the buildid empty for reproducibility. impureEnvVars = lib.fetchers.proxyImpureEnvVars
ldflags = ldflags ++ lib.optional (!lib.any (lib.hasPrefix "-buildid=") ldflags) "-buildid="; ++ [ "GIT_PROXY_COMMAND" "SOCKS_SERVER" "GOPROXY" ];
configurePhase = configurePhase = args.modConfigurePhase or ''
args.configurePhase or ( runHook preConfigure
'' export GOCACHE=$TMPDIR/go-cache
runHook preConfigure export GOPATH="$TMPDIR/go"
cd "${modRoot}"
runHook postConfigure
'';
export GOCACHE=$TMPDIR/go-cache buildPhase = args.modBuildPhase or (''
export GOPATH="$TMPDIR/go" runHook preBuild
export GOPROXY=off '' + lib.optionalString deleteVendor ''
export GOSUMDB=off if [ ! -d _vendor ]; then
cd "$modRoot" echo "_vendor folder does not exist, 'deleteVendor' is not needed"
'' exit 10
+ lib.optionalString (vendorHash != null) '' else
${ rm -rf _vendor
if proxyVendor then fi
'' '' + ''
export GOPROXY=file://${hugoModules} if [ -d _vendor ]; then
'' echo "_vendor folder exists, please set 'vendorHash = null;' in your expression"
else exit 10
'' fi
rm -rf _vendor
cp -r --reflink=auto ${hugoModules} _vendor
''
}
''
+ ''
# currently pie is only enabled by default in pkgsMusl ${if proxyVendor then ''
# this will respect the `hardening{Disable,Enable}` flags if set mkdir -p "''${GOPATH}/pkg/mod/cache/download"
if [[ $NIX_HARDENING_ENABLE =~ "pie" ]]; then hugo mod vendor
export GOFLAGS="-buildmode=pie $GOFLAGS" '' else ''
fi if (( "''${NIX_DEBUG:-0}" >= 1 )); then
hugoModVendorFlags+=(-v)
fi
hugo mod vendor "''${hugoModVendorFlags[@]}"
''}
runHook postConfigure mkdir -p _vendor
''
);
buildPhase = runHook postBuild
args.buildPhase or '' '');
runHook preBuild
hugo "''${buildFlags[@]}" --destination public
runHook postBuild
'';
doCheck = args.doCheck or true; installPhase = args.modInstallPhase or ''
checkPhase = runHook preInstall
args.checkPhase or ''
runHook preCheck
runHook postCheck ${if proxyVendor then ''
''; rm -rf "''${GOPATH}/pkg/mod/cache/download/sumdb"
cp -r --reflink=auto "''${GOPATH}/pkg/mod/cache/download" $out
'' else ''
cp -r --reflink=auto _vendor $out
''}
installPhase = if ! [ "$(ls -A $out)" ]; then
args.installPhase or '' echo "_vendor folder is empty, please set 'vendorHash = null;' in your expression"
runHook preInstall exit 10
fi
mkdir -p $out runHook postInstall
cp -r public/* $out '';
runHook postInstall dontFixup = true;
'';
strictDeps = true; outputHashMode = "recursive";
outputHash = vendorHash;
# Handle empty vendorHash; avoid
# error: empty hash requires explicit hash algorithm
outputHashAlgo = if vendorHash == "" then "sha256" else null;
}).overrideAttrs overrideModAttrs;
disallowedReferences = lib.optional (!allowGoReference) go; package = stdenv.mkDerivation (args // {
nativeBuildInputs = [ hugo git go ] ++ nativeBuildInputs;
passthru = passthru // { inherit (go) GOOS GOARCH;
inherit
go
hugo
hugoModules
vendorHash
;
};
meta = { GOFLAGS = GOFLAGS ++ lib.warnIf (lib.any (lib.hasPrefix "-mod=") GOFLAGS)
# Add default meta information "use `proxyVendor` to control Go module/vendor behavior instead of setting `-mod=` in GOFLAGS"
platforms = go.meta.platforms or lib.platforms.all; (lib.optional (!proxyVendor) "-mod=vendor")
} // meta; ++ lib.warnIf (builtins.elem "-trimpath" GOFLAGS)
} "`-trimpath` is added by default to GOFLAGS by buildHugoSite when allowGoReference isn't set to true"
); (lib.optional (!allowGoReference) "-trimpath");
in inherit CGO_ENABLED enableParallelBuilding GO111MODULE GOTOOLCHAIN;
package
# If not set to an explicit value, set the buildid empty for reproducibility.
ldflags = ldflags
++ lib.optional (!lib.any (lib.hasPrefix "-buildid=") ldflags)
"-buildid=";
configurePhase = args.configurePhase or (''
runHook preConfigure
export GOCACHE=$TMPDIR/go-cache
export GOPATH="$TMPDIR/go"
export GOPROXY=off
export GOSUMDB=off
cd "$modRoot"
'' + lib.optionalString (vendorHash != null) ''
${if proxyVendor then ''
export GOPROXY=file://${hugoModules}
'' else ''
rm -rf _vendor
cp -r --reflink=auto ${hugoModules} _vendor
''}
'' + ''
# currently pie is only enabled by default in pkgsMusl
# this will respect the `hardening{Disable,Enable}` flags if set
if [[ $NIX_HARDENING_ENABLE =~ "pie" ]]; then
export GOFLAGS="-buildmode=pie $GOFLAGS"
fi
runHook postConfigure
'');
buildPhase = args.buildPhase or ''
runHook preBuild
hugo "''${buildFlags[@]}" --destination public
runHook postBuild
'';
doCheck = args.doCheck or true;
checkPhase = args.checkPhase or ''
runHook preCheck
runHook postCheck
'';
installPhase = args.installPhase or ''
runHook preInstall
mkdir -p $out
cp -r public/* $out
runHook postInstall
'';
strictDeps = true;
disallowedReferences = lib.optional (!allowGoReference) go;
passthru = passthru // { inherit go hugo hugoModules vendorHash; };
meta = {
# Add default meta information
platforms = go.meta.platforms or lib.platforms.all;
} // meta;
});
in package

View File

@ -6,24 +6,25 @@
typically in lowercase ASCII. typically in lowercase ASCII.
*/ */
{ {
# An optional string containing the name of the desktop to be associated # An optional string containing the name of the desktop to be associated
# with. # with.
desktopName ? "", desktopName ? "",
# Applications to be put in `Added Associations`. This is not set when the # Applications to be put in `Added Associations`. This is not set when the
# database is desktop-specific (when the `desktopName` is non-empty.) # database is desktop-specific (when the `desktopName` is non-empty.)
addedAssociations ? { }, addedAssociations ? { },
# Associations to be put in `Removed Associations` in the file. Similar to # Associations to be put in `Removed Associations` in the file. Similar to
# `addedAssociations`, this will not be added when it is desktop-specific. # `addedAssociations`, this will not be added when it is desktop-specific.
removedAssociations ? { }, removedAssociations ? { },
# Set of applications to be opened associated with the MIME type. # Set of applications to be opened associated with the MIME type.
defaultApplications ? { }, defaultApplications ? { }, }:
}:
writeTextFile { writeTextFile {
name = "xdg-mime-associations${lib.optionalString (desktopName != "") "-${desktopName}"}"; name = "xdg-mime-associations${
lib.optionalString (desktopName != "") "-${desktopName}"
}";
text = text =
# Non-desktop-specific mimeapps.list are only allowed to specify # Non-desktop-specific mimeapps.list are only allowed to specify
# default applications. # default applications.
@ -33,6 +34,8 @@ writeTextFile {
"Added Associations" = addedAssociations; "Added Associations" = addedAssociations;
"Removed Associations" = removedAssociations; "Removed Associations" = removedAssociations;
})); }));
destination = "/share/applications/${lib.optionalString (desktopName != "") "${desktopName}-"}mimeapps.list"; destination = "/share/applications/${
lib.optionalString (desktopName != "") "${desktopName}-"
}mimeapps.list";
} }

View File

@ -6,19 +6,18 @@
create something like an entry for a desktop session. create something like an entry for a desktop session.
*/ */
{ {
# Name of the desktop entry. Only used as part of the package name and the # Name of the desktop entry. Only used as part of the package name and the
# default value of the destination path. # default value of the destination path.
name, name,
# Nix-representable data to be exported as the desktop entry. # Nix-representable data to be exported as the desktop entry.
config, config,
# Add a validation check for the exported desktop entry. # Add a validation check for the exported desktop entry.
validate ? true, validate ? true,
# Destination path relative to the output path. # Destination path relative to the output path.
destination ? "/share/applications/${name}.desktop", destination ? "/share/applications/${name}.desktop", }:
}:
writeTextFile { writeTextFile {
name = "xdg-desktop-entry-${name}"; name = "xdg-desktop-entry-${name}";
@ -26,14 +25,14 @@ writeTextFile {
listsAsDuplicateKeys = false; listsAsDuplicateKeys = false;
mkKeyValue = lib.generators.mkKeyValueDefault { mkKeyValue = lib.generators.mkKeyValueDefault {
mkValueString = v: mkValueString = v:
if lib.isList v then lib.concatStringsSep ";" v if lib.isList v then
else lib.generators.mkValueStringDefault { } v; lib.concatStringsSep ";" v
else
lib.generators.mkValueStringDefault { } v;
} "="; } "=";
} config; } config;
inherit destination; inherit destination;
checkPhase = checkPhase = lib.optionalString validate ''
lib.optionalString validate ${lib.getExe' desktop-file-utils "desktop-file-validate"} "$target"
'' '';
${lib.getExe' desktop-file-utils "desktop-file-validate"} "$target"
'';
} }

View File

@ -1,17 +1,19 @@
{ lib, writeTextFile }: { lib, writeTextFile }:
/* Create an XDG Portals configuration with the given desktop name and its /* Create an XDG Portals configuration with the given desktop name and its
configuration. Similarly, the given desktop name is assumed to be already configuration. Similarly, the given desktop name is assumed to be already
in its suitable form of a lowercase ASCII. in its suitable form of a lowercase ASCII.
*/ */
{ { desktopName ? "common",
desktopName ? "common",
# Nix-representable data to be exported as the portal configuration. # Nix-representable data to be exported as the portal configuration.
config, config, }:
}:
writeTextFile { writeTextFile {
name = "xdg-portal-config${lib.optionalString (desktopName != "common") "-${desktopName}"}"; name = "xdg-portal-config${
lib.optionalString (desktopName != "common") "-${desktopName}"
}";
text = lib.generators.toINI { } config; text = lib.generators.toINI { } config;
destination = "/share/xdg-desktop-portal/${lib.optionalString (desktopName != "common") "${desktopName}-"}portals.conf"; destination = "/share/xdg-desktop-portal/${
lib.optionalString (desktopName != "common") "${desktopName}-"
}portals.conf";
} }

View File

@ -55,8 +55,7 @@
=> /nix/store/HASH-mustache-render-template => /nix/store/HASH-mustache-render-template
*/ */
renderMustacheTemplate = { template, context, extraArgs ? { } }: renderMustacheTemplate = { template, context, extraArgs ? { } }:
let let extraArgs' = lib.cli.toGNUCommandLineShell { } extraArgs;
extraArgs' = lib.cli.toGNUCommandLineShell { } extraArgs;
in pkgs.runCommand "mustache-render-template" { in pkgs.runCommand "mustache-render-template" {
nativeBuildInputs = with pkgs; [ mustache-go ]; nativeBuildInputs = with pkgs; [ mustache-go ];
context = builtins.toJSON context; context = builtins.toJSON context;

View File

@ -14,39 +14,30 @@
let let
# A set of nixos-generators modules including our custom ones. # A set of nixos-generators modules including our custom ones.
nixosGeneratorModules = nixosGeneratorModules = let
let officialFormats = builtins.readDir "${sources.nixos-generators}/formats";
officialFormats = builtins.readDir "${sources.nixos-generators}/formats"; unofficialFormats = builtins.readDir ../modules/nixos-generators;
unofficialFormats = builtins.readDir ../modules/nixos-generators; formats = officialFormats // unofficialFormats;
formats = officialFormats // unofficialFormats; in lib.mapAttrs' (n: _:
in lib.nameValuePair (lib.removeSuffix ".nix" n) {
lib.mapAttrs' (n: _: lib.nameValuePair (lib.removeSuffix ".nix" n) {
imports = [ imports = [
"${sources.nixos-generators}/format-module.nix" "${sources.nixos-generators}/format-module.nix"
( (if (lib.hasAttr n officialFormats) then
if (lib.hasAttr n officialFormats) "${sources.nixos-generators}/formats/${n}"
then "${sources.nixos-generators}/formats/${n}" else
else "${../modules/nixos-generators}/${n}" "${../modules/nixos-generators}/${n}")
)
]; ];
}) formats; }) formats;
in in rec {
rec { mkNixosSystem =
mkNixosSystem = { { pkgs, lib ? pkgs.lib, system, extraModules ? [ ], specialArgs ? { }, }:
pkgs,
lib ? pkgs.lib,
system,
extraModules ? [ ],
specialArgs ? { },
}:
let let
nixosModules = ../modules/nixos; nixosModules = ../modules/nixos;
# Evaluating the system ourselves (which is trivial) instead of relying # Evaluating the system ourselves (which is trivial) instead of relying
# on nixpkgs.lib.nixosSystem flake output. # on nixpkgs.lib.nixosSystem flake output.
nixosSystem = args: import "${pkgs.path}/nixos/lib/eval-config.nix" args; nixosSystem = args: import "${pkgs.path}/nixos/lib/eval-config.nix" args;
in in (lib.makeOverridable nixosSystem) {
(lib.makeOverridable nixosSystem) {
inherit pkgs; inherit pkgs;
specialArgs = specialArgs // { specialArgs = specialArgs // {
foodogsquaredUtils = import ./utils/nixos.nix { inherit lib; }; foodogsquaredUtils = import ./utils/nixos.nix { inherit lib; };
@ -55,9 +46,7 @@ rec {
modules = extraModules ++ [ modules = extraModules ++ [
nixosModules nixosModules
../modules/nixos/_private ../modules/nixos/_private
({ lib, ... }: { ({ lib, ... }: { nixpkgs.hostPlatform = lib.mkForce system; })
nixpkgs.hostPlatform = lib.mkForce system;
})
]; ];
# Since we're setting it through nixpkgs.hostPlatform, we'll have to pass # Since we're setting it through nixpkgs.hostPlatform, we'll have to pass
@ -66,44 +55,27 @@ rec {
}; };
# A very very thin wrapper around `mkNixosSystem` to build with the given format. # A very very thin wrapper around `mkNixosSystem` to build with the given format.
mkNixosImage = { mkNixosImage = { pkgs, system, lib ? pkgs.lib, extraModules ? [ ]
pkgs, , specialArgs ? { }, format ? "iso", }:
system,
lib ? pkgs.lib,
extraModules ? [ ],
specialArgs ? { },
format ? "iso",
}:
let let
extraModules' = extraModules ++ [ nixosGeneratorModules.${format} ]; extraModules' = extraModules ++ [ nixosGeneratorModules.${format} ];
nixosSystem = mkNixosSystem { nixosSystem = mkNixosSystem {
inherit pkgs lib system specialArgs; inherit pkgs lib system specialArgs;
extraModules = extraModules'; extraModules = extraModules';
}; };
in in nixosSystem.config.system.build.${nixosSystem.config.formatAttr};
nixosSystem.config.system.build.${nixosSystem.config.formatAttr};
mkHome = { mkHome =
pkgs, { pkgs, homeManagerSrc, lib ? pkgs.lib, modules ? [ ], specialArgs ? { }, }:
homeManagerSrc, let homeModules = ../modules/home-manager;
lib ? pkgs.lib, in import "${homeManagerSrc}/modules" {
modules ? [ ],
specialArgs ? { },
}:
let
homeModules = ../modules/home-manager;
in
import "${homeManagerSrc}/modules" {
inherit pkgs lib; inherit pkgs lib;
check = true; check = true;
extraSpecialArgs = specialArgs // { extraSpecialArgs = specialArgs // {
foodogsquaredModulesPath = builtins.toString homeModules; foodogsquaredModulesPath = builtins.toString homeModules;
}; };
configuration = { lib, ... }: { configuration = { lib, ... }: {
imports = modules ++ [ imports = modules ++ [ homeModules ../modules/home-manager/_private ];
homeModules
../modules/home-manager/_private
];
config = { config = {
programs.home-manager.path = homeManagerSrc; programs.home-manager.path = homeManagerSrc;
@ -113,25 +85,17 @@ rec {
}; };
}; };
mkWrapper = { mkWrapper = { pkgs, lib ? pkgs.lib, wrapperManagerSrc, modules ? [ ]
pkgs, , specialArgs ? { }, }:
lib ? pkgs.lib,
wrapperManagerSrc,
modules ? [ ],
specialArgs ? { },
}:
let let
wrapperManagerModules = ../modules/wrapper-manager; wrapperManagerModules = ../modules/wrapper-manager;
wrapperManager = import wrapperManagerSrc { }; wrapperManager = import wrapperManagerSrc { };
in in wrapperManager.lib.build {
wrapperManager.lib.build { inherit pkgs lib;
inherit pkgs lib; specialArgs = specialArgs // {
specialArgs = specialArgs // { foodogsquaredModulesPath = builtins.toString wrapperManagerModules;
foodogsquaredModulesPath = builtins.toString wrapperManagerModules;
};
modules = modules ++ [
wrapperManagerModules
../modules/wrapper-manager/_private
];
}; };
modules = modules
++ [ wrapperManagerModules ../modules/wrapper-manager/_private ];
};
} }

View File

@ -2,9 +2,8 @@
{ pkgs, lib, self }: { pkgs, lib, self }:
rec { rec {
/* /* Checks if there is the `osConfig` attribute and get the attribute path from
Checks if there is the `osConfig` attribute and get the attribute path from its system configuration.
its system configuration.
*/ */
hasNixOSConfigAttr = hasNixOSConfigAttr =
# The configuration attribute set of the home-manager configuration. # The configuration attribute set of the home-manager configuration.
@ -26,11 +25,10 @@ rec {
# The default value when `attrPath` is missing. # The default value when `attrPath` is missing.
default: default:
attrs ? darwinConfig && pkgs.lib.attrByPath attrPath default attrs.darwinConfig; attrs ? darwinConfig
&& pkgs.lib.attrByPath attrPath default attrs.darwinConfig;
/* # A quick function to check if the optional NixOS system module is enabled.
A quick function to check if the optional NixOS system module is enabled.
*/
hasOSModuleEnabled = hasOSModuleEnabled =
# The configuration attribute set of the home-manager configuration. # The configuration attribute set of the home-manager configuration.
attrs: attrs:

View File

@ -5,12 +5,10 @@
# Checks if the NixOS configuration is part of the nixos-generator build. # Checks if the NixOS configuration is part of the nixos-generator build.
# Typically, we just check if there's a certain attribute that is imported # Typically, we just check if there's a certain attribute that is imported
# from it. # from it.
hasNixosFormat = config: hasNixosFormat = config: lib.hasAttrByPath [ "formatAttr" ] config;
lib.hasAttrByPath [ "formatAttr" ] config;
# Checks if the NixOS config is being built for a particular format. # Checks if the NixOS config is being built for a particular format.
isFormat = config: format: isFormat = config: format: (config.formatAttr or "") == format;
(config.formatAttr or "") == format;
# Create a separate environment similar to NixOS `system.path`. This is # Create a separate environment similar to NixOS `system.path`. This is
# typically used to create isolated environments for custom desktop sessions # typically used to create isolated environments for custom desktop sessions
@ -21,17 +19,16 @@
pkgs.buildEnv (args // { pkgs.buildEnv (args // {
inherit (config.environment) pathsToLink extraOutputsToInstall; inherit (config.environment) pathsToLink extraOutputsToInstall;
ignoreCollisions = true; ignoreCollisions = true;
postBuild = postBuild = ''
'' # Remove wrapped binaries, they shouldn't be accessible via PATH.
# Remove wrapped binaries, they shouldn't be accessible via PATH. find $out/bin -maxdepth 1 -name ".*-wrapped" -type l -delete
find $out/bin -maxdepth 1 -name ".*-wrapped" -type l -delete
if [ -x $out/bin/glib-compile-schemas -a -w $out/share/glib-2.0/schemas ]; then if [ -x $out/bin/glib-compile-schemas -a -w $out/share/glib-2.0/schemas ]; then
$out/bin/glib-compile-schemas $out/share/glib-2.0/schemas $out/bin/glib-compile-schemas $out/share/glib-2.0/schemas
fi fi
${config.environment.extraSetup} ${config.environment.extraSetup}
''; '';
}); });
# Given an environment (built with `pkgs.buildEnv`), create a systemd # Given an environment (built with `pkgs.buildEnv`), create a systemd
@ -44,26 +41,24 @@
# Create a range object (as [start, end) in notation) that is typically used # Create a range object (as [start, end) in notation) that is typically used
# in module options that accept them. # in module options that accept them.
makeRange = start: range: makeRange = start: range: {
{ from = start; to = start + range; }; from = start;
to = start + range;
};
# Create a range object (as [start + 1, end + 1] in notation) that is typically used # Create a range object (as [start + 1, end + 1] in notation) that is typically used
# in module options that accept them except that the starting port is included. # in module options that accept them except that the starting port is included.
makeRange' = start: range: makeRange' = start: range:
let let start' = start + 1;
start' = start + 1; in {
in from = start';
{ from = start'; to = start' + range; }; to = start' + range;
};
/* # A specific function that checks if specific filesystem setups are set.
A specific function that checks if specific filesystem setups are set.
*/
isFilesystemSet = config: setupName: isFilesystemSet = config: setupName:
config.suites.filesystem.setups.${setupName}.enable or false; config.suites.filesystem.setups.${setupName}.enable or false;
/* # Get the path from the state variable.
Get the path from the state variable. getFilesystem = config: setupName: config.state.paths.${setupName};
*/
getFilesystem = config: setupName:
config.state.paths.${setupName};
} }

View File

@ -2,5 +2,5 @@
{ {
isStandalone = config: isStandalone = config:
!config?hmConfig && !config?nixosConfig && !config?darwinConfig; !config ? hmConfig && !config ? nixosConfig && !config ? darwinConfig;
} }

View File

@ -18,13 +18,8 @@
} }
*/ */
getSecrets = sopsFile: secrets: getSecrets = sopsFile: secrets:
let let getKey = key: { inherit key sopsFile; };
getKey = key: { inherit key sopsFile; }; in lib.mapAttrs (path: attrs: (getKey path) // attrs) secrets;
in
lib.mapAttrs
(path: attrs:
(getKey path) // attrs)
secrets;
/* Prepend a prefix for the given secrets. This allows a workflow for /* Prepend a prefix for the given secrets. This allows a workflow for
separate sops file. separate sops file.
@ -44,10 +39,7 @@
})) }))
*/ */
attachSopsPathPrefix = prefix: secrets: attachSopsPathPrefix = prefix: secrets:
lib.mapAttrs' lib.mapAttrs' (key: settings:
(key: settings: lib.nameValuePair "${prefix}/${key}" ({ inherit key; } // settings))
lib.nameValuePair secrets;
"${prefix}/${key}"
({ inherit key; } // settings))
secrets;
} }

View File

@ -5,15 +5,12 @@ rec {
containing all of the addons properly placed as a system resource folder. containing all of the addons properly placed as a system resource folder.
*/ */
wrapBlenderAddons = { blenderPackage, addons }: wrapBlenderAddons = { blenderPackage, addons }:
let let blenderVersion = lib.versions.majorMinor blenderPackage.version;
blenderVersion = lib.versions.majorMinor blenderPackage.version; in pkgs.runCommand "blender-system-resources" {
in passAsFile = [ "paths" ];
pkgs.runCommand "blender-system-resources" paths = addons ++ [ blenderPackage ];
{ nativeBuildInputs = with pkgs; [ outils ];
passAsFile = [ "paths" ]; } ''
paths = addons ++ [ blenderPackage ];
nativeBuildInputs = with pkgs; [ outils ];
} ''
mkdir -p $out mkdir -p $out
for i in $(cat $pathsPath); do for i in $(cat $pathsPath); do
resourcesPath="$i/share/blender" resourcesPath="$i/share/blender"
@ -24,11 +21,10 @@ rec {
done done
''; '';
makeBlenderWrapper = module@{ blenderPackage, blenderArgs ? [ ] , addons ? [ ], ... }: makeBlenderWrapper =
let module@{ blenderPackage, blenderArgs ? [ ], addons ? [ ], ... }:
blenderAddons = wrapBlenderAddons { inherit blenderPackage addons; }; let blenderAddons = wrapBlenderAddons { inherit blenderPackage addons; };
in in lib.mkMerge [
lib.mkMerge [
{ {
arg0 = lib.getExe' blenderPackage "blender"; arg0 = lib.getExe' blenderPackage "blender";
prependArgs = lib.mkBefore blenderArgs; prependArgs = lib.mkBefore blenderArgs;
@ -41,48 +37,49 @@ rec {
(lib.removeAttrs module [ "blenderPackage" "blenderArgs" "addons" ]) (lib.removeAttrs module [ "blenderPackage" "blenderArgs" "addons" ])
]; ];
/* Create a configuration module for quickly wrapping with Boxxy. # Create a configuration module for quickly wrapping with Boxxy.
*/ makeBoxxyWrapper =
makeBoxxyWrapper = module@{ boxxyArgs, wraparound, wraparoundArgs ? [], ... }: module@{ boxxyArgs, wraparound, wraparoundArgs ? [ ], ... }:
lib.mkMerge [ lib.mkMerge [
{ {
arg0 = lib.getExe' pkgs.boxxy "boxxy"; arg0 = lib.getExe' pkgs.boxxy "boxxy";
prependArgs = lib.mkBefore (boxxyArgs ++ [ "--" wraparound ] ++ wraparoundArgs); prependArgs =
lib.mkBefore (boxxyArgs ++ [ "--" wraparound ] ++ wraparoundArgs);
} }
(builtins.removeAttrs module [ "boxxyArgs" "wraparound" "wraparoundArgs" ]) (builtins.removeAttrs module [
"boxxyArgs"
"wraparound"
"wraparoundArgs"
])
]; ];
/* Given the path to the source code, the attribute path, and the executable /* Given the path to the source code, the attribute path, and the executable
name, return the store path to one of its executables. name, return the store path to one of its executables.
*/ */
getNixglExecutable = { src, variant ? [ "auto" "nixGLDefault" ], nixglProgram ? "nixGL" }: getNixglExecutable =
{ src, variant ? [ "auto" "nixGLDefault" ], nixglProgram ? "nixGL" }:
let let
nixgl = import src { inherit pkgs; }; nixgl = import src { inherit pkgs; };
nixglPkg = lib.getAttrFromPath variant nixgl; nixglPkg = lib.getAttrFromPath variant nixgl;
in in lib.getExe' nixglPkg nixglProgram;
lib.getExe' nixglPkg nixglProgram;
/* Create a configuration module for quickly wrapping with NixGL. # Create a configuration module for quickly wrapping with NixGL.
*/ makeNixglWrapper = { nixglSrc, nixglArgs, nixglVariant, nixglExecutable
makeNixglWrapper = { , wraparound, wraparoundArgs ? [ ], ... }@module:
nixglSrc,
nixglArgs,
nixglVariant,
nixglExecutable,
wraparound,
wraparoundArgs ? [],
...
}@module:
lib.mkMerge [ lib.mkMerge [
{ {
arg0 = getNixglExecutable nixglSrc nixglVariant nixglExecutable; arg0 = getNixglExecutable nixglSrc nixglVariant nixglExecutable;
prependArgs = lib.mkBefore (nixglArgs ++ [ "--" wraparound ] ++ wraparoundArgs); prependArgs =
lib.mkBefore (nixglArgs ++ [ "--" wraparound ] ++ wraparoundArgs);
} }
(builtins.removeAttrs module [ (builtins.removeAttrs module [
"nixglArgs" "nixglVariant" "nixglExecutable" "nixglArgs"
"wraparound" "wraparoundArgs" "nixglVariant"
"nixglExecutable"
"wraparound"
"wraparoundArgs"
]) ])
]; ];
} }

View File

@ -1,27 +1,20 @@
{ stdenvNoCC, lib, fetchzip, fetchurl, curl }: { stdenvNoCC, lib, fetchzip, fetchurl, curl }:
{ { id, file ? "", formats ? [ ], hash ? "", name ? "internet-archive-${id}",
id,
file ? "",
formats ? [ ],
hash ? "",
name ? "internet-archive-${id}",
}@args: }@args:
let let
isFormatIndiciated = formats != [ ]; isFormatIndiciated = formats != [ ];
url = url = if isFormatIndiciated then
if isFormatIndiciated "https://archive.org/compress/${lib.escapeURL id}/formats=${
then "https://archive.org/compress/${lib.escapeURL id}/formats=${lib.concatStringsSep "," formats}" lib.concatStringsSep "," formats
else "https://archive.org/download/${lib.escapeURL id}/${lib.escapeURL file}"; }"
else
"https://archive.org/download/${lib.escapeURL id}/${lib.escapeURL file}";
args' = lib.removeAttrs args [ "id" "file" "formats" ] // { args' = lib.removeAttrs args [ "id" "file" "formats" ] // {
inherit url hash name; inherit url hash name;
}; };
fetcher = fetcher = if isFormatIndiciated then fetchzip else fetchurl;
if isFormatIndiciated in fetcher args'
then fetchzip
else fetchurl;
in
fetcher args'

View File

@ -1,15 +1,8 @@
{ fetchzip, lib }: { fetchzip, lib }:
{ { fileId, pid, ext ? "gz", ... }@args:
fileId,
pid,
ext ? "gz",
...
}@args:
let let args' = lib.removeAttrs args [ "fileId" "pid" "ext" ];
args' = lib.removeAttrs args [ "fileId" "pid" "ext" ]; in fetchzip (args' // {
in
fetchzip (args' // {
url = "https://www.ugee.com/download/file/id/${fileId}/pid/${pid}/ext/${ext}"; url = "https://www.ugee.com/download/file/id/${fileId}/pid/${pid}/ext/${ext}";
}) })

View File

@ -1,7 +1,7 @@
# No, this is not a flake of the library set, it is a library subset for # No, this is not a flake of the library set, it is a library subset for
# flake-related shtick. This should be used VERY RARELY in most parts of the # flake-related shtick. This should be used VERY RARELY in most parts of the
# configuration because they are set up to be usable both in flakes- and # configuration because they are set up to be usable both in flakes and
# non-flakes-enabled environment. # flake-less environment.
# #
# Take note it has a very strict design constraint of not relying on the # Take note it has a very strict design constraint of not relying on the
# `inputs` attribute of the flake output. Instead, we're relying on the # `inputs` attribute of the flake output. Instead, we're relying on the
@ -22,6 +22,5 @@ rec {
fetchTree = metadata: inputName: fetchTree = metadata: inputName:
builtins.fetchTree metadata.nodes.${inputName}.locked; builtins.fetchTree metadata.nodes.${inputName}.locked;
fetchInput = metadata: inputName: fetchInput = metadata: inputName: (fetchTree metadata inputName).outPath;
(fetchTree metadata inputName).outPath;
} }

View File

@ -11,8 +11,7 @@ rec {
abs (1 / 5) abs (1 / 5)
=> 0.2 => 0.2
*/ */
abs = number: abs = number: if number < 0 then -(number) else number;
if number < 0 then -(number) else number;
/* Exponentiates the given base with the exponent. /* Exponentiates the given base with the exponent.
Example: Example:
@ -28,10 +27,10 @@ rec {
let let
absValue = abs exponent; absValue = abs exponent;
iter = product: counter: maxCount: iter = product: counter: maxCount:
if counter > maxCount if counter > maxCount then
then product product
else iter (product * base) (counter + 1) maxCount; else
iter (product * base) (counter + 1) maxCount;
value = iter 1 1 absValue; value = iter 1 1 absValue;
in in if exponent < 0 then (1 / value) else value;
if exponent < 0 then (1 / value) else value;
} }

View File

@ -23,7 +23,7 @@ rec {
*/ */
countAttrs = pred: attrs: countAttrs = pred: attrs:
lib.count (attr: pred attr.name attr.value) lib.count (attr: pred attr.name attr.value)
(lib.mapAttrsToList lib.nameValuePair attrs); (lib.mapAttrsToList lib.nameValuePair attrs);
/* Filters and groups the attribute set into two separate attribute where it /* Filters and groups the attribute set into two separate attribute where it
either accepted or denied from a given predicate function. either accepted or denied from a given predicate function.
@ -33,14 +33,15 @@ rec {
=> { ok = { a = 4; }; notOk = { b = 2; c = 6; }; } => { ok = { a = 4; }; notOk = { b = 2; c = 6; }; }
*/ */
filterAttrs' = f: attrs: filterAttrs' = f: attrs:
lib.foldlAttrs (acc: name: value: let lib.foldlAttrs (acc: name: value:
isOk = f name value; let isOk = f name value;
in { in {
ok = acc.ok // lib.optionalAttrs isOk { ${name} = value; }; ok = acc.ok // lib.optionalAttrs isOk { ${name} = value; };
notOk = acc.notOk // lib.optionalAttrs (!isOk) { ${name} = value; }; notOk = acc.notOk // lib.optionalAttrs (!isOk) { ${name} = value; };
}) }) {
{ ok = { }; notOk = { }; } ok = { };
attrs; notOk = { };
} attrs;
/* Convenient function for converting bits to bytes. /* Convenient function for converting bits to bytes.
@ -87,8 +88,7 @@ rec {
r = -27; r = -27;
q = -30; q = -30;
}; };
in in prefixes.${c};
prefixes.${c};
/* Gives the multiplier for the metric units. /* Gives the multiplier for the metric units.
@ -99,8 +99,7 @@ rec {
metricPrefixMultiplier "G" metricPrefixMultiplier "G"
=> 1000000000 => 1000000000
*/ */
metricPrefixMultiplier = c: metricPrefixMultiplier = c: self.math.pow 10 (SIPrefixExponent c);
self.math.pow 10 (SIPrefixExponent c);
/* Gives the exponent with the associated binary prefix. /* Gives the exponent with the associated binary prefix.
@ -126,8 +125,7 @@ rec {
M = 20; M = 20;
K = 10; K = 10;
}; };
in in prefixes.${c};
prefixes.${c};
/* Gives the multiplier for the given byte unit. Essentially returns the /* Gives the multiplier for the given byte unit. Essentially returns the
value in number of bytes. value in number of bytes.
@ -139,8 +137,7 @@ rec {
binaryPrefixMultiplier "G" binaryPrefixMultiplier "G"
=> 1.099511628×10¹² => 1.099511628×10¹²
*/ */
binaryPrefixMultiplier = c: binaryPrefixMultiplier = c: self.math.pow 2 (binaryPrefixExponent c);
self.math.pow 2 (binaryPrefixExponent c);
/* Parse the given string containing the size into its appropriate value. /* Parse the given string containing the size into its appropriate value.
Returns the value in number of bytes. Returns the value in number of bytes.
@ -157,37 +154,37 @@ rec {
*/ */
parseBytesSizeIntoInt = str: parseBytesSizeIntoInt = str:
let let
matches = builtins.match "([[:digit:]]+)[[:space:]]*([[:alpha:]]{1})(i?[B|b])" str; matches =
builtins.match "([[:digit:]]+)[[:space:]]*([[:alpha:]]{1})(i?[B|b])"
str;
numeral = lib.toInt (lib.lists.head matches); numeral = lib.toInt (lib.lists.head matches);
prefix = lib.lists.elemAt matches 1; prefix = lib.lists.elemAt matches 1;
suffix = lib.lists.last matches; suffix = lib.lists.last matches;
isBinary = lib.hasPrefix "i" suffix; isBinary = lib.hasPrefix "i" suffix;
multiplier = multiplier = let
let multiplierFn =
multiplierFn = if isBinary then binaryPrefixMultiplier else metricPrefixMultiplier; if isBinary then binaryPrefixMultiplier else metricPrefixMultiplier;
in in multiplierFn prefix;
multiplierFn prefix;
bitDivider = if lib.hasSuffix "b" suffix then 8 else 1; bitDivider = if lib.hasSuffix "b" suffix then 8 else 1;
in in numeral * multiplier / bitDivider;
numeral * multiplier / bitDivider;
/* /* Given an attrset of unit size object, return the size in bytes.
Given an attrset of unit size object, return the size in bytes.
Example: Example:
unitsToInt { size = 4; prefix = "G"; type = "binary"; } unitsToInt { size = 4; prefix = "G"; type = "binary"; }
=> 4294967296 => 4294967296
unitsToInt { size = 4; prefix = "G"; type = "metric"; } unitsToInt { size = 4; prefix = "G"; type = "metric"; }
=> 4000000000 => 4000000000
*/ */
unitsToInt = { size, prefix, type ? "binary" }: unitsToInt = { size, prefix, type ? "binary" }:
let let
multiplierFn = multiplierFn = if type == "binary" then
if type == "binary" then binaryPrefixMultiplier binaryPrefixMultiplier
else if type == "metric" then metricPrefixMultiplier else if type == "metric" then
else builtins.throw "no multiplier type ${type}"; metricPrefixMultiplier
in else
size * (multiplierFn prefix); builtins.throw "no multiplier type ${type}";
in size * (multiplierFn prefix);
} }

View File

@ -3,10 +3,8 @@
{ {
# This is only used for home-manager users without a NixOS user counterpart. # This is only used for home-manager users without a NixOS user counterpart.
mapHomeManagerUser = user: settings: mapHomeManagerUser = user: settings:
let let homeDirectory = "/home/${user}";
homeDirectory = "/home/${user}"; in ({ lib, ... }: {
in
({ lib, ... }: {
home-manager.users."${user}" = { ... }: { home-manager.users."${user}" = { ... }: {
imports = [ imports = [
{ {