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 }:
with lib;
let
inherit (lib) types;
in
rec {
autoGroupOption = types.submodule {
options = {
clear = mkOption {
clear = lib.mkOption {
type = types.bool;
description = "Clear existing commands if the group already exists.";
default = true;

View file

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

View file

@ -1,5 +1,7 @@
{ lib, helpers }:
with lib;
let
inherit (lib) optionalAttrs isAttrs types;
in
rec {
# These are the configuration options that change the behavior of each mapping.
mapConfigOptions = {
@ -17,7 +19,7 @@ rec {
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.";
};
@ -52,9 +54,9 @@ rec {
};
modeEnum =
types.enum
lib.types.enum
# ["" "n" "v" ...]
(map ({ short, ... }: short) (attrValues modes));
(map ({ short, ... }: short) (lib.attrValues modes));
mapOptionSubmodule = mkMapOptionSubmodule { };
@ -66,8 +68,8 @@ rec {
mkModeOption =
default:
mkOption {
type = with types; either modeEnum (listOf modeEnum);
lib.mkOption {
type = with lib.types; either modeEnum (listOf modeEnum);
description = ''
One or several modes.
Use the short-names (`"n"`, `"v"`, ...).
@ -96,17 +98,16 @@ rec {
extraOptions ? { },
extraModules ? [ ],
}:
with types;
submodule (
types.submodule (
{ config, options, ... }:
{
imports = extraModules;
options =
(optionalAttrs (isAttrs key || key) {
key = mkOption (
(lib.optionalAttrs (isAttrs key || key) {
key = lib.mkOption (
{
type = str;
type = types.str;
description = "The key to map.";
example = "<C-m>";
}
@ -115,9 +116,9 @@ rec {
);
})
// (optionalAttrs (isAttrs action || action) {
action = mkOption (
action = lib.mkOption (
{
type = maybeRaw str;
type = types.maybeRaw types.str;
description = "The action to execute.";
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) {
lua = mkOption (
lua = lib.mkOption (
{
type = bool;
type = types.bool;
description = ''
If true, `action` is considered to be lua code.
Thus, it will not be wrapped in `""`.

View file

@ -1,11 +1,10 @@
{ lib, helpers }:
with lib;
{
# TODO: DEPRECATED: use the `settings` option instead
extraOptionsOptions = {
extraOptions = mkOption {
extraOptions = lib.mkOption {
default = { };
type = with types; attrsOf anything;
type = with lib.types; attrsOf anything;
description = ''
These attributes will be added to the table parameter for the setup function.
Typically, it can override NixVim's default settings.
@ -78,7 +77,7 @@ with lib;
options.${namespace}.${name} =
{
enable = mkEnableOption originalName;
enable = lib.mkEnableOption originalName;
package =
if lib.isOption package then
package
@ -94,7 +93,7 @@ with lib;
];
};
}
// optionalAttrs hasSettings {
// lib.optionalAttrs hasSettings {
settings = helpers.mkSettingsOption {
description = settingsDescription;
options = settingsOptions;
@ -103,19 +102,25 @@ with lib;
}
// 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;
}
(optionalAttrs callSetup {
(lib.optionalAttrs callSetup {
${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)
]);
]
);
};
in
{
@ -129,9 +134,9 @@ with lib;
in
imports
++ [ module ]
++ (optional deprecateExtraOptions (
mkRenamedOptionModule (basePluginPath ++ [ "extraOptions" ]) settingsPath
++ (lib.optional deprecateExtraOptions (
lib.mkRenamedOptionModule (basePluginPath ++ [ "extraOptions" ]) settingsPath
))
++ (nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings);
++ (lib.nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings);
};
}

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,4 @@
{ lib, helpers }:
with lib;
{
mkVimPlugin =
{
@ -34,9 +33,9 @@ with lib;
let
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 {
options = settingsOptions;
example = settingsExample;
@ -77,7 +76,7 @@ with lib;
};
options.${namespace}.${name} = {
enable = mkEnableOption originalName;
enable = lib.mkEnableOption originalName;
package =
if lib.isOption package then
package
@ -94,16 +93,20 @@ with lib;
};
} // settingsOption // extraOptions;
config = mkIf cfg.enable (mkMerge [
config = lib.mkIf cfg.enable (
lib.mkMerge [
{
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.
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)
]);
]
);
};
in
{
@ -117,9 +120,9 @@ with lib;
in
imports
++ [ module ]
++ (optional (deprecateExtraConfig && createSettingsOption) (
mkRenamedOptionModule (basePluginPath ++ [ "extraConfig" ]) settingsPath
++ (lib.optional (deprecateExtraConfig && createSettingsOption) (
lib.mkRenamedOptionModule (basePluginPath ++ [ "extraConfig" ]) settingsPath
))
++ (nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings);
++ (lib.nixvim.mkSettingsRenamedOptionModules basePluginPath settingsPath optionsRenamedToSettings);
};
}