all repos — nixfiles @ aedea00a8b6ccbbeea0ea0215af0652ff7ccbd28

System and user configuration, managed by nix and home-manager

user/modules/caddy.nix (view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.services.caddy;
in
{
  options.services.caddy = {
    enable = lib.mkEnableOption "Caddy web server (for local development)";

    package = lib.mkPackageOption pkgs "caddy" { };

    configFile = lib.mkOption {
      type = lib.types.path;
      description = ''
        Path to a Caddyfile configuration file.
      '';
    };

    adapter = lib.mkOption {
      type = with lib.types; nullOr str;
      default = "caddyfile";

      description = ''
        Name of the config adapter to use.
        See <https://caddyserver.com/docs/config-adapters>
        for the full list.

        If `null` is specified, the `--adapter` argument is omitted when
        starting or restarting Caddy. Notably, this allows specification of a
        configuration file in Caddy's native JSON format, as long as the
        filename does not start with `Caddyfile` (in which case the `caddyfile`
        adapter is implicitly enabled). See
        <https://caddyserver.com/docs/command-line#caddy-run> for details.
      '';
    };

    watch = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Automatically reload the config file, when changed.
      '';
    };
  };

  config =
    let
      args = [
        "run"
        "--config"
        "${cfg.configFile}"
      ]
      ++ lib.optionals (cfg.adapter != null) [
        "--adapter"
        cfg.adapter
      ]
      ++ lib.optional cfg.watch "--watch";
    in
    lib.mkIf cfg.enable {
      home.packages = [ cfg.package ];

      launchd.agents.caddy = {
        enable = true;

        config = {
          ProgramArguments = [ (lib.getExe cfg.package) ] ++ args;
          RunAtLoad = true;
        };
      };

      # untested
      systemd.user.services.caddy = {
        unitConfig = {
          wantedBy = [ "default.target" ];
        };
        serviceConfig = {
          ExecStart = "${lib.getExe cfg.package} ${lib.escapeShellArgs args}";
        };
      };

    };
}