nix flake refactor: avoid `with lib; & use lib.optional*`

Upstream Nixpkgs has been pushing the style of removing ``with lib;``
with the reasoning of clarity around where variables in scope come that
hurt readability & static analysis[*].

While on the topic of ``lib``, introduce ``lib.optional`` &
``lib.optionalString`` in a few more places to tidy up the code while
using common library patterns.

.. [*] https://nix.dev/guides/best-practices#with-scopes

Format: text/x-rst
This commit is contained in:
โทสฺตัล
2025-01-24 00:10:53 +07:00
parent 8ca227e21a
commit 0a64bfb3c7

View File

@@ -10,32 +10,34 @@
in in
{ {
nixosModule = { config, ... }: nixosModule = { config, ... }:
with nixpkgs.lib;
let let
inherit (nixpkgs) lib;
cfg = config.networking.stevenBlackHosts; cfg = config.networking.stevenBlackHosts;
alternatesList = (if cfg.blockFakenews then [ "fakenews" ] else []) ++ alternatesList =
(if cfg.blockGambling then [ "gambling" ] else []) ++ (lib.optional cfg.blockFakenews "fakenews")
(if cfg.blockPorn then [ "porn" ] else []) ++ ++ (lib.optional cfg.blockGambling "gambling")
(if cfg.blockSocial then [ "social" ] else []); ++ (lib.optional cfg.blockPorn "porn")
++ (lib.optional cfg.blockSocial "social");
alternatesPath = "alternates/" + builtins.concatStringsSep "-" alternatesList + "/"; alternatesPath = "alternates/" + builtins.concatStringsSep "-" alternatesList + "/";
in in
{ {
options.networking.stevenBlackHosts = { options.networking.stevenBlackHosts = {
enable = mkEnableOption "Steven Black's hosts file"; enable = lib.mkEnableOption "Steven Black's hosts file";
enableIPv6 = mkEnableOption "IPv6 rules" // { enableIPv6 = lib.mkEnableOption "IPv6 rules" // {
default = config.networking.enableIPv6; default = config.networking.enableIPv6;
}; };
blockFakenews = mkEnableOption "fakenews hosts entries"; blockFakenews = lib.mkEnableOption "fakenews hosts entries";
blockGambling = mkEnableOption "gambling hosts entries"; blockGambling = lib.mkEnableOption "gambling hosts entries";
blockPorn = mkEnableOption "porn hosts entries"; blockPorn = lib.mkEnableOption "porn hosts entries";
blockSocial = mkEnableOption "social hosts entries"; blockSocial = lib.mkEnableOption "social hosts entries";
}; };
config = mkIf cfg.enable { config = lib.mkIf cfg.enable {
networking.extraHosts = networking.extraHosts =
let let
orig = builtins.readFile ("${self}/" + (if alternatesList != [] then alternatesPath else "") + "hosts"); orig = builtins.readFile ("${self}/" + (lib.optionalString (alternatesList != []) alternatesPath) + "hosts");
ipv6 = builtins.replaceStrings [ "0.0.0.0" ] [ "::" ] orig; ipv6 = builtins.replaceStrings [ "0.0.0.0" ] [ "::" ] orig;
in orig + (optionalString cfg.enableIPv6 ("\n" + ipv6)); in
orig + (lib.optionalString cfg.enableIPv6 ("\n" + ipv6));
}; };
}; };