fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Naïm FavierRevert "mbsync: make passwordCommand escaping consistent" (#3657)1232d0e1

master
10.6 KiB297 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.programs.mbsync;
8
9  # Accounts for which mbsync is enabled.
10  mbsyncAccounts =
11    filter (a: a.mbsync.enable) (attrValues config.accounts.email.accounts);
12
13  # Given a SINGLE group's channels attribute set, return true if ANY of the channel's
14  # patterns use the invalidOption attribute set value name.
15  channelInvalidOption = channels: invalidOption:
16    any (c: c) (mapAttrsToList (c: hasAttr invalidOption) channels);
17
18  # Given a SINGLE account's groups attribute set, return true if ANY of the account's group's channel's patterns use the invalidOption attribute set value name.
19  groupInvalidOption = groups: invalidOption:
20    any (g: g) (mapAttrsToList (groupName: groupVals:
21      channelInvalidOption groupVals.channels invalidOption) groups);
22
23  # Given all accounts (ensure that accounts passed in here ARE mbsync-using accounts)
24  # return true if ANY of the account's groups' channels' patterns use the
25  # invalidOption attribute set value name.
26  accountInvalidOption = accounts: invalidOption:
27    any (a: a)
28    (map (account: groupInvalidOption account.mbsync.groups invalidOption)
29      mbsyncAccounts);
30
31  genTlsConfig = tls:
32    {
33      SSLType = if !tls.enable then
34        "None"
35      else if tls.useStartTls then
36        "STARTTLS"
37      else
38        "IMAPS";
39    } // optionalAttrs (tls.enable && tls.certificatesFile != null) {
40      CertificateFile = toString tls.certificatesFile;
41    };
42
43  imports = [
44    (mkRenamedOptionModule [ "programs" "mbsync" "masterSlaveMapping" ] [
45      "programs"
46      "mbsync"
47      "nearFarMapping"
48    ])
49  ];
50
51  nearFarMapping = {
52    none = "None";
53    imap = "Far";
54    maildir = "Near";
55    both = "Both";
56  };
57
58  genSection = header: entries:
59    let
60      escapeValue = escape [ ''"'' ];
61      hasSpace = v: builtins.match ".* .*" v != null;
62      genValue = n: v:
63        if isList v then
64          concatMapStringsSep " " (genValue n) v
65        else if isBool v then
66          lib.hm.booleans.yesNo v
67        else if isInt v then
68          toString v
69        else if isString v && hasSpace v then
70          ''"${escapeValue v}"''
71        else if isString v then
72          v
73        else
74          let prettyV = lib.generators.toPretty { } v;
75          in throw "mbsync: unexpected value for option ${n}: '${prettyV}'";
76    in ''
77      ${header}
78      ${concatStringsSep "\n"
79      (mapAttrsToList (n: v: "${n} ${genValue n v}") entries)}
80    '';
81
82  genAccountConfig = account:
83    with account;
84    genSection "IMAPAccount ${name}" ({
85      Host = imap.host;
86      User = userName;
87      PassCmd = toString passwordCommand;
88    } // genTlsConfig imap.tls
89      // optionalAttrs (imap.port != null) { Port = toString imap.port; }
90      // mbsync.extraConfig.account) + "\n"
91    + genSection "IMAPStore ${name}-remote"
92    ({ Account = name; } // mbsync.extraConfig.remote) + "\n"
93    + genSection "MaildirStore ${name}-local" ({
94      Inbox = "${maildir.absPath}/${folders.inbox}";
95    } // optionalAttrs
96      (mbsync.subFolders != "Maildir++" || mbsync.flatten != null) {
97        Path = "${maildir.absPath}/";
98      } // optionalAttrs (mbsync.flatten == null) {
99        SubFolders = mbsync.subFolders;
100      } // optionalAttrs (mbsync.flatten != null) { Flatten = mbsync.flatten; }
101      // mbsync.extraConfig.local) + "\n" + genChannels account;
102
103  genChannels = account:
104    with account;
105    if mbsync.groups == { } then
106      genAccountWideChannel account
107    else
108      genGroupChannelConfig name mbsync.groups + "\n"
109      + genAccountGroups mbsync.groups;
110
111  # Used when no channels are specified for this account. This will create a
112  # single channel for the entire account that is then further refined within
113  # the Group for synchronization.
114  genAccountWideChannel = account:
115    with account;
116    genSection "Channel ${name}" ({
117      Far = ":${name}-remote:";
118      Near = ":${name}-local:";
119      Patterns = mbsync.patterns;
120      Create = nearFarMapping.${mbsync.create};
121      Remove = nearFarMapping.${mbsync.remove};
122      Expunge = nearFarMapping.${mbsync.expunge};
123      SyncState = "*";
124    } // mbsync.extraConfig.channel) + "\n";
125
126  # Given the attr set of groups, return a string of channels that will direct
127  # mail to the proper directories, according to the pattern used in channel's
128  # "far" pattern definition.
129  genGroupChannelConfig = storeName: groups:
130    let
131      # Given the name of the group this channel is part of and the channel
132      # itself, generate the string for the desired configuration.
133      genChannelString = groupName: channel:
134        let
135          escapeValue = escape [ ''\"'' ];
136          hasSpace = v: builtins.match ".* .*" v != null;
137          # Given a list of patterns, will return the string requested.
138          # Only prints if the pattern is NOT the empty list, the default.
139          genChannelPatterns = patterns:
140            if (length patterns) != 0 then
141              "Pattern " + concatStringsSep " "
142              (map (pat: if hasSpace pat then escapeValue pat else pat)
143                patterns) + "\n"
144            else
145              "";
146        in genSection "Channel ${groupName}-${channel.name}" ({
147          Far = ":${storeName}-remote:${channel.farPattern}";
148          Near = ":${storeName}-local:${channel.nearPattern}";
149        } // channel.extraConfig) + genChannelPatterns channel.patterns;
150      # Given the group name, and a attr set of channels within that group,
151      # Generate a list of strings for each channels' configuration.
152      genChannelStrings = groupName: channels:
153        optionals (channels != { })
154        (mapAttrsToList (channelName: info: genChannelString groupName info)
155          channels);
156      # Given a group, return a string that configures all the channels within
157      # the group.
158      genGroupsChannels = group:
159        concatStringsSep "\n" (genChannelStrings group.name group.channels);
160      # Generate all channel configurations for all groups for this account.
161    in concatStringsSep "\n"
162    (remove "" (mapAttrsToList (name: group: genGroupsChannels group) groups));
163
164  # Given the attr set of groups, return a string which maps channels to groups
165  genAccountGroups = groups:
166    let
167      # Given the name of the group and the attribute set of channels, make
168      # make "Channel <grpName>-<chnName>" for each channel to list os strings
169      genChannelStrings = groupName: channels:
170        mapAttrsToList (name: info: "Channel ${groupName}-${name}") channels;
171      # Take in 1 group, if the group has channels specified, construct the
172      # "Group <grpName>" header and each of the channels.
173      genGroupChannelString = group:
174        flatten (optionals (group.channels != { }) ([ "Group ${group.name}" ]
175          ++ (genChannelStrings group.name group.channels)));
176      # Given set of groups, generates list of strings, where each string is one
177      # of the groups and its constituent channels.
178      genGroupsStrings = mapAttrsToList (name: info:
179        concatStringsSep "\n" (genGroupChannelString groups.${name})) groups;
180      # Join all non-empty groups.
181      combined = concatStringsSep "\n\n" (remove "" genGroupsStrings) + "\n";
182    in combined;
183
184  genGroupConfig = name: channels:
185    let
186      genGroupChannel = n: boxes: "Channel ${n}:${concatStringsSep "," boxes}";
187    in "\n" + concatStringsSep "\n"
188    ([ "Group ${name}" ] ++ mapAttrsToList genGroupChannel channels);
189
190in {
191  meta.maintainers = [ maintainers.KarlJoad ];
192
193  options = {
194    programs.mbsync = {
195      enable = mkEnableOption "mbsync IMAP4 and Maildir mailbox synchronizer";
196
197      package = mkOption {
198        type = types.package;
199        default = pkgs.isync;
200        defaultText = literalExpression "pkgs.isync";
201        example = literalExpression "pkgs.isync";
202        description = "The package to use for the mbsync binary.";
203      };
204
205      groups = mkOption {
206        type = types.attrsOf (types.attrsOf (types.listOf types.str));
207        default = { };
208        example = literalExpression ''
209          {
210            inboxes = {
211              account1 = [ "Inbox" ];
212              account2 = [ "Inbox" ];
213            };
214          }
215        '';
216        description = ''
217          Definition of groups.
218        '';
219      };
220
221      extraConfig = mkOption {
222        type = types.lines;
223        default = "";
224        description = ''
225          Extra configuration lines to add to the mbsync configuration.
226        '';
227      };
228    };
229
230    accounts.email.accounts = mkOption {
231      type = with types; attrsOf (submodule (import ./mbsync-accounts.nix));
232    };
233  };
234
235  config = mkIf cfg.enable (mkMerge [
236    {
237      assertions = let
238        checkAccounts = pred: msg:
239          let badAccounts = filter pred mbsyncAccounts;
240          in {
241            assertion = badAccounts == [ ];
242            message = "mbsync: ${msg} for accounts: "
243              + concatMapStringsSep ", " (a: a.name) badAccounts;
244          };
245      in [
246        (checkAccounts (a: a.maildir == null) "Missing maildir configuration")
247        (checkAccounts (a: a.imap == null) "Missing IMAP configuration")
248        (checkAccounts (a: a.passwordCommand == null) "Missing passwordCommand")
249        (checkAccounts (a: a.userName == null) "Missing username")
250      ];
251    }
252
253    (mkIf (accountInvalidOption mbsyncAccounts "masterPattern") {
254      warnings = [
255        "mbsync channels no longer use masterPattern. Use farPattern in its place."
256      ];
257    })
258
259    (mkIf (accountInvalidOption mbsyncAccounts "slavePattern") {
260      warnings = [
261        "mbsync channels no longer use slavePattern. Use nearPattern in its place."
262      ];
263    })
264
265    {
266      home.packages = [ cfg.package ];
267
268      programs.notmuch.new.ignore = [ ".uidvalidity" ".mbsyncstate" ];
269
270      home.file.".mbsyncrc".text = let
271        accountsConfig = map genAccountConfig mbsyncAccounts;
272        # Only generate this kind of Group configuration if there are ANY accounts
273        # that do NOT have a per-account groups/channels option(s) specified.
274        groupsConfig =
275          if any (account: account.mbsync.groups == { }) mbsyncAccounts then
276            mapAttrsToList genGroupConfig cfg.groups
277          else
278            [ ];
279      in ''
280        # Generated by Home Manager.
281
282      ''
283      + concatStringsSep "\n" (optional (cfg.extraConfig != "") cfg.extraConfig)
284      + concatStringsSep "\n\n" accountsConfig
285      + concatStringsSep "\n" groupsConfig;
286
287      home.activation = mkIf (mbsyncAccounts != [ ]) {
288        createMaildir =
289          hm.dag.entryBetween [ "linkGeneration" ] [ "writeBoundary" ] ''
290            $DRY_RUN_CMD mkdir -m700 -p $VERBOSE_ARG ${
291              concatMapStringsSep " " (a: a.maildir.absPath) mbsyncAccounts
292            }
293          '';
294      };
295    }
296  ]);
297}