script-helper v0.8.9
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
{
"bin": { "my-scripts": "lib/index.js" },
"scripts": {
"postinstall": "my-scripts init",
"preuninstall": "my-scripts reset",
"test": "my-scripts test"
}
}
my-scripts/lib/index.js
#!/usr/bin/env node
const { Project, execute } = require("script-helper");
const project = new Project();
module.exports = project; // If you don't want to use execute() helper, you can access exported project via require.
// If called from directly from CLI
if (require.main === module) {
try {
const result = project.executeFromCLISync(); // Optional helper which executes scripts in 'scripts' directory, which is in same directory with this file.
} catch (e) {
console.error(e);
process.exit(1);
}
}
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
function script(project, args, s) {
// Reset previous modifications
project.reset();
// 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.
project.package.set("scripts.test", "my-scripts test").set("scripts.compile", "my-scripts compile");
// Create a .env file with default content. (Does not overwirte if it is already created or changed by user.)
project.writeFile(".env", "PASSWORD=my-super-secret-password");
// 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.createSymLink("lib/config/tsconfig.json", "tsconfig.json");
// Copy a file from your custom module to project.
// Copy: project/node_modules/my-scripts/lib/config/changelog.md -> project/CHANGELOG.md
project.copyFile("lib/config/changelog.md", "CHANGELOG.md");
}
// Function to be called must be exported under 'script' key if you use 'execute' helper.
module.exports = { script };
my-scripts/lib/scripts/reset.js
function script(project, args, s) {
// 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.reset();
}
module.exports = { script };
my-scripts/lib/scripts/build/index.js
function script(project, args, s) {
// s is ScriptKit instance, see API doc.
const subScript = project.isTypeScript ? "tsc" : "babel";
// Executes my-scripts/lib/scripts/build/tsc.js or my-scripts/lib/scripts/build/babel.js
return s.executeSubScriptSync(subScript, args);
}
module.exports = { script };
my-scripts/lib/scripts/build/tsc.js
function script(project, args, s) {
// 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.executeSync(
["serial-command-1", ["arg"]],
"serial-command-2",
someCondition ? "serial-command-3" : null,
{
my-parallel-job: ["build-doc-command", ["arg"],
my-parallel-task: "some-other-command"
builder: ["tsc", ["arg"],
},
["other-serial-command", ["arg"]],
);
}
module.exports = { script };
my-scripts/lib/scripts/test.js
process.env.BABEL_ENV = "test";
process.env.NODE_ENV = "test";
function script(project, args, s) {
const config = []; // Some default config
require("jest").run(config);
return { status: 0, exit: false };
}
module.exports = { 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)
{
"scripts": {
"test": "my-scripts test"
}
}
> 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 = new 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.deleteFile("user.txt"); // NOT deleted, because it is created by user.
project.writeFile("auto.txt", "x"); // Created and tracked. It is known this file is created by this library.
project.deleteFile("auto.txt"); // Deleted, because it is known that file was created by this library.
project.writeFile("non-tracked.txt", "x", { track: false }); // Created and tracked. It is known this file is created by this library.
project.deleteFile("non-tracked.txt"); // NOT deleted, because it is not tracked, and it is unknown created by whom.
project.deleteFile("non-tracked.txt", { force: true }); // Deleted, because `force` is in effect.
API
Classes
Functions
Typedefs
Project
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 config and script directories. Default value assumes file called from CLI resides same dir with scripts and config. |
options.cwd | string | "project root" | For Testing Working directory of project root. |
options.moduleRoot | string | "module root" | For Testing Root of the module using this library. |
options.debug | boolean | false | Turns on debug mode. |
options.logger | Logger | A looger instance such as winston. Must implement info, warn, error, verbose, silly. |
project.name : string
Kind: instance property of Project
Read only: true
project.safeName : string
Kind: instance property of Project
Read only: true
Example
const name = project.name(); // @microsoft/typescript
const safeName = project.safeName(); // microsoft-typescript
project.moduleName : string
Kind: instance property of Project
Read only: true
project.safeModuleName : string
Kind: instance property of Project
Read only: true
Example
const name = project.moduleName(); // @user/my-scripts
const safeName = project.safeModuleName(); // user-my-scripts
project.moduleRoot : string
Kind: instance property of Project
Read only: true
project.config : Object
Kind: instance property of Project
Read only: true
project.package : DataObject
Kind: instance property of Project
Read only: true
project.modulePackage : Object
Kind: instance property of Project
Read only: true
project.isCompiled : boolean
Kind: instance property of Project
Read only: true
project.isTypeScript : boolean
Kind: instance property of Project
Read only: true
project.moduleBin : string
Kind: instance property of Project
Read only: true
Example
const bin = project.moduleBin; // "my-scripts"
project.availableScripts : Array.<string>
Kind: instance property of Project
Read only: true
project.scriptsDir : string
Kind: instance property of Project
Read only: true
project.configDir : string
Kind: instance property of Project
Read only: true
project.root : string
Kind: instance property of Project
Read only: true
project.sourceRoot : string
Kind: instance property of Project
Read only: true
project.track : boolean
Kind: instance property of Project
Read only: true
project.logger : BasicLogger
Kind: instance property of Project
Read only: true
project.logLevel : string
Kind: instance property of Project
project.resolveModule(name) ⇒ string
Kind: instance method of Project
Returns: string -
Param | Type | Description |
---|---|---|
name | string | Name of the module to get root path of. |
Example
project.resolveModule("fs-extra"); // /path/to/project-module/node_modules/fs-extra
project.bin(executable) ⇒ string
Kind: instance method of Project
Returns: string -
Param | Type | Description |
---|---|---|
executable | string | Name of the executable |
project.resolveScriptsBin(options, executable, cwd) ⇒ string | undefined
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.resolveScriptsBin(); // my-scripts (executable of this libraray)
project.resolveBin(modName, options, executable, cwd) ⇒ string
Kind: instance method of Project
Returns: string -
- VError
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.resolveBin("typescript", { executable: "tsc" }); // Searches typescript module, looks `bin.tsc` in package.json and returns it's path.
project.resolveBin("tsc"); // If `tsc` is defined in PATH, returns `tsc`s path, otherwise searches "tsc" module, which returns no result and throws error.
project.resolveBin("some-cmd"); // Searches "some-cmd" module and
project.fromModuleRoot(...part) ⇒ string
Kind: instance method of Project
Returns: string -
Param | Type | Description |
---|---|---|
...part | string | Path parts to get path relative to module root. |
project.fromConfigDir(...part) ⇒ string
Kind: instance method of Project
Returns: string -
Param | Type | Description |
---|---|---|
...part | string | Path relative to config dir. |
project.fromScriptsDir(...part) ⇒ string
Kind: instance method of Project
Returns: string -
Param | Type | Description |
---|---|---|
...part | string | Path relative to scripts dir. |
project.hasAnyDep(deps, t, f) ⇒ *
Kind: instance method of Project
Returns: * -
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. |
project.envIsSet(name) ⇒ boolean
Kind: instance method of Project
Returns: boolean -
Param | Type | Description |
---|---|---|
name | string | Name of the environment variable to look for. |
project.parseEnv(name, defaultValue) ⇒ *
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. |
project.executeFromCLISync(exit) ⇒ ScriptResult | void
Kind: instance method of Project
Returns: ScriptResult | void -
- VError
Param | Type | Description |
---|---|---|
exit | boolean | Whether to exit from process. |
Example
// in my-scripts/lib/index.js
project.executeFromCLI();
// in package.json
{ "scripts": { "test": "my-scripts test" } }
// on CLI
> npm run test
> node_modules/.bin/my-scripts test
project.executeScriptFileSync(scriptFile, args) ⇒ ScriptResult | Array.<ScriptResult>
Kind: instance method of Project
Returns: ScriptResult | Array.<ScriptResult> -
- VError
Param | Type | Default | Description |
---|---|---|---|
scriptFile | string | Script file to execute in scripts directory. | |
args | Array.<string> | [] | Arguments to pass script function. |
Example
const result = executeScriptFileSync("build"); // Executes my-scripts/lib/scripts/build
project.hasScriptSync(scriptFile) ⇒ string | undefined
Kind: instance method of Project
Returns: string | undefined -
Param | Type | Description |
---|---|---|
scriptFile | string | Module file to check existence. |
project.executeSync(...executables) ⇒ ScriptResult
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.executeSync(
["serial-command-1", ["arg"]],
"serial-command-2",
someCondition ? "serial-command-3" : null,
{
my-parallel-job: ["build-doc-command", ["arg"],
my-parallel-task: "some-other-command"
builder: ["tsc", ["arg"],
},
["other-serial-command", ["arg"]],
);
project.executeWithoutExitSync(...executables) ⇒ ScriptResult
Kind: instance method of Project
Returns: ScriptResult -
Param | Type | Description |
---|---|---|
...executables | Executable | Executable or executables. |
project.getConcurrentlyArgs(scripts, options, killOthers) ⇒ Array.<string>
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) ⇒ *
Kind: instance method of Project
Returns: * -
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) ⇒ *
Kind: instance method of Project
Returns: * -
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. |
project.fromRoot(...part) ⇒ string
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 = new ResettableFile({ registryFile: "dir/registry.json" });
resettable.fromRoot("path/to/file.txt"); // dir/path/to/file.txt
project.fromSourceRoot(...part) ⇒ string
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 = new ResettableFile({ sourceRoot: "sourcedir" });
resettable.fromSourceRoot("path/to/file.txt"); // sourcedir/path/to/file.txt
project.isDataFile(projectFile) ⇒ boolean
Kind: instance method of Project
Returns: boolean -
Param | Type | Description |
---|---|---|
projectFile | string | File to check |
project.hasFileSync(projectFiles, t, f) ⇒ *
Kind: instance method of Project
Returns: * -
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. |
project.isBrokenLink(projectFile) ⇒ boolena
Kind: instance method of Project
Returns: boolena -
Param | Type | Description |
---|---|---|
projectFile | string | Project file to check. |
project.saveSync() ⇒ void
Kind: instance method of Project
Throws:
- VError
project.resetSync() ⇒ void
Kind: instance method of Project
Throws:
- VError
project.resetFileSync(projectFile) ⇒ void
Kind: instance method of Project
Throws:
- VError
Param | Type | Description |
---|---|---|
projectFile | string | File to reset |
project.getFileDetailsSync(projectFile, options) ⇒ FileDetail
Kind: instance method of Project
Returns: FileDetail -
- VError
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. |
project.getFileHashSync(projectFile) ⇒ string
Kind: instance method of Project
Returns: string -
Param | Type | Description |
---|---|---|
projectFile | string | File path of the file relative to root to calculate hash for. |
project.getDataObjectSync(projectFile, options) ⇒ DataObject
Kind: instance method of Project
Returns: DataObject -
- VError
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. (json or yaml) Default is json. |
options.createFormat | boolean | "json" | Format to serialize data in given format. (json or yaml) Default is json. |
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" |
project.createSymLinkSync(targetFile, projectFile, options) ⇒ void
Kind: instance method of Project
Throws:
- VError
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.
createSymLink(here("../../config.json"), "tsconfig.json");
project.readFileSync(projectFile, options) ⇒ *
Kind: instance method of Project
Returns: * -
- VError
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) |
project.readFileDetailedSync(projectFile, options) ⇒ Object
Kind: instance method of Project
Returns: Object -
- VError
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) |
project.writeFileSync(projectFile, data, options) ⇒ void
Kind: instance method of Project
Throws:
- VError
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. a.b.c -> Keys of c would be sorted) |
Example
project.writeFile("./some-config.json", '{"name": "my-project"}'); // Writes given data to some-config.json in project root.
project.deleteFileSync(projectFile, options) ⇒ void
Kind: instance method of Project
Throws:
- VError
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.copy("./some-config.json", "./some-config.json"); // Copies some-config.json file from module's root to project's root.
project.copyFileSync(sourceFile, projectFile, options) ⇒ void
Kind: instance method of Project
Throws:
- VError
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.copy("./some-config.json", "./some-config.json"); // Copies some-config.json file from module's root to project's root.
project.createDirSync(projectDir, options) ⇒ void
Kind: instance method of Project
Throws:
- VError
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.createDir("path/to/dir"); // Created "path", "to" and "dir" as necessary.
project.deleteDirSync(projectDir, options) ⇒ void
Kind: instance method of Project
Throws:
- VError
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
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)
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 silky, verbose, info, warn, error. |
dataObject.isChanged : boolean
Kind: instance property of DataObject
Read only: true
dataObject.data : Data
Kind: instance property of DataObject
Read only: true
dataObject.original : Data
Kind: instance property of DataObject
Read only: true
dataObject.snapshot : Data
Kind: instance property of DataObject
Read only: true
dataObject.has(props, t, f) ⇒ *
Kind: instance method of DataObject
Returns: * -
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.hasProp(["scripts.build", "scripts.build:doc"], "yes", "no");
dataObject.hasSubProp(prop, subProps, t, f) ⇒ *
Kind: instance method of DataObject
Returns: * -
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.hasSubProp("scripts", ["build", "build:doc"]);
const result2 = project.hasSubProp("address.home", ["street.name", "street.no"]);
dataObject.get(path) ⇒ *
Kind: instance method of DataObject
Returns: * -
Param | Type | Description |
---|---|---|
path | Path | Path to get data from |
dataObject.set(path, value, options) ⇒ this
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. |
dataObject.setObject(data, options) ⇒ this
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.setObject({ "a.b": 1, c: 2, d: 3 });
dataObject.remove(path, options) ⇒ this
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. |
dataObject.reset() ⇒ Array.<Operation>
Kind: instance method of DataObject
Returns: Array.<Operation> -
replaceArgumentName(args, names, newName) ⇒ 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"];
replaceArgumentName(arguments, ["--a"], "--c"); // -> ["--c", "--b"]
Options : Object
Kind: global typedef
Properties
Name | Type | Description |
---|---|---|
stdio | Array | stdio parameter to feed spawn |
encoding | string | encoding to provide to feed spawn |
Executable : string | Array.<(string|Array.<string>|SpawnOptions)>
Kind: global typedef
Example
const bin = "tsc";
const binWithArgs = ["tsc", ["--strict", "--target", "ESNext"]];
const binWithOptions = ["tsc", ["--strict", "--target", "ESNext"], { encoding: "utf-8" }];
ScriptResult : Object
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) |
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. |
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago