git.iko.soy/typeable/nixpkgs
on master help sign in
lib.generators: add toGitINI

This code was taken from the home-manager project.

commit10c96e5b60cec0025e1576ab451237a291aa5a91 authorzimbatm <zimbatm@zimbatm.com> dateThu 5 Mar 2020, 18:59 (7 years ago) parentaf615af
1 file changed+53
lib/generators.nix+53
lib/generators.nix+53
@@ -126,6 +126,59 @@ rec {
126126 # map input to ini sections
127127 mapAttrsToStringsSep "\n" mkSection attrsOfAttrs;
128128
129+ /* Generate a git-config file from an attrset.
130+ *
131+ * It has two major differences from the regular INI format:
132+ *
133+ * 1. values are indented with tabs
134+ * 2. sections can have sub-sections
135+ *
136+ * generators.toGitINI {
137+ * url."ssh://git@github.com/".insteadOf = "https://github.com";
138+ * user.name = "edolstra";
139+ * }
140+ *
141+ *> [url "ssh://git@github.com/"]
142+ *> insteadOf = https://github.com/
143+ *>
144+ *> [user]
145+ *> name = edolstra
146+ */
147+ toGitINI = attrs:
148+ with builtins;
149+ let
150+ mkSectionName = name:
151+ let
152+ containsQuote = libStr.hasInfix ''"'' name;
153+ sections = libStr.splitString "." name;
154+ section = head sections;
155+ subsections = tail sections;
156+ subsection = concatStringsSep "." subsections;
157+ in if containsQuote || subsections == [ ] then
158+ name
159+ else
160+ ''${section} "${subsection}"'';
161+
162+ # generation for multiple ini values
163+ mkKeyValue = k: v:
164+ let mkKeyValue = mkKeyValueDefault { } " = " k;
165+ in concatStringsSep "\n" (map (kv: "\t" + mkKeyValue kv) (lib.toList v));
166+
167+ # converts { a.b.c = 5; } to { "a.b".c = 5; } for toINI
168+ gitFlattenAttrs = let
169+ recurse = path: value:
170+ if isAttrs value then
171+ lib.mapAttrsToList (name: value: recurse ([ name ] ++ path) value) value
172+ else if length path > 1 then {
173+ ${concatStringsSep "." (lib.reverseList (tail path))}.${head path} = value;
174+ } else {
175+ ${head path} = value;
176+ };
177+ in attrs: lib.foldl lib.recursiveUpdate { } (lib.flatten (recurse [ ] attrs));
178+
179+ toINI_ = toINI { inherit mkKeyValue mkSectionName; };
180+ in
181+ toINI_ (gitFlattenAttrs attrs);
129182
130183 /* Generates JSON from an arbitrary (non-function) value.
131184 * For more information see the documentation of the builtin.