]> git.immae.eu Git - perso/Immae/Config/Nix.git/blob - flakes/files-watcher/flake.nix
Squash changes containing private information
[perso/Immae/Config/Nix.git] / flakes / files-watcher / flake.nix
1 {
2 description = "Module to watch fo file changes to force restart systemd service";
3 outputs = { self }: {
4 nixosModule = { config, lib, pkgs, ... }: let cfg = config.services.filesWatcher; in with lib; {
5 # Necessary for situations where flake gets included multiple times
6 key = builtins.hashString "sha256" (builtins.path { path = self.sourceInfo.outPath; name = "source"; });
7 options = {
8 services.filesWatcher = with lib.types; mkOption {
9 default = {};
10 description = ''
11 Files to watch and trigger service reload or restart of service
12 when changed.
13 '';
14 type = attrsOf (submodule {
15 options = {
16 restart = mkEnableOption "Restart service rather than reloading it";
17 paths = mkOption {
18 type = listOf str;
19 description = ''
20 Paths to watch that should trigger a reload of the
21 service
22 '';
23 };
24 waitTime = mkOption {
25 type = int;
26 default = 5;
27 description = ''
28 Time to wait before reloading/restarting the service.
29 Set 0 to not wait.
30 '';
31 };
32 };
33 });
34 };
35 };
36
37 config = {
38 systemd.services = attrsets.mapAttrs' (name: icfg: attrsets.nameValuePair "${name}Watcher" {
39 description = "${name} reloader";
40 after = [ "network.target" ];
41 script = let
42 action = if icfg.restart then "restart" else "reload";
43 in ''
44 # Service may be stopped during file modification (e.g. activationScripts)
45 if ${pkgs.systemd}/bin/systemctl --quiet is-active ${name}.service; then
46 ${pkgs.coreutils}/bin/sleep ${toString icfg.waitTime}
47 ${pkgs.systemd}/bin/systemctl ${action} ${name}.service
48 fi
49 '';
50 serviceConfig.Type = "oneshot";
51 }) cfg;
52
53 systemd.paths = attrsets.mapAttrs' (name: icfg: attrsets.nameValuePair "${name}Watcher" {
54 wantedBy = [ "multi-user.target" ];
55 pathConfig.PathChanged = icfg.paths;
56 }) cfg;
57 };
58 };
59 };
60 }