1.8.0 • Published 4 years ago

edit-config v1.8.0

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

edit-config

Read, edit, write configuration files.

Synopsis

Load, Edit & Save Single Config

import { DataFile, Manager } from "edit-config";
const packageJson = await DataFile.load("package.json");

packageJson
  .set("typings", "dist/index.d.ts",")
  .set("scripts.build", "tsc")
  .set("scripts.test", (value) => `${value} --coverage`)
  .merge("husky.hooks", { pre-commit: "eslint" })
  .merge("devDependencies", (value, key, data, path, dataFile) => ({ "@types/lodash": dataFile.get("dependencies.lodash") }) )
  .sortKeys("scripts", { start: ["build", "test", "lint"] });

await packageJson.save();

Cosmiconfig: Load, Edit & Save

// Loads from `package.json` or configuration file using cosmiconfig. Set true to use default cosmiconfig configuration.
const husky = await DataFile.load("husky", { cosmiconfig: true });
const eslint = await DataFile.load("eslint", { cosmiconfig: { options: cosmiconfigOptions, searchFrom: __dirname } });

husky.set("hooks.pre-commit", "lint-staged");

// Check if cosmiconfig data can be saved, because saving "js" files are not supported.
if (!husky.readOnly) await husky.save();

Load, Edit & Save Multiple Config

// Create manager and load files.
const manager = new Manager({ root: ".", logger: winstonLogger });
const [packageJson, tsconfig] = await manager.loadAll(["package.json", "tsconfig.json"]);
await manager.saveAll();

Example Logger

import { createLogger, format, transports } from "winston";
const logger = createLogger({
  level: "debug",
  format: format.combine(format.colorize(), format.splat(), format.simple()),
  transports: [new transports.Console()],
});

const packageJson = await DataFile.load("package.json", { logger });

Conditional Update

const packageJson = await DataFile.load("package.json");
packageJson
  .set("keywords", ["my", "keywords"], { if: (value) => value === undefined })
  .merge("scripts", { build: "tsc", test: "jest" }, { if: (value, key, data, path, rootData) => rootData.has("typings") });

Details

DataFile class reads JSON, YAML and JS configuration files and writes JSON and YAML files. Manager class is used to manage multiple DataFile classes.

Tips

  • Don't forget to add await when chaining async methods: await (await packageJson.reload()).save();

Highlights:

  • Provides has, get, set, merge methods based on lodash functions. delete is based on lodash.unset.
  • In addition to lodash functionality, manipulation methods accept value function and condition callback function for conditional manipulation.
  • load() and loadAll() do not throw even files do not exist. Instead return default data (if provided), or empty object.
  • Data manipulation operations do not write to disk until save() or saveAll() called if autoSave is false. (Default behaviour)
  • Manager.load() and Manager.loadAll() methods cache loaded files and return cached results in consequencing calls. Use DataFile.reload() to reload from disk.
  • Supports winston logger.

API

edit-config

Type aliases

FileFormat

Ƭ FileFormat: "" | "json" | "yaml" | "js"

Defined in types.ts:12

Data file format.


LogLevel

Ƭ LogLevel: "error" | "warn" | "info" | "http" | "verbose" | "debug" | "silly"

Defined in types.ts:9


PredicateFunction

Ƭ PredicateFunction: function

Defined in types.ts:29

Type declaration:

▸ (value: any, key: Key, data: object, path: Key[], dataFile: DataFile): boolean

Callback function to test whether operation should be performed. If result is false, operation is not performed.

Parameters:

NameTypeDescription
valueanyis the value to be modified.
keyKeyis the key of the changed value.
dataobjectis the object/array to get value from.
pathKey[]is the full data path of the value in root data.
dataFileDataFileis the DataFile instance.

ValueFunction

Ƭ ValueFunction: function

Defined in types.ts:42

Type declaration:

▸ (value: any, key: Key, data: object, path: Key[], dataFile: DataFile): any

If a function is provided instead of value, return value of the function is used as new value.

Parameters:

NameTypeDescription
valueanyis the value to be modified.
keyKeyis the key of the changed value.
dataobjectis the object/array to get value from.
pathKey[]is the full data path of the value in root data.
dataFileDataFileis the DataFile instance.

WritableFileFormat

Ƭ WritableFileFormat: "json" | "yaml"

Defined in types.ts:15

Writeable Data file format.

Classes

Class: DataFile ‹T

Read, edit and write configuration files.

Type parameters

T: object

Hierarchy

  • DataFile

Properties

data

data: T

Defined in data-file.ts:45

Actual data


found

found: boolean

Defined in data-file.ts:48

Whether file exists or cosmiconfig configuration found.

Accessors

readOnly

get readOnly(): boolean

Defined in data-file.ts:100

Whether file can be saved using this library.

Returns: boolean

Methods

delete

delete(path: DataPath, __namedParameters: object): this

Defined in data-file.ts:169

Deletes the property at path of file data.

Example

dataFile
  .delete("script.build")
  .delete(["scripts", "test"], { if: (value) => value !== "jest" });

Parameters:

path: DataPath

is data path of the property to delete.

Default value __namedParameters: object= {}

NameTypeDescription
conditionundefined | function-
loggerundefined | Loggeris winston compatible logger to be used when logging.

Returns: this


get

get(path: DataPath, defaultValue?: any): any

Defined in data-file.ts:129

Gets the value at path of file data. If the resolved value is undefined, the defaultValue is returned in its place.

Example

dataFile.get("script.build");
dataFile.get(["script", "build"]);

Parameters:

NameTypeDescription
pathDataPathis data path of the property to get.
defaultValue?anyis value to get if path does not exists on data.

Returns: any

data stored in given object path or default value.


getModifiedKeys

getModifiedKeys(__namedParameters: object): object

Defined in data-file.ts:224

Returns deleted and modified keys (paths) in data file. Keys may be filtered by required condition.

Example

dataFile.getModifiedKeys({ include: "scripts", exclude: ["scripts.validate", "scripts.docs"] });

Parameters:

Default value __namedParameters: object= {}

NameTypeDescription
filterundefined | functionis a filter function to test whether to include key and type in result.

Returns: object

set and deleted keys

  • deleted: StringDataPath[]

  • set: StringDataPath[]


has

has(path: DataPath): boolean

Defined in data-file.ts:114

Returns whether given path exists in file data.

Example

dataFile.has("script.build");
dataFile.has(["script", "build"]);

Parameters:

NameTypeDescription
pathDataPathis data path of the property to check.

Returns: boolean

whether path exists.


merge

merge(path: DataPath, ...valuesAndOptions: any[]): this

Defined in data-file.ts:196

This method is like assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

If you would like merge root object (this.data), use empty array [] as path, because undefined, '' and null are valid object keys.

Example

dataFile.merge("scripts", { build: "tsc", test: "jest", }, { if: (scripts) => scripts.build !== "someCompiler" });
dataFile.merge([], { name: "my-module", version: "1.0.0" });

Parameters:

NameTypeDescription
pathDataPathis data path of the property to delete.
...valuesAndOptionsany[]are objects to merge given path or a function which returns object to be merged.

Returns: this


reload

reload(): Promise‹this›

Defined in data-file.ts:380

Reload data from disk. If file is not present resets data to default data.

Returns: Promise‹this›


save

save(__namedParameters: object): Promise‹void›

Defined in data-file.ts:279

Saves file. If this is a partial data uses only related part by utilizing rootDataPath option.

Parameters:

Default value __namedParameters: object= {}

NameTypeDefaultDescription
loggerLoggerthis.#loggerWinston compatible logger to be used when logging.
throwOnReadOnlybooleantrueWhether to throw if file is read only.

Returns: Promise‹void›


serialize

serialize(wholeFile: boolean): Promise‹string›

Defined in data-file.ts:303

Returns data serialized as text.

Parameters:

NameTypeDefaultDescription
wholeFilebooleanfalseis whether to serialize whole file when rootDataPath is set. Reads whole file including rootDataPath part and serializes whole file data.

Returns: Promise‹string›

serialized data as string.


set

set(path: DataPath, value: any, __namedParameters: object): this

Defined in data-file.ts:147

Sets the value at path of file data. If a portion of path doesn't exist, it's created. Arrays are created for missing index properties while objects are created for all other missing properties.

Example

dataFile
  .set("script.build", "tsc")
  .set(["scripts", "test"], "jest", { if: (value) => value !== "mocha" });

Parameters:

path: DataPath

is data path of the property to set.

value: any

is value to set or a function which returns value to be set.

Default value __namedParameters: object= {}

NameTypeDescription
conditionundefined | function-
loggerundefined | Loggeris winston compatible logger to be used when logging.

Returns: this


sortKeys

sortKeys(path: DataPath, __namedParameters: object): this

Defined in data-file.ts:271

When keys/values added which are previously does not exist, they are added to the end of the file during file write. This method allows reordering of the keys in given path. Required keys may be put at the beginning and of the order.

If you would like sort root object (this.data) use sort method or, provide use empty array [] as path, because undefined, '' and null are valid object keys.

Example

dataFile.sortKeys("scripts", { start: ["build", "lint"], end: ["release"] });
dataFile.sortKeys({ start: ["name", "description"], end: ["dependencies", "devDependencies"] });

Parameters:

path: DataPath

is data path of the property to order keys of.

Default value __namedParameters: object= {}

NameTypeDescription
endundefined | string[]are ordered keys to appear at the end of given path when saved.
startundefined | string[]are ordered keys to appear at the beginning of given path when saved.

Returns: this


Static fromData

fromData(path: string, data: object, options: DataFileFromDataOptions): Promise‹DataFile

Defined in data-file.ts:344

Creates DataFile instance from given data to be saved for given file path.

Parameters:

NameTypeDefaultDescription
pathstring-is path of the file.
dataobject-is the data to create DataFile from.
optionsDataFileFromDataOptions{}are options.

Returns: Promise‹DataFile

DataFile instance.


Static load

load(path: string, options?: DataFileLoadOptions): Promise‹DataFile

Defined in data-file.ts:361

Reads data from given file. If file is not present returns default data to be saved with method.

throws if file exists but cannot be parsed.

Parameters:

NameTypeDescription
pathstringis path of the file.
options?DataFileLoadOptionsare options.

Returns: Promise‹DataFile

DataFile instance.

Class: Manager

Manage multiple configuration files using DataFile.

Hierarchy

  • Manager

Constructors

constructor

+ new Manager(__namedParameters: object): Manager

Defined in manager.ts:14

Creates a manager to manage multiple data files.

Parameters:

Default value __namedParameters: object= {} as any

NameTypeDefaultDescription
loggerLoggernoLoggeris the winston compatible Logger to be used when logging.
rootstringprocess.cwd()is the root path to be used for all relative file paths.
saveIfChangedundefined | false | true-is whether to save file only if data is changed. Clones initial data deeply to check during save.

Returns: Manager

Methods

fromData

fromData(path: string, data: object, options: ManagerFromDataOptions): Promise‹DataFile

Defined in manager.ts:67

Creates DataFile instance from given data and returns it. Also caches the data.

Parameters:

NameTypeDefaultDescription
pathstring-is the path of the file. Could be an absolute path or relative to root path option provided to Manager
dataobject-is the data to create DataFile from.
optionsManagerFromDataOptions{}are options

Returns: Promise‹DataFile

DataFile instance.


load

load(path: string, options: ManagerLoadOptions): Promise‹DataFile

Defined in manager.ts:42

Reads data from given file and caches it. If file is not present, returns default data to be saved with DataFile.save or [save} methods. If same data file requested multiple times returns cached data file. Absolute path of the file is used as cache key.

Example

manager.load("package.json");
manager.load("eslint", { defaultFormat: "json", cosmiconfig: { options: { packageProp: "eslint" }, searchForm: "some/path" } })

Parameters:

NameTypeDefaultDescription
pathstring-is the path of the file. Could be an absolute path or relative to root path option provided to Manager.
optionsManagerLoadOptions{}are options

Returns: Promise‹DataFile

DataFile instance.


loadAll

loadAll(paths: string[], options: object): Promise‹DataFile[]›

Defined in manager.ts:92

Reads data from all given files and caches them. If same data file requested multiple times returns cached data file. Absolute path of the file is used as cache key.

Parameters:

paths: string[]

are arry of paths of the files. Could be an absolute path or relative to root path option provided to Manager.

Default value options: object= {}

are options.

NameTypeDescription
defaultData?anyis the default data to be used if file does not exist.
defaultFormat?WritableFileFormatis the default format to be used if file format cannot be determined from file name and content.
readOnly?undefined | false | true-
saveIfChanged?undefined | false | trueis whether to save file only if data is changed. Clones initial data deeply to check during save.

Returns: Promise‹DataFile[]›


saveAll

saveAll(): Promise‹void›

Defined in manager.ts:102

Saves all files.

Returns: Promise‹void›

Interfaces

Interface: DataFileFromDataOptions

DataFile.fromData options.

Hierarchy

Properties

Optional defaultFormat

defaultFormat? : WritableFileFormat

Inherited from ManagerFromDataOptions.defaultFormat

Defined in types.ts:58

The default format to be used if file format cannot be determined from file name and content.


Optional logger

logger? : Logger

Defined in types.ts:78

Winston compatible logger to be used when logging.


Optional prettierConfig

prettierConfig? : PrettierConfig

Defined in types.ts:82

Prettier configuration to be used. If not provided determined automatically.


Optional readOnly

readOnly? : undefined | false | true

Inherited from ManagerFromDataOptions.readOnly

Defined in types.ts:62

Whether file can be saved using this library.


Optional rootDataPath

rootDataPath? : DataPath

Inherited from ManagerFromDataOptions.rootDataPath

Defined in types.ts:60

If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts, only script key of the data is loaded.


Optional rootDir

rootDir? : undefined | string

Defined in types.ts:80

Root directory for file. If provided, relative path is based on this root directory.


Optional saveIfChanged

saveIfChanged? : undefined | false | true

Inherited from ManagerFromDataOptions.saveIfChanged

Defined in types.ts:64

Whether to save file only if data is changed. Clones initial data deeply to check during save.

Interface: DataFileLoadOptions

[DatFile.load] options.

Hierarchy

DataFileFromDataOptions

DataFileLoadOptions

Properties

Optional cosmiconfig

cosmiconfig? : boolean | object

Defined in types.ts:90

Whether to use https://www.npmjs.com/package/cosmiconfig to load configuration. Set true for default cosmiconfig options or provide an object with options for cosmiconfig options and searchFrom to provide cosmiconfig.search() parameter.


Optional defaultData

defaultData? : undefined | object

Defined in types.ts:88

If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts, only script key of the data is loaded.


Optional defaultFormat

defaultFormat? : WritableFileFormat

Inherited from ManagerFromDataOptions.defaultFormat

Defined in types.ts:58

The default format to be used if file format cannot be determined from file name and content.


Optional logger

logger? : Logger

Inherited from DataFileFromDataOptions.logger

Defined in types.ts:78

Winston compatible logger to be used when logging.


Optional prettierConfig

prettierConfig? : PrettierConfig

Inherited from DataFileFromDataOptions.prettierConfig

Defined in types.ts:82

Prettier configuration to be used. If not provided determined automatically.


Optional readOnly

readOnly? : undefined | false | true

Inherited from ManagerFromDataOptions.readOnly

Defined in types.ts:62

Whether file can be saved using this library.


Optional rootDataPath

rootDataPath? : DataPath

Inherited from ManagerFromDataOptions.rootDataPath

Defined in types.ts:60

If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts, only script key of the data is loaded.


Optional rootDir

rootDir? : undefined | string

Inherited from DataFileFromDataOptions.rootDir

Defined in types.ts:80

Root directory for file. If provided, relative path is based on this root directory.


Optional saveIfChanged

saveIfChanged? : undefined | false | true

Inherited from ManagerFromDataOptions.saveIfChanged

Defined in types.ts:64

Whether to save file only if data is changed. Clones initial data deeply to check during save.

Interface: Logger

Logger

Hierarchy

  • Logger

Properties

log

log: function

Defined in types.ts:6

Type declaration:

▸ (...args: Array‹any›): any

Parameters:

NameType
...argsArray‹any›

Interface: ManagerFromDataOptions

Manager.fromData options.

Hierarchy

Properties

Optional defaultFormat

defaultFormat? : WritableFileFormat

Defined in types.ts:58

The default format to be used if file format cannot be determined from file name and content.


Optional readOnly

readOnly? : undefined | false | true

Defined in types.ts:62

Whether file can be saved using this library.


Optional rootDataPath

rootDataPath? : DataPath

Defined in types.ts:60

If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts, only script key of the data is loaded.


Optional saveIfChanged

saveIfChanged? : undefined | false | true

Defined in types.ts:64

Whether to save file only if data is changed. Clones initial data deeply to check during save.

Interface: ManagerLoadOptions

Manager.load options.

Hierarchy

Properties

Optional cosmiconfig

cosmiconfig? : boolean | object

Defined in types.ts:72

Whether to use https://www.npmjs.com/package/cosmiconfig to load configuration. Set true for default cosmiconfig options or provide an object with options for cosmiconfig options and searchFrom to provide cosmiconfig.search() parameter.


Optional defaultData

defaultData? : any

Defined in types.ts:70

The default data to be used if file does not exist.


Optional defaultFormat

defaultFormat? : WritableFileFormat

Inherited from ManagerFromDataOptions.defaultFormat

Defined in types.ts:58

The default format to be used if file format cannot be determined from file name and content.


Optional readOnly

readOnly? : undefined | false | true

Inherited from ManagerFromDataOptions.readOnly

Defined in types.ts:62

Whether file can be saved using this library.


Optional rootDataPath

rootDataPath? : DataPath

Inherited from ManagerFromDataOptions.rootDataPath

Defined in types.ts:60

If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts, only script key of the data is loaded.


Optional saveIfChanged

saveIfChanged? : undefined | false | true

Inherited from ManagerFromDataOptions.saveIfChanged

Defined in types.ts:64

Whether to save file only if data is changed. Clones initial data deeply to check during save.

1.8.0

4 years ago

1.7.6

4 years ago

1.7.5

4 years ago

1.7.4

4 years ago

1.7.3

4 years ago

1.7.2

4 years ago

1.7.1

4 years ago

1.7.0

4 years ago

1.6.2

4 years ago

1.6.1

4 years ago

1.6.0

4 years ago

1.5.0

4 years ago

1.4.13

4 years ago

1.4.12

4 years ago

1.4.11

4 years ago

1.4.10

4 years ago

1.4.9

4 years ago

1.4.8

4 years ago

1.4.6

4 years ago

1.4.7

4 years ago

1.4.5

4 years ago

1.4.4

4 years ago

1.4.3

4 years ago

1.4.2

4 years ago

1.4.1

4 years ago

1.4.0

4 years ago

1.3.13

4 years ago

1.3.12

4 years ago

1.3.11

4 years ago

1.3.7

4 years ago

1.3.6

4 years ago

1.3.5

4 years ago

1.3.4

4 years ago

1.3.3

4 years ago

1.3.10

4 years ago

1.3.9

4 years ago

1.3.8

4 years ago

1.3.2

4 years ago

1.3.1

4 years ago

1.3.0

4 years ago

1.2.4

4 years ago

1.2.3

4 years ago

1.2.2

4 years ago

1.2.0

4 years ago

1.1.1

4 years ago

1.2.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago