lib: cleanup with lib

This commit is contained in:
Austin Horstman 2024-08-30 14:49:20 -05:00
parent c76e5070b9
commit 35788bbc5a
No known key found for this signature in database
9 changed files with 179 additions and 160 deletions

View file

@ -1,9 +1,11 @@
{ lib, helpers }: { lib, helpers }:
with lib; let
inherit (lib) types;
in
rec { rec {
autoGroupOption = types.submodule { autoGroupOption = types.submodule {
options = { options = {
clear = mkOption { clear = lib.mkOption {
type = types.bool; type = types.bool;
description = "Clear existing commands if the group already exists."; description = "Clear existing commands if the group already exists.";
default = true; default = true;

View file

@ -1,5 +1,4 @@
{ lib }: { lib }:
with lib;
rec { rec {
# Get a (sub)option by walking the path, # Get a (sub)option by walking the path,
# checking for submodules along the way # checking for submodules along the way
@ -7,14 +6,14 @@ rec {
opt: prefix: optionPath: opt: prefix: optionPath:
if optionPath == [ ] then if optionPath == [ ] then
opt opt
else if isOption opt then else if lib.isOption opt then
getOptionRecursive (opt.type.getSubOptions prefix) prefix optionPath getOptionRecursive (opt.type.getSubOptions prefix) prefix optionPath
else else
let let
name = head optionPath; name = lib.head optionPath;
opt' = getAttr name opt; opt' = lib.getAttr name opt;
prefix' = prefix ++ [ name ]; prefix' = prefix ++ [ name ];
optionPath' = drop 1 optionPath; optionPath' = lib.drop 1 optionPath;
in in
getOptionRecursive opt' prefix' optionPath'; getOptionRecursive opt' prefix' optionPath';
@ -24,7 +23,8 @@ rec {
optionPath: replacementInstructions: optionPath: replacementInstructions:
{ options, ... }: { options, ... }:
{ {
options = setAttrByPath optionPath (mkOption { options = lib.setAttrByPath optionPath (
lib.mkOption {
# When (e.g.) `mkAttrs` is used on a submodule, this option will be evaluated. # When (e.g.) `mkAttrs` is used on a submodule, this option will be evaluated.
# Therefore we have to apply _something_ (null) when there's no definition. # Therefore we have to apply _something_ (null) when there's no definition.
apply = apply =
@ -35,13 +35,14 @@ rec {
in in
if res.success then res.value else null; if res.success then res.value else null;
visible = false; visible = false;
}); }
);
config.warnings = config.warnings =
let let
opt = getOptionRecursive options [ ] optionPath; opt = getOptionRecursive options [ ] optionPath;
in in
optional opt.isDefined '' lib.optional opt.isDefined ''
The option definition `${showOption optionPath}' in ${showFiles opt.files} is deprecated. The option definition `${lib.showOption optionPath}' in ${lib.showFiles opt.files} is deprecated.
${replacementInstructions} ${replacementInstructions}
''; '';
}; };
@ -51,11 +52,11 @@ rec {
map ( map (
option': option':
let let
option = toList option'; option = lib.toList option';
oldPath = oldPrefix ++ option; oldPath = oldPrefix ++ option;
newPath = newPrefix ++ map nixvim.toSnakeCase option; newPath = newPrefix ++ map lib.nixvim.toSnakeCase option;
in in
mkRenamedOptionModule oldPath newPath lib.mkRenamedOptionModule oldPath newPath
); );
# A clone of types.coercedTo, but it prints a warning when oldType is used. # A clone of types.coercedTo, but it prints a warning when oldType is used.

View file

@ -1,5 +1,7 @@
{ lib, helpers }: { lib, helpers }:
with lib; let
inherit (lib) optionalAttrs isAttrs types;
in
rec { rec {
# These are the configuration options that change the behavior of each mapping. # These are the configuration options that change the behavior of each mapping.
mapConfigOptions = { mapConfigOptions = {
@ -17,7 +19,7 @@ rec {
remap = helpers.defaultNullOpts.mkBool false "Make the mapping recursive. Inverses `noremap`."; remap = helpers.defaultNullOpts.mkBool false "Make the mapping recursive. Inverses `noremap`.";
desc = helpers.mkNullOrOption types.str "A textual description of this keybind, to be shown in which-key, if you have it."; desc = helpers.mkNullOrOption lib.types.str "A textual description of this keybind, to be shown in which-key, if you have it.";
buffer = helpers.defaultNullOpts.mkBool false "Make the mapping buffer-local. Equivalent to adding `<buffer>` to a map."; buffer = helpers.defaultNullOpts.mkBool false "Make the mapping buffer-local. Equivalent to adding `<buffer>` to a map.";
}; };
@ -52,9 +54,9 @@ rec {
}; };
modeEnum = modeEnum =
types.enum lib.types.enum
# ["" "n" "v" ...] # ["" "n" "v" ...]
(map ({ short, ... }: short) (attrValues modes)); (map ({ short, ... }: short) (lib.attrValues modes));
mapOptionSubmodule = mkMapOptionSubmodule { }; mapOptionSubmodule = mkMapOptionSubmodule { };
@ -66,8 +68,8 @@ rec {
mkModeOption = mkModeOption =
default: default:
mkOption { lib.mkOption {
type = with types; either modeEnum (listOf modeEnum); type = with lib.types; either modeEnum (listOf modeEnum);
description = '' description = ''
One or several modes. One or several modes.
Use the short-names (`"n"`, `"v"`, ...). Use the short-names (`"n"`, `"v"`, ...).
@ -96,17 +98,16 @@ rec {
extraOptions ? { }, extraOptions ? { },
extraModules ? [ ], extraModules ? [ ],
}: }:
with types; types.submodule (
submodule (
{ config, options, ... }: { config, options, ... }:
{ {
imports = extraModules; imports = extraModules;
options = options =
(optionalAttrs (isAttrs key || key) { (lib.optionalAttrs (isAttrs key || key) {
key = mkOption ( key = lib.mkOption (
{ {
type = str; type = types.str;
description = "The key to map."; description = "The key to map.";
example = "<C-m>"; example = "<C-m>";
} }
@ -115,9 +116,9 @@ rec {
); );
}) })
// (optionalAttrs (isAttrs action || action) { // (optionalAttrs (isAttrs action || action) {
action = mkOption ( action = lib.mkOption (
{ {
type = maybeRaw str; type = types.maybeRaw types.str;
description = "The action to execute."; description = "The action to execute.";
apply = v: if options.lua.isDefined or false && config.lua then helpers.mkRaw v else v; apply = v: if options.lua.isDefined or false && config.lua then helpers.mkRaw v else v;
} }
@ -126,9 +127,9 @@ rec {
); );
}) })
// optionalAttrs (isAttrs lua || lua) { // optionalAttrs (isAttrs lua || lua) {
lua = mkOption ( lua = lib.mkOption (
{ {
type = bool; type = types.bool;
description = '' description = ''
If true, `action` is considered to be lua code. If true, `action` is considered to be lua code.
Thus, it will not be wrapped in `""`. Thus, it will not be wrapped in `""`.

View file

@ -1,11 +1,10 @@
{ lib, helpers }: { lib, helpers }:
with lib;
{ {
# TODO: DEPRECATED: use the `settings` option instead # TODO: DEPRECATED: use the `settings` option instead
extraOptionsOptions = { extraOptionsOptions = {
extraOptions = mkOption { extraOptions = lib.mkOption {
default = { }; default = { };
type = with types; attrsOf anything; type = with lib.types; attrsOf anything;
description = '' description = ''
These attributes will be added to the table parameter for the setup function. These attributes will be added to the table parameter for the setup function.
Typically, it can override NixVim's default settings. Typically, it can override NixVim's default settings.
@ -78,7 +77,7 @@ with lib;
options.${namespace}.${name} = options.${namespace}.${name} =
{ {
enable = mkEnableOption originalName; enable = lib.mkEnableOption originalName;
package = package =
if lib.isOption package then if lib.isOption package then
package package
@ -94,7 +93,7 @@ with lib;
]; ];
}; };
} }
// optionalAttrs hasSettings { // lib.optionalAttrs hasSettings {
settings = helpers.mkSettingsOption { settings = helpers.mkSettingsOption {
description = settingsDescription; description = settingsDescription;
options = settingsOptions; options = settingsOptions;
@ -103,19 +102,25 @@ with lib;
} }
// extraOptions; // extraOptions;
config = mkIf cfg.enable (mkMerge [ config = lib.mkIf cfg.enable (
lib.mkMerge [
{ {
extraPlugins = (optional installPackage cfg.package) ++ extraPlugins; extraPlugins = (lib.optional installPackage cfg.package) ++ extraPlugins;
inherit extraPackages; inherit extraPackages;
} }
(optionalAttrs callSetup { (lib.optionalAttrs callSetup {
${extraConfigNamespace} = '' ${extraConfigNamespace} = ''
require('${luaName}')${setup}(${optionalString (cfg ? settings) (helpers.toLuaObject cfg.settings)}) require('${luaName}')${setup}(${
lib.optionalString (cfg ? settings) (helpers.toLuaObject cfg.settings)
})
''; '';
}) })
(optionalAttrs (isColorscheme && (colorscheme != null)) { colorscheme = mkDefault colorscheme; }) (lib.optionalAttrs (isColorscheme && (colorscheme != null)) {
colorscheme = lib.mkDefault colorscheme;
})
(extraConfig cfg) (extraConfig cfg)
]); ]
);
}; };
in in
{ {
@ -129,9 +134,9 @@ with lib;
in in
imports imports
++ [ module ] ++ [ module ]
++ (optional deprecateExtraOptions ( ++ (lib.optional deprecateExtraOptions (
mkRenamedOptionModule (basePluginPath ++ [ "extraOptions" ]) settingsPath lib.mkRenamedOptionModule (basePluginPath ++ [ "extraOptions" ]) settingsPath
)) ))
++ (nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings); ++ (lib.nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings);
}; };
} }

View file

@ -1,6 +1,7 @@
{ lib, helpers }: { lib, helpers }:
with lib;
let let
inherit (lib) types;
# Render a plugin default string # Render a plugin default string
pluginDefaultText = pluginDefaultText =
{ {
@ -9,7 +10,7 @@ let
# nix option default value, used if `defaultText` is missing # nix option default value, used if `defaultText` is missing
default ? null, default ? null,
# nix option default string or literal expression # nix option default string or literal expression
defaultText ? options.renderOptionValue default // { defaultText ? lib.options.renderOptionValue default // {
__lang = "nix"; __lang = "nix";
}, },
... ...
@ -20,15 +21,15 @@ let
if pluginDefault ? _type && pluginDefault ? text then if pluginDefault ? _type && pluginDefault ? text then
pluginDefault pluginDefault
else else
options.renderOptionValue pluginDefault // { __lang = "nix"; }; lib.options.renderOptionValue pluginDefault // { __lang = "nix"; };
# Format text using markdown code block or inline code # Format text using markdown code block or inline code
# Handle `v` being a literalExpression or literalMD type # Handle `v` being a literalExpression or literalMD type
toMD = toMD =
v: v:
let let
value = options.renderOptionValue v; value = lib.options.renderOptionValue v;
multiline = hasInfix "\n" value.text; multiline = lib.hasInfix "\n" value.text;
lang = value.__lang or ""; # `__lang` is added internally when parsed in argument defaults lang = value.__lang or ""; # `__lang` is added internally when parsed in argument defaults
in in
if value._type == "literalMD" then if value._type == "literalMD" then
@ -38,7 +39,7 @@ let
else else
" `${value.text}`"; " `${value.text}`";
in in
literalMD '' lib.literalMD ''
${toMD defaultText} ${toMD defaultText}
_Plugin default:_${toMD pluginDefaultText} _Plugin default:_${toMD pluginDefaultText}
@ -52,7 +53,7 @@ let
processNixvimArgs = processNixvimArgs =
args: args:
(removeAttrs args [ "pluginDefault" ]) (removeAttrs args [ "pluginDefault" ])
// (optionalAttrs (args ? pluginDefault) { defaultText = pluginDefaultText args; }); // (lib.optionalAttrs (args ? pluginDefault) { defaultText = pluginDefaultText args; });
in in
rec { rec {
inherit pluginDefaultText; inherit pluginDefaultText;
@ -76,7 +77,7 @@ rec {
mkCompositeOption' = mkCompositeOption' =
{ options, ... }@args: { options, ... }@args:
mkNullOrOption' ( mkNullOrOption' (
(filterAttrs (n: _: n != "options") args) // { type = types.submodule { inherit options; }; } (lib.filterAttrs (n: _: n != "options") args) // { type = types.submodule { inherit options; }; }
); );
mkCompositeOption = description: options: mkCompositeOption' { inherit description options; }; mkCompositeOption = description: options: mkCompositeOption' { inherit description options; };
@ -111,7 +112,7 @@ rec {
args args
// { // {
type = with types; either strLua type; type = with types; either strLua type;
apply = v: if isString v then helpers.mkRaw v else v; apply = v: if lib.isString v then helpers.mkRaw v else v;
} }
); );
mkNullOrStrLuaOr = type: description: mkNullOrStrLuaOr' { inherit type description; }; mkNullOrStrLuaOr = type: description: mkNullOrStrLuaOr' { inherit type description; };
@ -122,7 +123,7 @@ rec {
args args
// { // {
type = with types; either strLuaFn type; type = with types; either strLuaFn type;
apply = v: if isString v then helpers.mkRaw v else v; apply = v: if lib.isString v then helpers.mkRaw v else v;
} }
); );
mkNullOrStrLuaFnOr = type: description: mkNullOrStrLuaFnOr' { inherit type description; }; mkNullOrStrLuaFnOr = type: description: mkNullOrStrLuaFnOr' { inherit type description; };
@ -203,18 +204,18 @@ rec {
mkEnum' = mkEnum' =
{ values, ... }@args: { values, ... }@args:
let let
showInline = generators.toPretty { multiline = false; }; showInline = lib.generators.toPretty { multiline = false; };
# Check `v` is either null, one of `values`, or a literal type # Check `v` is either null, one of `values`, or a literal type
assertIsValid = assertIsValid =
v: v:
v == null v == null
|| elem v values || lib.elem v values
|| (v ? _type && v ? text) || (v ? _type && v ? text)
|| (v ? __raw && isString v.__raw) || (v ? __raw && lib.isString v.__raw)
|| throw "Default value ${showInline v} is not valid for enum ${showInline values}."; || throw "Default value ${showInline v} is not valid for enum ${showInline values}.";
in in
# Ensure `values` is a list and `pluginDefault` is valid if present # Ensure `values` is a list and `pluginDefault` is valid if present
assert isList values; assert lib.isList values;
assert args ? pluginDefault -> assertIsValid args.pluginDefault; assert args ? pluginDefault -> assertIsValid args.pluginDefault;
mkNullableWithRaw' (removeAttrs args [ "values" ] // { type = types.enum values; }); mkNullableWithRaw' (removeAttrs args [ "values" ] // { type = types.enum values; });
mkEnum = mkEnum =
@ -224,7 +225,7 @@ rec {
values: description: values: description:
mkEnum' { mkEnum' {
inherit values description; inherit values description;
pluginDefault = head values; pluginDefault = lib.head values;
}; };
mkBorder' = mkBorder' =
@ -234,11 +235,11 @@ rec {
... ...
}@args: }@args:
mkNullableWithRaw' ( mkNullableWithRaw' (
(filterAttrs (n: v: n != "name") args) (lib.filterAttrs (n: v: n != "name") args)
// { // {
type = types.border; type = types.border;
description = concatStringsSep "\n" ( description = lib.concatStringsSep "\n" (
(optional (description != "") description) (lib.optional (description != "") description)
++ [ ++ [
"Defines the border to use for ${name}." "Defines the border to use for ${name}."
"Accepts same border values as `nvim_open_win()`. See `:help nvim_open_win()` for more info." "Accepts same border values as `nvim_open_win()`. See `:help nvim_open_win()` for more info."
@ -263,9 +264,12 @@ rec {
"info" "info"
"hint" "hint"
]); ]);
apply = mapNullable ( apply = lib.mapNullable (
value: value:
if isInt value then value else helpers.mkRaw "vim.diagnostic.severity.${strings.toUpper value}" if lib.isInt value then
value
else
helpers.mkRaw "vim.diagnostic.severity.${lib.strings.toUpper value}"
); );
} }
); );
@ -277,8 +281,9 @@ rec {
args args
// { // {
type = with types; either ints.unsigned logLevel; type = with types; either ints.unsigned logLevel;
apply = mapNullable ( apply = lib.mapNullable (
value: if isInt value then value else helpers.mkRaw "vim.log.levels.${strings.toUpper value}" value:
if lib.isInt value then value else helpers.mkRaw "vim.log.levels.${lib.strings.toUpper value}"
); );
} }
); );
@ -304,7 +309,7 @@ rec {
{ {
inherit pluginDefault; inherit pluginDefault;
} }
// (optionalAttrs (description != null && description != "") { inherit description; }) // (lib.optionalAttrs (description != null && description != "") { inherit description; })
); );
}; };
@ -316,7 +321,7 @@ rec {
# `name` must be present if `description` is missing # `name` must be present if `description` is missing
assert (!args ? description) -> args ? name; assert (!args ? description) -> args ? name;
mkNullOrOption' ( mkNullOrOption' (
(filterAttrs (n: _: n != "name") args) (lib.filterAttrs (n: _: n != "name") args)
// { // {
type = types.package; type = types.package;
description = description =
@ -330,7 +335,7 @@ rec {
# TODO: Deprecated 2024-09-02; remove once all internal uses are gone # TODO: Deprecated 2024-09-02; remove once all internal uses are gone
mkPluginPackageOption = mkPluginPackageOption =
name: default: name: default:
mkOption { lib.mkOption {
type = types.package; type = types.package;
inherit default; inherit default;
description = "Which package to use for the ${name} plugin."; description = "Which package to use for the ${name} plugin.";
@ -342,7 +347,7 @@ rec {
description, description,
example ? null, example ? null,
}: }:
mkOption { lib.mkOption {
type = type =
with types; with types;
submodule { submodule {

View file

@ -1,10 +1,9 @@
{ lib }: { lib }:
with lib;
rec { rec {
# Whether the string is a reserved keyword in lua # Whether the string is a reserved keyword in lua
isKeyword = isKeyword =
s: s:
elem s [ lib.elem s [
"and" "and"
"break" "break"
"do" "do"
@ -150,18 +149,18 @@ rec {
value value
else if isInline value then else if isInline value then
value value
else if isDerivation value then else if lib.isDerivation value then
value value
else if isList value then else if lib.isList value then
let let
needsFiltering = removeNullListEntries || removeEmptyListEntries; needsFiltering = removeNullListEntries || removeEmptyListEntries;
fn = fn =
v: (removeNullListEntries -> (v != null)) && (removeEmptyListEntries -> (v != [ ] && v != { })); v: (removeNullListEntries -> (v != null)) && (removeEmptyListEntries -> (v != [ ] && v != { }));
v' = map removeEmptiesRecursive value; v' = map removeEmptiesRecursive value;
in in
if needsFiltering then filter fn v' else v' if needsFiltering then lib.filter fn v' else v'
else if isAttrs value then else if lib.isAttrs value then
concatMapAttrs ( lib.concatMapAttrs (
n: v: n: v:
let let
v' = removeEmptiesRecursive v; v' = removeEmptiesRecursive v;
@ -184,12 +183,12 @@ rec {
# Return the dict-style table key, formatted as per the config # Return the dict-style table key, formatted as per the config
toTableKey = toTableKey =
s: s:
if allowRawAttrKeys && hasPrefix "__rawKey__" s then if allowRawAttrKeys && lib.hasPrefix "__rawKey__" s then
"[${removePrefix "__rawKey__" s}]" "[${lib.removePrefix "__rawKey__" s}]"
else if allowUnquotedAttrKeys && isIdentifier s then else if allowUnquotedAttrKeys && isIdentifier s then
s s
else if allowLegacyEmptyStringAttr && s == "__emptyString" then else if allowLegacyEmptyStringAttr && s == "__emptyString" then
trace ''nixvim(toLua): __emptyString is deprecated, just use an attribute named "".'' ( lib.trace ''nixvim(toLua): __emptyString is deprecated, just use an attribute named "".'' (
toTableKey "" toTableKey ""
) )
else else
@ -208,17 +207,17 @@ rec {
in in
if v == null then if v == null then
"nil" "nil"
else if isInt v then else if lib.isInt v then
toString v toString v
# toString loses precision on floats, so we use toJSON instead. # toString loses precision on floats, so we use toJSON instead.
# It can output an exponent form supported by lua. # It can output an exponent form supported by lua.
else if isFloat v then else if lib.isFloat v then
builtins.toJSON v builtins.toJSON v
else if isBool v then else if lib.isBool v then
boolToString v lib.boolToString v
else if isPath v || isDerivation v then else if lib.isPath v || lib.isDerivation v then
go indent "${v}" go indent "${v}"
else if isString v then else if lib.isString v then
# TODO: support lua's escape sequences, literal string, and content-appropriate quote style # TODO: support lua's escape sequences, literal string, and content-appropriate quote style
# See https://www.lua.org/pil/2.4.html # See https://www.lua.org/pil/2.4.html
# and https://www.lua.org/manual/5.1/manual.html#2.1 # and https://www.lua.org/manual/5.1/manual.html#2.1
@ -226,11 +225,15 @@ rec {
builtins.toJSON v builtins.toJSON v
else if v == [ ] || v == { } then else if v == [ ] || v == { } then
"{ }" "{ }"
else if isFunction v then else if lib.isFunction v then
abort "nixvim(toLua): Unexpected function: " + generators.toPretty { } v abort "nixvim(toLua): Unexpected function: " + lib.generators.toPretty { } v
else if isList v then else if lib.isList v then
"{" + introSpace + concatMapStringsSep ("," + introSpace) (go (indent + " ")) v + outroSpace + "}" "{"
else if isAttrs v then + introSpace
+ lib.concatMapStringsSep ("," + introSpace) (go (indent + " ")) v
+ outroSpace
+ "}"
else if lib.isAttrs v then
# apply pretty values if allowed # apply pretty values if allowed
if allowPrettyValues && v ? __pretty && v ? val then if allowPrettyValues && v ? __pretty && v ? val then
v.__pretty v.val v.__pretty v.val
@ -244,11 +247,11 @@ rec {
else else
"{" "{"
+ introSpace + introSpace
+ concatStringsSep ("," + introSpace) ( + lib.concatStringsSep ("," + introSpace) (
mapAttrsToList ( lib.mapAttrsToList (
name: value: name: value:
(if allowExplicitEmpty && hasPrefix "__unkeyed" name then "" else toTableKey name + " = ") (if allowExplicitEmpty && lib.hasPrefix "__unkeyed" name then "" else toTableKey name + " = ")
+ addErrorContext "while evaluating an attribute `${name}`" (go (indent + " ") value) + lib.addErrorContext "while evaluating an attribute `${name}`" (go (indent + " ") value)
) v ) v
) )
+ outroSpace + outroSpace

View file

@ -1,30 +1,30 @@
# Custom types to be included in `lib.types` # Custom types to be included in `lib.types`
{ lib, helpers }: { lib, helpers }:
with lib;
with helpers;
with lib.types;
let let
inherit (lib) types;
inherit (lib.nixvim) mkNullOrStr mkNullOrOption;
strLikeType = strLikeType =
description: description:
mkOptionType { lib.mkOptionType {
name = "str"; name = "str";
inherit description; inherit description;
descriptionClass = "noun"; descriptionClass = "noun";
check = v: isString v || isRawType v; check = v: lib.isString v || isRawType v;
merge = lib.options.mergeEqualOption; merge = lib.options.mergeEqualOption;
}; };
isRawType = v: v ? __raw && isString v.__raw; isRawType = v: v ? __raw && lib.isString v.__raw;
in in
rec { rec {
# TODO: deprecate in favor of types.rawLua.check # TODO: deprecate in favor of types.rawLua.check
# Or move to utils, lua, etc? # Or move to utils, lua, etc?
inherit isRawType; inherit isRawType;
rawLua = mkOptionType { rawLua = lib.mkOptionType {
name = "rawLua"; name = "rawLua";
description = "raw lua code"; description = "raw lua code";
descriptionClass = "noun"; descriptionClass = "noun";
merge = mergeEqualOption; merge = lib.options.mergeEqualOption;
check = v: (isRawType v) || (v ? __empty); check = v: (isRawType v) || (v ? __empty);
}; };
@ -83,14 +83,14 @@ rec {
strLuaFn = strLikeType "lua function string"; strLuaFn = strLikeType "lua function string";
# Overridden when building the documentation # Overridden when building the documentation
eitherRecursive = either; eitherRecursive = types.either;
listOfLen = listOfLen =
elemType: len: elemType: len:
addCheck (listOf elemType) (v: builtins.length v == len) types.addCheck (types.listOf elemType) (v: builtins.length v == len)
// { // {
description = "list of ${toString len} ${ description = "list of ${toString len} ${
optionDescriptionPhrase (class: class == "noun" || class == "composite") elemType types.optionDescriptionPhrase (class: class == "noun" || class == "composite") elemType
}"; }";
}; };
} }

View file

@ -3,14 +3,13 @@
helpers, helpers,
_nixvimTests, _nixvimTests,
}: }:
with lib;
rec { rec {
# Whether a string contains something other than whitespaces # Whether a string contains something other than whitespaces
hasContent = str: builtins.match "[[:space:]]*" str == null; hasContent = str: builtins.match "[[:space:]]*" str == null;
# Concatenate a list of strings, adding a newline at the end of each one, # Concatenate a list of strings, adding a newline at the end of each one,
# but skipping strings containing only whitespace characters # but skipping strings containing only whitespace characters
concatNonEmptyLines = lines: concatLines (builtins.filter hasContent lines); concatNonEmptyLines = lines: lib.concatLines (builtins.filter hasContent lines);
listToUnkeyedAttrs = listToUnkeyedAttrs =
list: list:
@ -38,7 +37,7 @@ rec {
toRawKeys :: AttrSet -> AttrSet toRawKeys :: AttrSet -> AttrSet
``` ```
*/ */
toRawKeys = mapAttrs' (n: v: nameValuePair "__rawKey__${n}" v); toRawKeys = lib.mapAttrs' (n: v: lib.nameValuePair "__rawKey__${n}" v);
/** /**
Create a 1-element attrs with a raw lua key. Create a 1-element attrs with a raw lua key.
@ -70,13 +69,13 @@ rec {
toSnakeCase = toSnakeCase =
let let
splitByWords = builtins.split "([A-Z])"; splitByWords = builtins.split "([A-Z])";
processWord = s: if isString s then s else "_" + toLower (elemAt s 0); processWord = s: if lib.isString s then s else "_" + lib.toLower (lib.elemAt s 0);
in in
string: string:
let let
words = splitByWords string; words = splitByWords string;
in in
concatStrings (map processWord words); lib.concatStrings (map processWord words);
/** /**
Capitalize a string by making the first character uppercase. Capitalize a string by making the first character uppercase.
@ -97,13 +96,13 @@ rec {
upperFirstChar = upperFirstChar =
s: s:
let let
first = substring 0 1 s; first = lib.substring 0 1 s;
rest = substring 1 (stringLength s) s; rest = lib.substring 1 (lib.stringLength s) s;
result = (toUpper first) + rest; result = (lib.toUpper first) + rest;
in in
optionalString (s != "") result; lib.optionalString (s != "") result;
mkIfNonNull' = x: y: (mkIf (x != null) y); mkIfNonNull' = x: y: (lib.mkIf (x != null) y);
mkIfNonNull = x: (mkIfNonNull' x x); mkIfNonNull = x: (mkIfNonNull' x x);
@ -113,12 +112,12 @@ rec {
r: r:
if r == null || r == "" then if r == null || r == "" then
null null
else if isString r then else if lib.isString r then
{ __raw = r; } { __raw = r; }
else if types.isRawType r then else if lib.types.isRawType r then
r r
else else
throw "mkRaw: invalid input: ${generators.toPretty { multiline = false; } r}"; throw "mkRaw: invalid input: ${lib.generators.toPretty { multiline = false; } r}";
wrapDo = string: '' wrapDo = string: ''
do do
@ -131,7 +130,7 @@ rec {
# TODO: account for a possible ']]' in the string # TODO: account for a possible ']]' in the string
wrapVimscriptForLua = wrapVimscriptForLua =
string: string:
optionalString (hasContent string) '' lib.optionalString (hasContent string) ''
vim.cmd([[ vim.cmd([[
${string} ${string}
]]) ]])
@ -142,7 +141,7 @@ rec {
# TODO: account for a possible 'EOF' if the string # TODO: account for a possible 'EOF' if the string
wrapLuaForVimscript = wrapLuaForVimscript =
string: string:
optionalString (hasContent string) '' lib.optionalString (hasContent string) ''
lua << EOF lua << EOF
${string} ${string}
EOF EOF
@ -151,16 +150,16 @@ rec {
# Split a list into a several sub-list, each with a max-size of `size` # Split a list into a several sub-list, each with a max-size of `size`
groupListBySize = groupListBySize =
size: list: size: list:
reverseList ( lib.reverseList (
foldl' ( lib.foldl' (
lists: item: lists: item:
let let
first = head lists; first = lib.head lists;
rest = drop 1 lists; rest = lib.drop 1 lists;
in in
if lists == [ ] then if lists == [ ] then
[ [ item ] ] [ [ item ] ]
else if length first < size then else if lib.length first < size then
[ (first ++ [ item ]) ] ++ rest [ (first ++ [ item ]) ] ++ rest
else else
[ [ item ] ] ++ lists [ [ item ] ] ++ lists

View file

@ -1,5 +1,4 @@
{ lib, helpers }: { lib, helpers }:
with lib;
{ {
mkVimPlugin = mkVimPlugin =
{ {
@ -34,9 +33,9 @@ with lib;
let let
namespace = if isColorscheme then "colorschemes" else "plugins"; namespace = if isColorscheme then "colorschemes" else "plugins";
createSettingsOption = (isString globalPrefix) && (globalPrefix != ""); createSettingsOption = (lib.isString globalPrefix) && (globalPrefix != "");
settingsOption = optionalAttrs createSettingsOption { settingsOption = lib.optionalAttrs createSettingsOption {
settings = helpers.mkSettingsOption { settings = helpers.mkSettingsOption {
options = settingsOptions; options = settingsOptions;
example = settingsExample; example = settingsExample;
@ -77,7 +76,7 @@ with lib;
}; };
options.${namespace}.${name} = { options.${namespace}.${name} = {
enable = mkEnableOption originalName; enable = lib.mkEnableOption originalName;
package = package =
if lib.isOption package then if lib.isOption package then
package package
@ -94,16 +93,20 @@ with lib;
}; };
} // settingsOption // extraOptions; } // settingsOption // extraOptions;
config = mkIf cfg.enable (mkMerge [ config = lib.mkIf cfg.enable (
lib.mkMerge [
{ {
inherit extraPackages; inherit extraPackages;
globals = mapAttrs' (n: nameValuePair (globalPrefix + n)) (cfg.settings or { }); globals = lib.mapAttrs' (n: lib.nameValuePair (globalPrefix + n)) (cfg.settings or { });
# does this evaluate package? it would not be desired to evaluate package if we use another package. # does this evaluate package? it would not be desired to evaluate package if we use another package.
extraPlugins = extraPlugins ++ optional (cfg.package != null) cfg.package; extraPlugins = extraPlugins ++ lib.optional (cfg.package != null) cfg.package;
} }
(optionalAttrs (isColorscheme && (colorscheme != null)) { colorscheme = mkDefault colorscheme; }) (lib.optionalAttrs (isColorscheme && (colorscheme != null)) {
colorscheme = lib.mkDefault colorscheme;
})
(extraConfig cfg) (extraConfig cfg)
]); ]
);
}; };
in in
{ {
@ -117,9 +120,9 @@ with lib;
in in
imports imports
++ [ module ] ++ [ module ]
++ (optional (deprecateExtraConfig && createSettingsOption) ( ++ (lib.optional (deprecateExtraConfig && createSettingsOption) (
mkRenamedOptionModule (basePluginPath ++ [ "extraConfig" ]) settingsPath lib.mkRenamedOptionModule (basePluginPath ++ [ "extraConfig" ]) settingsPath
)) ))
++ (nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings); ++ (lib.nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings);
}; };
} }