Skip to content

Commit

Permalink
lib: init ansi module
Browse files Browse the repository at this point in the history
The lib.ansi module provides a basic set of ANSI escape sequences to
colorize and style text. The main purpose is to colorize trace
messages (warnings, errors).
  • Loading branch information
phip1611 committed Apr 2, 2024
1 parent 46bcc66 commit 50e5e29
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
58 changes: 58 additions & 0 deletions lib/ansi.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# This exports a basic set of ANSI escape sequences to colorize terminal output.

{ ... }:

let
colorCodeMap = {
black = 0;
red = 1;
green = 2;
yellow = 3;
blue = 4;
magenta = 5;
cyan = 6;
white = 7;
};

# Escape character. "\e" or similar encodings currently not supported by Nix.
esc = "";
reset = "${esc}[0m";
style = {
bold = "${esc}[1m";
italic = "${esc}[3m";
};
# Only foreground colors are supported at the moment.
color = builtins.mapAttrs (name: value: "${esc}[3${toString value}m") colorCodeMap;

/* Stylizes a string with ANSI escape sequences.
Type: stylize :: [String] -> String -> String
*/
stylize =
# List of ANSI style attributes.
styles:
# Text to encapsulate by style.
text:
let
ansiBefore = builtins.concatStringsSep "" styles;
in
if text == ""
then ""
else "${ansiBefore}${text}${reset}";

/* Stylizes a string as bold and red.
Type: stylizeError :: String -> String
*/
stylizeError = text: stylize [ style.bold color.red ] text;

/* Stylizes a string as bold and yellow.
Type: stylizeWarn :: String -> String
*/
stylizeWarn = text: stylize [ style.bold color.yellow ] text;
in
{
inherit color style reset;
inherit stylize stylizeError stylizeWarn;
}
1 change: 1 addition & 0 deletions lib/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ let
generators = callLibs ./generators.nix;

# misc
ansi = callLibs ./ansi.nix;
asserts = callLibs ./asserts.nix;
debug = callLibs ./debug.nix;
misc = callLibs ./deprecated.nix;
Expand Down
16 changes: 16 additions & 0 deletions lib/tests/misc.nix
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ let
inherit (lib)
allUnique
and
ansi
attrNames
attrsets
attrsToList
Expand Down Expand Up @@ -1543,6 +1544,21 @@ runTests {
}'';
};

# MISC

testAnsiStylizeEmptyInput = {
expr = ansi.stylize [ansi.style.bold ansi.color.fg.red] "";
expected = "";
};
testAnsiStylizeError = {
expr = ansi.stylizeError "ERROR";
expected = "ERROR";
};
testAnsiStylizeWarn = {
expr = ansi.stylizeWarn "WARN";
expected = "WARN";
};

# CLI

testToGNUCommandLine = {
Expand Down

0 comments on commit 50e5e29

Please sign in to comment.