Skip to content

Commit

Permalink
lib.strings.concatMapAttrsStringSep: init
Browse files Browse the repository at this point in the history
Co-authored-by: Silvan Mosberger <[email protected]>
  • Loading branch information
ShamrockLee and infinisil committed Aug 7, 2024
1 parent 4197076 commit 13c5586
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions lib/strings.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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")`.
Expand Down
6 changes: 6 additions & 0 deletions lib/tests/misc.nix
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ let
composeManyExtensions
concatLines
concatMapAttrs
concatMapAttrsStringSep
concatMapStrings
concatStrings
concatStringsSep
Expand Down Expand Up @@ -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";
Expand Down

0 comments on commit 13c5586

Please sign in to comment.