script-helper
Helper for creating and maintaining boilerplates, configurations and script modules for npm projects.
- Description
- Inspired
- Synopsis
- Configuration
- Highlights
- API
- Classes
- Functions
- Typedefs
- Project
- new Project([options])
- project.name :
string
- project.safeName :
string
- project.moduleName :
string
- project.safeModuleName :
string
- project.moduleRoot :
string
- project.config :
Object
- project.package :
DataObject
- project.modulePackage :
Object
- project.isCompiled :
boolean
- project.isTypeScript :
boolean
- project.moduleBin :
string
- project.availableScripts :
Array.<string>
- project.scriptsDir :
string
- project.configDir :
string
- project.root :
string
- project.sourceRoot :
string
- project.track :
boolean
- project.logger :
BasicLogger
- project.logLevel :
string
- project.resolveModule(name) ⇒
string
- project.bin(executable) ⇒
string
- project.resolveScriptsBin([options], [executable], [cwd]) ⇒
string
|undefined
- project.resolveBin(modName, [options], [executable], [cwd]) ⇒
string
- project.fromModuleRoot(...part) ⇒
string
- project.fromConfigDir(...part) ⇒
string
- project.fromScriptsDir(...part) ⇒
string
- project.hasAnyDep(deps, [t], [f]) ⇒
*
- project.envIsSet(name) ⇒
boolean
- project.parseEnv(name, defaultValue) ⇒
*
- project.executeFromCLISync(exit) ⇒
ScriptResult
|void
- project.executeScriptFileSync(scriptFile, [args]) ⇒
ScriptResult
|Array.<ScriptResult>
- project.hasScriptSync(scriptFile) ⇒
string
|undefined
- project.executeSync(...executables) ⇒
ScriptResult
- project.executeWithoutExitSync(...executables) ⇒
ScriptResult
- project.getConcurrentlyArgs(scripts, [options], [killOthers]) ⇒
Array.<string>
- project.isOptedOut(key, [t], [f]) ⇒
*
- project.isOptedIn(key, [t], [f]) ⇒
*
- project.fromRoot(...part) ⇒
string
- project.fromSourceRoot(...part) ⇒
string
- project.isDataFile(projectFile) ⇒
boolean
- project.hasFileSync(projectFiles, [t], [f]) ⇒
*
- project.isBrokenLink(projectFile) ⇒
boolena
- project.saveSync() ⇒
void
- project.resetSync() ⇒
void
- project.resetFileSync(projectFile) ⇒
void
- project.getFileDetailsSync(projectFile, options) ⇒
FileDetail
- project.getFileHashSync(projectFile) ⇒
string
- project.getDataObjectSync(projectFile, [options]) ⇒
DataObject
- project.createSymLinkSync(targetFile, projectFile, [options]) ⇒
void
- project.readFileSync(projectFile, [options]) ⇒
*
- project.readFileDetailedSync(projectFile, [options]) ⇒
Object
- project.writeFileSync(projectFile, data, [options]) ⇒
void
- project.deleteFileSync(projectFile, [options]) ⇒
void
- project.copyFileSync(sourceFile, projectFile, [options]) ⇒
void
- project.createDirSync(projectDir, [options]) ⇒
void
- project.deleteDirSync(projectDir, [options]) ⇒
void
- DataObject
- new DataObject([data], [options])
- dataObject.isChanged :
boolean
- dataObject.data :
Data
- dataObject.original :
Data
- dataObject.snapshot :
Data
- dataObject.has(props, [t], [f]) ⇒
*
- dataObject.hasSubProp(prop, subProps, [t], [f]) ⇒
*
- dataObject.get(path) ⇒
*
- dataObject.set(path, value, [options]) ⇒
this
- dataObject.setObject(data, [options]) ⇒
this
- dataObject.remove(path, [options]) ⇒
this
- dataObject.reset() ⇒
Array.<Operation>
- replaceArgumentName(args, names, newName) ⇒
Array
- Options :
Object
- Executable :
string
|Array.<(string|Array.<string>|SpawnOptions)>
- ScriptResult :
Object
- Script :
function
Description
Provides utility class and related methods to create script modules which manipulate npm projects such as create/copy/remove files, directories and data files.
Also provides reset()
method which reverses all modifications made by this module.
Script modules help to develop npm modules without config. A very good article explaining this concept is written by Kent C. Dodds which can be found here.
With script-helper
, it is very easy to cerate custom script modules.
Inspired
Inspired by kcd-scripts utility functions, thanks to Kent C. Dodds and all contributors.
Synopsis
Module Hierarchy
┏ 'project' module: npm project.
┣━━ 'my-scripts' module: Your custom scripts module to manipulate npm projects. Uses `script-helper` (this module).
┣━━━━ 'script-helper' module: This module.
Configuration
Configuration is based on cosmiconfig. See below for details.
'my-scripts' module
In examples below, it is assumed that your scripts module is named and uploaded to npm as my-scripts
. You can use name you choose.
my-scripts/package.json
my-scripts/lib/index.js
#!/usr/bin/env node const Project execute = ;const project = ;moduleexports = project; // If you don't want to use execute() helper, you can access exported project via require. // If called from directly from CLIif requiremain === module try const result = project; // Optional helper which executes scripts in 'scripts' directory, which is in same directory with this file. catch e console; process;
project.executeFromCLISync()
takes script name to execute and arguments from process.argv
and requires your script and executes it's exported script()
function, and passes 3 parameters.
project
: {@link Project} instance, to help tasks related to project module.args
: args passed from CLI.s
: {@link ScriptKit} instance, to help tasks related to script file which will be executed.
my-scripts/lib/scripts/init.js
{ // Reset previous modifications project; // Add some scripts to package.json. (Does not overwrite if target keys are already defined or changed by user.) // You can change other keys by hand. projectpackage; // Create a .env file with default content. (Does not overwirte if it is already created or changed by user.) project; // Create a symlink in project which points to a file in your custom module. // project/tsconfig.json -> project/node_modules/my-scripts/lib/config/tsconfig.json project; // Copy a file from your custom module to project. // Copy: project/node_modules/my-scripts/lib/config/changelog.md -> project/CHANGELOG.md project;} // Function to be called must be exported under 'script' key if you use 'execute' helper.moduleexports = script ;
my-scripts/lib/scripts/reset.js
{ // Reset all created files, symlinks, changed JSON and YAML entries if they are not changed by user. // All modifications are tracked in a JSON file called 'my-scripts-registry.json' // 'my-scripts' is the name of your module and file name is shaped according the name of your module. project;} moduleexports = script ;
my-scripts/lib/scripts/build/index.js
{ // s is ScriptKit instance, see API doc. const subScript = projectisTypeScript ? "tsc" : "babel"; // Executes my-scripts/lib/scripts/build/tsc.js or my-scripts/lib/scripts/build/babel.js return s;} moduleexports = script ;
my-scripts/lib/scripts/build/tsc.js
{ // Execute some commands serially and concurrently. Commands in object is executed concurrently. // In example below, `serial-command-1` is executed first, then `serial-command-2` is executed, then based on condition `serial-command-3` is executed or not, // `build-doc-command`, `some-other-command` and `tsc` is executed using `concurrently` module (Keys are names used in log). // Lastly `other-serial-command` is executed. If some command in serial tasks fails, no further command is executed and function would return. return project;} moduleexports = script ;
my-scripts/lib/scripts/test.js
processenvBABEL_ENV = "test";processenvNODE_ENV = "test"; { const config = ; // Some default config ; return status: 0 exit: false ;} moduleexports = script ;
and so on...
npm project module
package.json
Instead of adding scripts below manually, you can create an init script and add it to postinstall
(see init example above)
> npm test
or
> node_modules/.bin/my-scripts test
Configuration
Your scripts module (i.e. my-scripts
) has builtin cosmiconfig support. If user puts a cosmiconfig compatibale configuration in npm project,
you can access configration via project.config()
method in your script functions.
If script module contains user names such as @microsoft/typescript
, cosmiconfig name is converted to dashed version: microsoft-typescript
.
By default you can design your own configuration schema. script-helper
provides some defaults and related methods, as described below:
Key | Type | Method | Description |
---|---|---|---|
optIn |
Array.<string> |
project.isOptedIn() |
Lists opted in options. |
optOut |
Array.<string> |
project.isOptedOut() |
Lists opted out options. |
Highlights
- Tries best for non-destructive modifications.
- Tracks all modifications in a registry json file.
- Provides
project.reset()
method to reset all changes made by this module. - Changes in JSON and YAML files are tracked by key level using resettable.
- User created keys and values would not be deleted/modified if
{ force: true }
ıs not used. - User can further modify data files. They do not interfere with this module's targets.
- CAVEAT: resettable cannot handle all cases, please see it's documentation and always use version control.
- User created keys and values would not be deleted/modified if
- Changes in non data files are tracked using SHA-1 hash.
- JSON, YAML and JavaScript files are normalized in memory before comparison to eliminate white-space noise.
- Provides
execute()
helper function to execute your scripts and handle errors and saving project data files and registry. - Provides
project.save()
method for saving registry json file and changes made to data files.
Notes
- For tracking data files by key level, use
project.readDataFile()
method, which returns DataObject- Methods of DataObject such as
set()
,remove()
provides automatic log messages. - You can directly access data using
.data
property. - Tracking still works if you manipulate data from
.data
directly, because modifications are calculated during file save.
- Methods of DataObject such as
- All data files read with
project.readDataFile()
are saved during project save (project.save()
).- Do not use
project.writeFile()
for those files.
- Do not use
- If user modifies file or data created by this library, they are not modified further if not forced with
{ force: true }
option. - DO NOT forget
project.save()
after you finish your modifications.- Or use
execute()
helper function, which saves project even after error in your scripts, and handleprocess.exit()
as necessary.
- Or use
reset()
method does not recreate deleted files and directories.
Disable Tracking
To completely disable tracking, set track
to false
in constructor:
const project = track: false ;
Tracking may be enabled/disabled per operation:
project.writeFile("some.txt", "content", { track: false });
Please note that disabling tracking does not permit automatically modifying user created files / content.
force
option is still needed to overwrite. However non-tracked modifications are treated like user created content.
For example:
// Assume user.txt is created manually by user beforehand.project; // NOT deleted, because it is created by user.project; // Created and tracked. It is known this file is created by this library.project; // Deleted, because it is known that file was created by this library.project; // Created and tracked. It is known this file is created by this library.project; // NOT deleted, because it is not tracked, and it is unknown created by whom.project; // Deleted, because `force` is in effect.
API
Classes
- Project
Provides utility class and related methods to create modules which manipulate npm projects such as create/copy/remove files, directories and data files. Also provides
reset()
method which reverses all modifications made by this module.- DataObject
This class is used for modifications of the given object.
Functions
- replaceArgumentName(args, names, newName) ⇒
Array
Returns a new array, after replacing output destination argument name with a new name. Does not mutate original array.
Typedefs
- Options :
Object
to provide spawn method.
- Executable :
string
|Array.<(string|Array.<string>|SpawnOptions)>
Type for holding executable. It may be string to store executable name without arguments. For executable with arguments or options it is a tuple
[bin-name, [arg1, arg2, arg3], spawn-options]
- ScriptResult :
Object
Type for returned value from CLI command.
- Script :
function
Type for script function.
Project
Provides utility class and related methods to create modules which manipulate npm projects such as create/copy/remove files, directories and data files.
Also provides reset()
method which reverses all modifications made by this module.
Kind: global class
- Project
- new Project([options])
- .name :
string
- .safeName :
string
- .moduleName :
string
- .safeModuleName :
string
- .moduleRoot :
string
- .config :
Object
- .package :
DataObject
- .modulePackage :
Object
- .isCompiled :
boolean
- .isTypeScript :
boolean
- .moduleBin :
string
- .availableScripts :
Array.<string>
- .scriptsDir :
string
- .configDir :
string
- .root :
string
- .sourceRoot :
string
- .track :
boolean
- .logger :
BasicLogger
- .logLevel :
string
- .resolveModule(name) ⇒
string
- .bin(executable) ⇒
string
- .resolveScriptsBin([options], [executable], [cwd]) ⇒
string
|undefined
- .resolveBin(modName, [options], [executable], [cwd]) ⇒
string
- .fromModuleRoot(...part) ⇒
string
- .fromConfigDir(...part) ⇒
string
- .fromScriptsDir(...part) ⇒
string
- .hasAnyDep(deps, [t], [f]) ⇒
*
- .envIsSet(name) ⇒
boolean
- .parseEnv(name, defaultValue) ⇒
*
- .executeFromCLISync(exit) ⇒
ScriptResult
|void
- .executeScriptFileSync(scriptFile, [args]) ⇒
ScriptResult
|Array.<ScriptResult>
- .hasScriptSync(scriptFile) ⇒
string
|undefined
- .executeSync(...executables) ⇒
ScriptResult
- .executeWithoutExitSync(...executables) ⇒
ScriptResult
- .getConcurrentlyArgs(scripts, [options], [killOthers]) ⇒
Array.<string>
- .isOptedOut(key, [t], [f]) ⇒
*
- .isOptedIn(key, [t], [f]) ⇒
*
- .fromRoot(...part) ⇒
string
- .fromSourceRoot(...part) ⇒
string
- .isDataFile(projectFile) ⇒
boolean
- .hasFileSync(projectFiles, [t], [f]) ⇒
*
- .isBrokenLink(projectFile) ⇒
boolena
- .saveSync() ⇒
void
- .resetSync() ⇒
void
- .resetFileSync(projectFile) ⇒
void
- .getFileDetailsSync(projectFile, options) ⇒
FileDetail
- .getFileHashSync(projectFile) ⇒
string
- .getDataObjectSync(projectFile, [options]) ⇒
DataObject
- .createSymLinkSync(targetFile, projectFile, [options]) ⇒
void
- .readFileSync(projectFile, [options]) ⇒
*
- .readFileDetailedSync(projectFile, [options]) ⇒
Object
- .writeFileSync(projectFile, data, [options]) ⇒
void
- .deleteFileSync(projectFile, [options]) ⇒
void
- .copyFileSync(sourceFile, projectFile, [options]) ⇒
void
- .createDirSync(projectDir, [options]) ⇒
void
- .deleteDirSync(projectDir, [options]) ⇒
void
new Project([options])
Param | Type | Default | Description |
---|---|---|---|
[options] | Object |
Options |
|
[options.track] | boolean |
Sets default tracking option for methods. |
|
[options.sortPackageKeys] | Array.<string> |
["scripts"] |
Default keys to be sorted in package.json file. |
[options.logLevel] | LogLevel |
"info" |
Sets log level. ("error", "warn", "info", "debug", "verbose", "silly") |
[options.filesDir] | boolean |
require.main.filename |
Directory of |
[options.cwd] | string |
"[project root]" |
[ |
[options.moduleRoot] | string |
"[module root]" |
[ |
[options.debug] | boolean |
false |
Turns on debug mode. |
[options.logger] | Logger |
A looger instance such as winston. Must implement |
string
project.name : Project name which uses scripts module.
Kind: instance property of Project
Read only: true
string
project.safeName : Safe project name, which "@" and "/" characters names are replaced.
Kind: instance property of Project
Read only: true
Example
const name = projectname; // @microsoft/typescriptconst safeName = project; // microsoft-typescript
string
project.moduleName : Module name which provides configuration services to project using this library.
Kind: instance property of Project
Read only: true
string
project.safeModuleName : Safe module name, which "@" and "/" characters names are replaced.
Kind: instance property of Project
Read only: true
Example
const name = project; // @user/my-scriptsconst safeName = project; // user-my-scripts
string
project.moduleRoot : Root directory path of module which provides configuration services to project using this library.
Kind: instance property of Project
Read only: true
Object
project.config : Configuration for module.
Kind: instance property of Project
Read only: true
DataObject
project.package : [DataObject](#DataObject) instance for package.json
of project. Also this is a shorthand for project.readDataFile("package.json")
Kind: instance property of Project
Read only: true
Object
project.modulePackage : Object of script module's package.json
data. This data is read only and it's keys/values should not be changed.
Kind: instance property of Project
Read only: true
boolean
project.isCompiled : Whether project is a compiled project via TypeScript or Babel.
Kind: instance property of Project
Read only: true
boolean
project.isTypeScript : Whether project is a TypeScript project.
Kind: instance property of Project
Read only: true
string
project.moduleBin : Command name of the module's bin. (It is simply it's bin (string) or first key of it's bin (object) in package.json) For more complex requirements, it is possible to use [Project.modulePackage](Project.modulePackage) and do manual calculations.
Kind: instance property of Project
Read only: true
Example
const bin = projectmoduleBin; // "my-scripts"
Array.<string>
project.availableScripts : Lists of available scripts in scripts folder.
Kind: instance property of Project
Read only: true
string
project.scriptsDir : Path of the scripts dir.
Kind: instance property of Project
Read only: true
string
project.configDir : Path of the config dir.
Kind: instance property of Project
Read only: true
string
project.root : Root path for files to be managed. It is the directory registry file is located.
Kind: instance property of Project
Read only: true
string
project.sourceRoot : Source root path for files to be managed. It is the source root directory given during object construction.
Kind: instance property of Project
Read only: true
boolean
project.track : Whether files of the project are tracked by default.
Kind: instance property of Project
Read only: true
BasicLogger
project.logger : Returns logger object which provides error
, warn
, info
, debug
, verbose
, silly
methods.
Kind: instance property of Project
Read only: true
string
project.logLevel : Log level if default logger is used. ("none", "error", "warn", "info", "debug", "verbose", "silly")
Kind: instance property of Project
string
project.resolveModule(name) ⇒ Returns root path of given module.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
name | string |
Name of the module to get root path of. |
Example
project; // /path/to/project-module/node_modules/fs-extra
string
project.bin(executable) ⇒ Returns relative path to given executable located in project's node_modules/.bin
.
Kind: instance method of Project
Returns: string
-
node_modules/.bim
Param | Type | Description |
---|---|---|
executable | string |
Name of the executable |
string
| undefined
project.resolveScriptsBin([options], [executable], [cwd]) ⇒ Finds and returns path to module's binary. (Module which requires this library)
Kind: instance method of Project
Returns: string
| undefined
-
Param | Type | Default | Description |
---|---|---|---|
[options] | Object |
Options. |
|
[executable] | string |
Executable name. |
|
[cwd] | string |
"process.cwd()" |
Current working directory |
Example
project; // my-scripts (executable of this libraray)
string
project.resolveBin(modName, [options], [executable], [cwd]) ⇒ Finds and returns path of given command, trying to following steps:
- If it is a command defined in path, returns it's path.
- Searches if given node module is installed.
2.a. If executable is given, looks
bin[executable]
in module's package.json. 2.b. If no executable is given, looksbin[module name]
in module's package.json. 2.c. If found returns it's path. - Throws error. module name is used by default.
Kind: instance method of Project
Returns: string
-
VError
- Throws error no binary cannot be found.
Param | Type | Default | Description |
---|---|---|---|
modName | string |
Module name to find executable from. |
|
[options] | Object |
Options. |
|
[executable] | string |
"param.modName" |
Executable name. (Defaults to module name) |
[cwd] | string |
"process.cwd()" |
Current working directory |
Example
project; // Searches typescript module, looks `bin.tsc` in package.json and returns it's path.project; // If `tsc` is defined in PATH, returns `tsc`s path, otherwise searches "tsc" module, which returns no result and throws error.project; // Searches "some-cmd" module and
string
project.fromModuleRoot(...part) ⇒ Joins parts to form a path using path.join
. Returns path in module by adding module root at the beginning of path.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
...part | string |
Path parts to get path relative to module root. |
string
project.fromConfigDir(...part) ⇒ Returns given path added to path of config directory. Path may be given as a single string or in multiple parts.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
...part | string |
Path relative to config dir. |
string
project.fromScriptsDir(...part) ⇒ Returns given path added to path of scripts directory. Path may be given as a single string or in multiple parts.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
...part | string |
Path relative to scripts dir. |
*
project.hasAnyDep(deps, [t], [f]) ⇒ Returns one of the given values based on whether project has any of the given dependencies in dependencies
, devDependencies
, peerDependencies
.
Kind: instance method of Project
Returns: *
-
t
or f
value based on existence of dependency in package.json.Param | Type | Default | Description |
---|---|---|---|
deps | string | Array.<string> |
Dependency or dependencies to check. |
|
[t] | * |
true |
Value to return if any of dependencies exists. |
[f] | * |
false |
Value to return if none of dependencies exists. |
boolean
project.envIsSet(name) ⇒ Returns whether given environment variable is set and not empty.
Kind: instance method of Project
Returns: boolean
-
Param | Type | Description |
---|---|---|
name | string |
Name of the environment variable to look for. |
*
project.parseEnv(name, defaultValue) ⇒ Returns environment variable if it exists and is not empty. Returns given default value otherwise.
Kind: instance method of Project
Returns: *
-
Param | Type | Description |
---|---|---|
name | string |
Name of the environment variable |
defaultValue | * |
Default value to return if no environment variable is set or is empty. |
ScriptResult
| void
project.executeFromCLISync(exit) ⇒ Executes script based on script name from CLI (process.argv). If exit
is true and there is no exit: false
in script result objects,
also exist from process with success (0) or failure code (1).
Kind: instance method of Project
Returns: ScriptResult
| void
-
VError
- Throws error if script throws error.
Param | Type | Description |
---|---|---|
exit | boolean |
Whether to exit from process. |
Example
// in my-scripts/lib/index.jsproject; // in package.json "scripts": "test": "my-scripts test" // on CLI> npm run test> node_modules/bin/my-scripts test
ScriptResult
| Array.<ScriptResult>
project.executeScriptFileSync(scriptFile, [args]) ⇒ Executes given script file's exported script
function. Script file should be given relative to scripts directory.
Kind: instance method of Project
Returns: ScriptResult
| Array.<ScriptResult>
-
VError
- Throws if given file does not export a function in script property.
Param | Type | Default | Description |
---|---|---|---|
scriptFile | string |
Script file to execute in scripts directory. |
|
[args] | Array.<string> |
[] |
Arguments to pass script function. |
Example
const result = ; // Executes my-scripts/lib/scripts/build
string
| undefined
project.hasScriptSync(scriptFile) ⇒ Checks whether given script exists in scripts directory. Script search method is as below:
- If given path found (dir or file), returns it.
- If file name has no extension, looks a file name with extension in order of
ts
,js
. - If file name with an extension is found, returns full path of filename including extension.
Kind: instance method of Project
Returns: string
| undefined
-
Param | Type | Description |
---|---|---|
scriptFile | string |
Module file to check existence. |
ScriptResult
project.executeSync(...executables) ⇒ Executes given binary using spawn.sync
with given arguments and return results.
For single [Executable](#Executable), it executes and returns result. For multiple [Executables](#Executable), it executes them
serially. Execution stops and function returns result, if one of the commands fails (also adds previous results in result.previousResults
).
If an object is provided with names as keys and [Executables](#Executable) as values, it executes them using concurrently
and returns result of concurrently
.
Kind: instance method of Project
Returns: ScriptResult
-
Param | Type | Description |
---|---|---|
...executables | Executable |
Executable or executables. |
Example
// Execute some commands serially and concurrently. Commands in object is executed concurrently.// In example below, `serial-command-1` is executed first, then `serial-command-2` is executed, then based on condition `serial-command-3` is executed or not,// `build-doc-command`, `some-other-command` and `tsc` is executed using `concurrently` module (Keys are names used in log).// Lastly `other-serial-command` is executed. If some command in serial tasks fails, no further command is executed and function would return.const result = project;
ScriptResult
project.executeWithoutExitSync(...executables) ⇒ Same as Project.executeSync()
, but adds exit: false
to the result.
Kind: instance method of Project
Returns: ScriptResult
-
Param | Type | Description |
---|---|---|
...executables | Executable |
Executable or executables. |
Array.<string>
project.getConcurrentlyArgs(scripts, [options], [killOthers]) ⇒ Given an object containing keys as script names, values as commands, returns parameters to feed to concurrently.
Kind: instance method of Project
Returns: Array.<string>
-
Param | Type | Default | Description |
---|---|---|---|
scripts | Object.<string, string> |
Object with script names as keys, commands as values. |
|
[options] | Object |
Options |
|
[killOthers] | boolean |
true |
Whether -kill-others-on-fail should added. |
*
project.isOptedOut(key, [t], [f]) ⇒ Returns whether given parameter is opted out by looking configuration.
Kind: instance method of Project
Returns: *
-
t
or f
value based on existence of sub property.Param | Type | Default | Description |
---|---|---|---|
key | string |
Paremeter to look for. |
|
[t] | * |
true |
Value to return if it is opted out. |
[f] | * |
false |
Value to return if it is not opted out. |
*
project.isOptedIn(key, [t], [f]) ⇒ Returns whether given parameter is opted in by looking configuration.
Kind: instance method of Project
Returns: *
-
t
or f
value based on existence of sub property.Param | Type | Default | Description |
---|---|---|---|
key | string |
Paremeter to look for. |
|
[t] | * |
true |
Value to return if it is opted in. |
[f] | * |
false |
Value to return if it is not opted in. |
string
project.fromRoot(...part) ⇒ Returns given path after prepending it to the root. Path may be given as a single string or in multiple parts.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
...part | string |
Path or path parts to get full path in root. |
Example
const resettable = registryFile: "dir/registry.json" ;resettable; // dir/path/to/file.txt
string
project.fromSourceRoot(...part) ⇒ Returns given path after prepending it to the source root. Path may be given as a single string or in multiple parts.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
...part | string |
Path or path parts to get full path in root. |
Example
const resettable = sourceRoot: "sourcedir" ;resettable; // sourcedir/path/to/file.txt
boolean
project.isDataFile(projectFile) ⇒ Checks whether given file is a tracked data file.
Kind: instance method of Project
Returns: boolean
-
Param | Type | Description |
---|---|---|
projectFile | string |
File to check |
*
project.hasFileSync(projectFiles, [t], [f]) ⇒ Returns one of the given values based on existence of given file path or file paths in root.
Returns true for broken links. (Links which points to non-existing paths, which fs.existsSync()
returns false)
Kind: instance method of Project
Returns: *
-
t
or f
value based on existence of files in root.Param | Type | Default | Description |
---|---|---|---|
projectFiles | string | Array.<string> |
File or list of files to look in root. |
|
[t] | * |
true |
Value to return if any of the files exists in root. |
[f] | * |
false |
Value to return if none of the files exists in root. |
boolena
project.isBrokenLink(projectFile) ⇒ Returns whether given project file is a broken link. (Links which points to non-existing paths)
Kind: instance method of Project
Returns: boolena
-
Param | Type | Description |
---|---|---|
projectFile | string |
Project file to check. |
void
project.saveSync() ⇒ Saves data files and registry file. Must be called if any changes are made.
Kind: instance method of Project
Throws:
VError
- Throws error if files cannot be written
void
project.resetSync() ⇒ Resets modifications made by this library by deleting created files and returns data files in original state. WARNING: Does not recreate deleted files.
Kind: instance method of Project
Throws:
VError
- Throws error if files cannot be written
void
project.resetFileSync(projectFile) ⇒ Resets given file.
Kind: instance method of Project
Throws:
VError
- Throws error if file cannot be reset.
Param | Type | Description |
---|---|---|
projectFile | string |
File to reset |
FileDetail
project.getFileDetailsSync(projectFile, options) ⇒ Returns file details related to given file path relative to root.
Kind: instance method of Project
Returns: FileDetail
-
VError
- Throws error if file details cannot be get.
Param | Type | Description |
---|---|---|
projectFile | string |
File to get detail for. |
options | Object |
Options |
options.force | boolean |
Assume safe to operate on file even it is not auto created. |
options.track | boolean |
Whether to track file if it is created by module. |
string
project.getFileHashSync(projectFile) ⇒ Calculates and returns hash for given file relative to root. For js, json and yaml files, ignores format differences and returns same hash for same data even they are formatted differently.
Kind: instance method of Project
Returns: string
-
Param | Type | Description |
---|---|---|
projectFile | string |
File path of the file relative to root to calculate hash for. |
DataObject
project.getDataObjectSync(projectFile, [options]) ⇒ Reads json or yaml data file and returns [DataObject](#DataObject) instance. Records changes made to object and writes them to registry file to be cleared when necessary.
Changes made are saved to same file when project is saved via save()
method.
Kind: instance method of Project
Returns: DataObject
-
VError
- Throws error if file cannot be created.
Param | Type | Default | Description |
---|---|---|---|
projectFile | string |
File path to read relative to root. |
|
[options] | Object |
Options |
|
[options.create] | boolean |
false |
Whether to create file if it does not exist. |
[options.defaultContent] | Object |
Default content to write if file is created. |
|
[options.throwNotExists] | boolean |
true |
Throw error if file does not exist. |
[options.format] | boolean |
[file extension] |
Format to serialize data in given format. ( |
[options.createFormat] | boolean |
"json" |
Format to serialize data in given format. ( |
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
[options.force] | boolean |
false |
Whether to force write file even it exist. |
[options.sortKeys] | Array.<string> |
List of keys which their values shoud be sorted. Key names be paths like "scripts.test" |
void
project.createSymLinkSync(targetFile, projectFile, [options]) ⇒ Creates a symbolic link in project which points to a file in module. Removes previously created symbolic link created by this library.
Kind: instance method of Project
Throws:
VError
- Throws error if symbolic link cannot be created.
Param | Type | Default | Description |
---|---|---|---|
targetFile | string |
Target file which link points to. Should be given relative to module root. |
|
projectFile | string |
Link file. Should be given relative to project root. |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Writes file even it exists and not auto created. |
[options.track] | boolean |
[this.track] |
Whether to track symlink if it is created by module. |
Example
// Creates tsconfig.json symbolic link file in project root, pointing to a file from toolkit.;
*
project.readFileSync(projectFile, [options]) ⇒ Reads and returns content of the given file relative to root. Optionally can create file if it does not exist.
Kind: instance method of Project
Returns: *
-
VError
- Throws error if file cannot be found.
Param | Type | Default | Description |
---|---|---|---|
projectFile | string |
File to read relative to root. |
|
[options] | Object |
Options |
|
[options.create] | boolean |
false |
Whether to create file if it does not exist. |
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
[options.force] | boolean |
false |
Whether to force create even it is deleted by user. |
[options.defaultContent] | * |
Default content to write if file does not exist. |
|
[options.throwNotExists] | boolean |
true |
Throw error if file does not exist. |
[options.parse] | boolean |
false |
Whether to parse file content to create a js object. |
[options.format] | Format |
[file extension] |
Format to use parsing data. |
[options.createFormat] | Format |
json |
Format to be used while creating nonexisting file if no format is provided. |
[options.serialize] | Format |
[parse] |
Whether to serialize content if file is created. (Default is status of parse option) |
Object
project.readFileDetailedSync(projectFile, [options]) ⇒ Reads and returns content and format of the given file relative to project root. Optionally can create file if it does not exist.
Kind: instance method of Project
Returns: Object
-
VError
- Throws error if file cannot be found.
Param | Type | Default | Description |
---|---|---|---|
projectFile | string |
File to read relative to project root. |
|
[options] | Object |
Options |
|
[options.create] | boolean |
false |
Whether to create file if it does not exist. |
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
[options.force] | boolean |
false |
Whether to force create even it is deleted by user. |
[options.defaultContent] | * |
Default content to write if file does not exist. |
|
[options.throwNotExists] | boolean |
true |
Throw error if file does not exist. |
[options.parse] | boolean |
false |
Whether to parse file content to create a js object. |
[options.format] | Format |
[file extension] |
Format to use parsing data. |
[options.createFormat] | Format |
json |
Format to be used while creating nonexisting file if no format is provided. |
[options.serialize] | Format |
[parse] |
Whether to serialize content if file is created. (Default is status of parse option) |
void
project.writeFileSync(projectFile, data, [options]) ⇒ Creates and writes given data to a file in project.
Kind: instance method of Project
Throws:
VError
- Throws error if file cannot be created
Param | Type | Default | Description |
---|---|---|---|
projectFile | string |
File path to relative to project root. |
|
data | string |
Data to write |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Writes file even it exists and not auto created. |
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
[options.serialize] | boolean |
false |
Whether to serialize object before written to file. |
[options.format] | Format |
[file extension] |
Format to use serializing data. |
[options.sortKeys] | Array |
Keys to be sorted. Keys may be given as chained paths. (i.e. |
Example
project; // Writes given data to some-config.json in project root.
void
project.deleteFileSync(projectFile, [options]) ⇒ Deletes a file from project. Path should be given relative to project root.
Kind: instance method of Project
Throws:
VError
- Throws error if file cannot be deleted.
Param | Type | Default | Description |
---|---|---|---|
projectFile | string |
File path relative to paroject root. |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Deletes file even it exists and not auto created. |
[options.track] | boolean |
[this.track] |
Whether to operate in tracked mode. In non-tracked mode existing files are not deleted if force is not active. |
[options.log] | boolean |
true |
Whether to log operation. |
[options.brokenLink] | boolean |
false |
Whether project file is a broken link. Broken links are treated as if they do not exist. |
Example
project; // Copies some-config.json file from module's root to project's root.
void
project.copyFileSync(sourceFile, projectFile, [options]) ⇒ Copies a file from module to project. Paths should be given relative to module root and project root.
Kind: instance method of Project
Throws:
VError
- Throws error if file cannot be created
Param | Type | Default | Description |
---|---|---|---|
sourceFile | string |
Source file path. |
|
projectFile | string |
Destinantion file path relative to paroject root. |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Overwrites file even it exists and not auto created. |
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
Example
project; // Copies some-config.json file from module's root to project's root.
void
project.createDirSync(projectDir, [options]) ⇒ Creates given directory and its tree relative to project root.
Kind: instance method of Project
Throws:
VError
- Throws error if directory tree cannot be created.
Param | Type | Default | Description |
---|---|---|---|
projectDir | string |
Directory path to relative to project root. |
|
[options] | Object |
Options |
|
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
[options.logDirs] | boolean |
true |
Whether to log delete operation of sub directories. |
Example
project; // Created "path", "to" and "dir" as necessary.
void
project.deleteDirSync(projectDir, [options]) ⇒ Deletes directory if empty or all of it's contents are created by this library. force
option may be used to delete non-empty directories.
Kind: instance method of Project
Throws:
VError
- Throws error if directory or its content cannot be deleted.
Param | Type | Default | Description |
---|---|---|---|
projectDir | string |
Destinantion directory to delete. |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Deletes directory and it's contents even it is not empty. |
[options.track] | boolean |
[this.track] |
Whether to track file in registry if it is created by module. |
[options.logFiles] | boolean |
true |
Whether to log delete operation of files. |
[options.logDirs] | boolean |
true |
Whether to log delete operation of sub directories. |
DataObject
This class is used for modifications of the given object.
Kind: global class
- DataObject
- new DataObject([data], [options])
- .isChanged :
boolean
- .data :
Data
- .original :
Data
- .snapshot :
Data
- .has(props, [t], [f]) ⇒
*
- .hasSubProp(prop, subProps, [t], [f]) ⇒
*
- .get(path) ⇒
*
- .set(path, value, [options]) ⇒
this
- .setObject(data, [options]) ⇒
this
- .remove(path, [options]) ⇒
this
- .reset() ⇒
Array.<Operation>
new DataObject([data], [options])
Creates an instance of DataObject.
Param | Type | Default | Description |
---|---|---|---|
[data] | Object |
{} |
Data to be modified. |
[options] | Object |
Options |
|
[options.track] | boolean |
Whether to track changes. |
|
[options.sortKeys] | Array.<string> |
List of keys which their values shoud be sorted. Key names be paths like "scripts.test" |
|
[options.name] | string |
Path of the name to be used in logs. |
|
[options.format] | Format |
Data format used for parsing and serializing data. |
|
[options.operations] | Array.<Operation> |
Operations to reset data to its original state. |
|
[options.logger] | Logger |
A looger instance such as winston. Must implement |
boolean
dataObject.isChanged : Whether data is changed.
Kind: instance property of DataObject
Read only: true
Data
dataObject.data : Stored data.
Kind: instance property of DataObject
Read only: true
Data
dataObject.original : Original state of the data after operations applied to reset into its original state.
Kind: instance property of DataObject
Read only: true
Data
dataObject.snapshot : Data in the state given to constructor
Kind: instance property of DataObject
Read only: true
*
dataObject.has(props, [t], [f]) ⇒ Returns one of the given values based on whether some of given property or properties exists in given object.
Property names may be given as chained such as key
or key.subkey
.
Kind: instance method of DataObject
Returns: *
-
t
or f
value based on existence of property.Param | Type | Default | Description |
---|---|---|---|
props | string | Array.<Path> |
Property or properties to look in data |
|
[t] | * |
true |
Value to return if some of the properties exists in project. |
[f] | * |
false |
Value to return if none of the properties exists in project. |
Example
const result = project;
*
dataObject.hasSubProp(prop, subProps, [t], [f]) ⇒ Returns one of the given values based on whether some of given property path or property paths exists in object's target property path.
Property names may be given as chained such as key
or key.subkey
.
Kind: instance method of DataObject
Returns: *
-
t
or f
value based on existence of sub property.Param | Type | Default | Description |
---|---|---|---|
prop | Path |
Property or properties to look in data |
|
subProps | string | Array.<Path> |
Property or properties to look in data |
|
[t] | * |
true |
Value to return if some of the properties exists. |
[f] | * |
false |
Value to return if none of the properties exists. |
Example
const result = project;const result2 = project;
*
dataObject.get(path) ⇒ Returns data in given key or path. Path may be given as chained. (i.e "scripts.compile")
Kind: instance method of DataObject
Returns: *
-
Param | Type | Description |
---|---|---|
path | Path |
Path to get data from |
this
dataObject.set(path, value, [options]) ⇒ Stores given data at given key or path. Based on force option, does not change value if it is not created automatically by this library by looking registry. Path may be given as chained. (i.e "scripts.compile")
Kind: instance method of DataObject
Returns: this
-
Param | Type | Default | Description |
---|---|---|---|
path | Path |
Path to store data at. |
|
value | * |
Value to store at given key. |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Whether to force change even value is altered by user manually. |
this
dataObject.setObject(data, [options]) ⇒ Stores each key and its value in the object. Key's may be given as chained paths such as scripts.compile
.
Kind: instance method of DataObject
Returns: this
-
Param | Type | Default | Description |
---|---|---|---|
data | Object |
Data to store at object. |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Whether to force change even value is altered by user manually. |
Example
data;
this
dataObject.remove(path, [options]) ⇒ Removes given path or paths from object . Based on force option, does not remove value if it is not created automatically by this library by looking registry. Path may be given as chained. (i.e "scripts.compile")
Kind: instance method of DataObject
Returns: this
-
Param | Type | Default | Description |
---|---|---|---|
path | string | Array.<Path> |
Path or list of paths to remove |
|
[options] | Object |
Options |
|
[options.force] | boolean |
false |
Whether to force change even value is altered by user manually. |
Array.<Operation>
dataObject.reset() ⇒ Resets data and snapshot to its original states.
Kind: instance method of DataObject
Returns: Array.<Operation>
-
Array
replaceArgumentName(args, names, newName) ⇒ Returns a new array, after replacing output destination argument name with a new name. Does not mutate original array.
Kind: global function
Returns: Array
-
Param | Type | Description |
---|---|---|
args | Array |
Arguments array. |
names | string | Array.<string> |
Parameter names to look for in arguments. |
newName | string |
Parameter names to look for in arguments. |
Example
const arguments = "--a" "--b";; // -> ["--c", "--b"]
Object
Options : to provide spawn method.
Kind: global typedef
Properties
Name | Type | Description |
---|---|---|
stdio | Array |
stdio parameter to feed spawn |
encoding | string |
encoding to provide to feed spawn |
string
| Array.<(string|Array.<string>|SpawnOptions)>
Executable : Type for holding executable. It may be string to store executable name without arguments. For executable
with arguments or options it is a tuple [bin-name, [arg1, arg2, arg3], spawn-options]
Kind: global typedef
Example
const bin = "tsc";const binWithArgs = "tsc" "--strict" "--target" "ESNext";const binWithOptions = "tsc" "--strict" "--target" "ESNext" encoding: "utf-8" ;
Object
ScriptResult : Type for returned value from CLI command.
Kind: global typedef
Properties
Name | Type | Description |
---|---|---|
status | number |
Exit status code of cli command (0: success, other value: error) |
[error] | Error |
Error object if execution of cli command fails. |
[previousResults] | Array.<ScriptResult> |
If more than one command is executed serially, results of prevoulsy executed commands. |
[exit] | boolean |
Whether script should exit after finishes its job. (Default behaviour is exit/true) |
function
Script : Type for script function.
Kind: global typedef
Param | Type | Description |
---|---|---|
project | Project |
Project instance. |
args | Array.<string> |
Argument. |
scriptKit | ScriptKit |
ScriptKit instance, which have utility methods fro currently executed script file. |