xdg-mime-apps: add function mimeAssociations

This convenience function allows automatic assignment of a package's
associations to `xdg.mimeApps.defaultApplications`.

For example,

    xdg.mimeApps.defaultApplications =
      config.lib.xdg.mimeAssociations [ pkgs.gnome.evince ];

Co-authored-by: Ryan Trinkle <ryan@trinkle.org>
This commit is contained in:
Robert Helgesson 2022-04-01 01:22:54 +02:00
parent 742c6cb3e9
commit 8d38ca8868
No known key found for this signature in database
GPG key ID: 36BDAA14C2797E89

View file

@ -72,20 +72,50 @@ in {
}; };
}; };
config = mkIf cfg.enable { config = mkMerge [
assertions = {
[ (hm.assertions.assertPlatform "xdg.mimeApps" pkgs platforms.linux) ]; # Given a package that installs .desktop files in the usual location,
# return a mapping from mime types to lists of desktop file names. This is
# suitable for use with `xdg.mimeApps.defaultApplications`.
lib.xdg.mimeAssociations = let
processLines = str:
zipAttrs
(filter (e: e != null) (map processLine (splitString "\n" str)));
# Deprecated but still used by some applications. processLine = str:
xdg.dataFile."applications/mimeapps.list".source = let
config.xdg.configFile."mimeapps.list".source; entry = splitString ";" str;
k = elemAt entry 0;
v = elemAt entry 1;
in if length entry == 2 then { ${k} = v; } else null;
xdg.configFile."mimeapps.list".text = associations = ps:
let joinValues = mapAttrs (n: concatStringsSep ";"); pkgs.runCommand "mime-assoc" { inherit ps; } ''
in generators.toINI { } { for p in $ps ; do
"Added Associations" = joinValues cfg.associations.added; for path in "$p"/share/applications/*.desktop ; do
"Removed Associations" = joinValues cfg.associations.removed; name="''${path##*/}"
"Default Applications" = joinValues cfg.defaultApplications; sed -n "/^MimeType=/ { s/.*=//; s/;/;$name\n/g; p; }" "$path"
}; done
}; done > "$out"
'';
in p: processLines (builtins.readFile (associations p));
}
(mkIf cfg.enable {
assertions =
[ (hm.assertions.assertPlatform "xdg.mimeApps" pkgs platforms.linux) ];
# Deprecated but still used by some applications.
xdg.dataFile."applications/mimeapps.list".source =
config.xdg.configFile."mimeapps.list".source;
xdg.configFile."mimeapps.list".text =
let joinValues = mapAttrs (n: concatStringsSep ";");
in generators.toINI { } {
"Added Associations" = joinValues cfg.associations.added;
"Removed Associations" = joinValues cfg.associations.removed;
"Default Applications" = joinValues cfg.defaultApplications;
};
})
];
} }