From 13c5586d7fec4eaf0394ec4d396a1cb773183bd3 Mon Sep 17 00:00:00 2001 From: Yueh-Shun Li Date: Fri, 26 Jul 2024 03:00:09 +0800 Subject: [PATCH] lib.strings.concatMapAttrsStringSep: init Co-authored-by: Silvan Mosberger --- lib/default.nix | 2 +- lib/strings.nix | 31 +++++++++++++++++++++++++++++++ lib/tests/misc.nix | 6 ++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/default.nix b/lib/default.nix index 63a31101eee7f..2a5b11e8b6155 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -99,7 +99,7 @@ let length head tail elem elemAt isList; inherit (self.strings) concatStrings concatMapStrings concatImapStrings stringLength substring isString replaceStrings - intersperse concatStringsSep concatMapStringsSep + intersperse concatStringsSep concatMapStringsSep concatMapAttrsStringSep concatImapStringsSep concatLines makeSearchPath makeSearchPathOutput makeLibraryPath makeIncludePath makeBinPath optionalString hasInfix hasPrefix hasSuffix stringToCharacters stringAsChars escape diff --git a/lib/strings.nix b/lib/strings.nix index aafbdffaa7bc0..a6a1cafe856c1 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -269,6 +269,37 @@ rec { f: list: concatStringsSep sep (lib.imap1 f list); + /** + Like [`concatMapStringsSep`](#function-library-lib.strings.concatMapStringsSep) + but takes an attribute set instead of a list. + + # Type + + ``` + concatMapAttrsStringSep :: String -> (String -> Any -> String) -> AttrSet -> String + ``` + + # Examples + + :::{.example} + ## `lib.strings.concatMapAttrsStringSep` usage example + + ```nix + concatMapAttrsStringSep "\n" (name: value: "${name}: foo-${value}") { a = "0.1.0"; b = "0.2.0"; } + => "a: foo-0.1.0\nb: foo-0.2.0" + ``` + + ::: + */ + concatMapAttrsStringSep = + # Separator to add between items + sep: + # Function that receives the attribute name and the value + f: + # Attribute set to map from + attrs: + concatMapStringsSep sep (name: f name attrs.${name}) (lib.attrNames attrs); + /** Concatenate a list of strings, adding a newline at the end of each one. Defined as `concatMapStrings (s: s + "\n")`. diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index d59f5586b82d7..b170b638b6a83 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -39,6 +39,7 @@ let composeManyExtensions concatLines concatMapAttrs + concatMapAttrsStringSep concatMapStrings concatStrings concatStringsSep @@ -330,6 +331,11 @@ runTests { expected = "a,b,c"; }; + testConcatMapAttrsStringSepExamples = { + expr = concatMapAttrsStringSep "\n" (name: value: "${name}: foo-${value}") { a = "0.1.0"; b = "0.2.0"; }; + expected = "a: foo-0.1.0\nb: foo-0.2.0"; + }; + testConcatLines = { expr = concatLines ["a" "b" "c"]; expected = "a\nb\nc\n";