script-helper
TypeScript icon, indicating that this package has built-in type declarations

0.8.9 • Public • Published

script-helper

Helper for creating and maintaining boilerplates, configurations and script modules for npm projects.

Commitizen friendly

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.

  1. project: {@link Project} instance, to help tasks related to project module.
  2. args: args passed from CLI.
  3. 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.
  • 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.
  • All data files read with project.readDataFile() are saved during project save (project.save()).
    • Do not use project.writeFile() for those files.
  • 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 handle process.exit() as necessary.
  • reset() method does not recreate deleted files and directories.

Disable Tracking

To completely disable tracking, set track to falsein 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

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

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

Project name which uses scripts module.

Kind: instance property of Project
Read only: true

project.safeName : string

Safe project name, which "@" and "/" characters names are replaced.

Kind: instance property of Project
Read only: true
Example

const name = project.name(); // @microsoft/typescript
const safeName = project.safeName(); // microsoft-typescript

project.moduleName : string

Module name which provides configuration services to project using this library.

Kind: instance property of Project
Read only: true

project.safeModuleName : string

Safe module name, which "@" and "/" characters names are replaced.

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

Root directory path of module which provides configuration services to project using this library.

Kind: instance property of Project
Read only: true

project.config : Object

Configuration for module.

Kind: instance property of Project
Read only: true

project.package : DataObject

[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

project.modulePackage : Object

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

project.isCompiled : boolean

Whether project is a compiled project via TypeScript or Babel.

Kind: instance property of Project
Read only: true

project.isTypeScript : boolean

Whether project is a TypeScript project.

Kind: instance property of Project
Read only: true

project.moduleBin : string

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 = project.moduleBin; // "my-scripts"

project.availableScripts : Array.<string>

Lists of available scripts in scripts folder.

Kind: instance property of Project
Read only: true

project.scriptsDir : string

Path of the scripts dir.

Kind: instance property of Project
Read only: true

project.configDir : string

Path of the config dir.

Kind: instance property of Project
Read only: true

project.root : string

Root path for files to be managed. It is the directory registry file is located.

Kind: instance property of Project
Read only: true

project.sourceRoot : string

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

project.track : boolean

Whether files of the project are tracked by default.

Kind: instance property of Project
Read only: true

project.logger : BasicLogger

Returns logger object which provides error, warn, info, debug, verbose, silly methods.

Kind: instance property of Project
Read only: true

project.logLevel : string

Log level if default logger is used. ("none", "error", "warn", "info", "debug", "verbose", "silly")

Kind: instance property of Project

project.resolveModule(name) ⇒ string

Returns root path of given module.

Kind: instance method of Project
Returns: string -

  • Root path of given module.
  • 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

    Returns relative path to given executable located in project's node_modules/.bin.

    Kind: instance method of Project
    Returns: string -

    • Path of the executable in node_modules/.bim
    • Param Type Description
      executable string

      Name of the executable

      project.resolveScriptsBin([options], [executable], [cwd]) ⇒ string | undefined

      Finds and returns path to module's binary. (Module which requires this library)

      Kind: instance method of Project
      Returns: string | undefined -

      • Path to parent module's binary.
      • 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

        Finds and returns path of given command, trying to following steps:

        1. If it is a command defined in path, returns it's path.
        2. 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, looks bin[module name] in module's package.json. 2.c. If found returns it's path.
        3. Throws error. module name is used by default.

        Kind: instance method of Project
        Returns: string -

        • Path to binary.
        • **Throws**:
          • 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.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

          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 -

          • Full path to module file.
          • Param Type Description
            ...part string

            Path parts to get path relative to module root.

            project.fromConfigDir(...part) ⇒ string

            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 -

            • Path in config directory.
            • Param Type Description
              ...part string

              Path relative to config dir.

              project.fromScriptsDir(...part) ⇒ string

              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 -

              • Path in config directory.
              • 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.

                  project.envIsSet(name) ⇒ boolean

                  Returns whether given environment variable is set and not empty.

                  Kind: instance method of Project
                  Returns: boolean -

                  • Whether given environment variable is set and not empty.
                  • 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: * -

                    • Environment variable or default value.
                    • 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

                      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 -

                      • Result of script
                      • **Throws**:
                        • VError
                          • Throws error if script throws error.
                        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>

                        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> -

                        • Result of script function. (If more than one command executed, array of results)
                        • **Throws**:
                          • 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 = executeScriptFileSync("build"); // Executes my-scripts/lib/scripts/build

                          project.hasScriptSync(scriptFile) ⇒ string | undefined

                          Checks whether given script exists in scripts directory. Script search method is as below:

                          1. If given path found (dir or file), returns it.
                          2. If file name has no extension, looks a file name with extension in order of ts, js.
                          3. If file name with an extension is found, returns full path of filename including extension.

                          Kind: instance method of Project
                          Returns: string | undefined -

                          • Full path (with extension if it has one). Undefined if not found.
                          • Param Type Description
                            scriptFile string

                            Module file to check existence.

                            project.executeSync(...executables) ⇒ ScriptResult

                            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 -

                            • Result of the executable.
                            • 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

                              Same as Project.executeSync(), but adds exit: false to the result.

                              Kind: instance method of Project
                              Returns: ScriptResult -

                              • Result of the executable.
                              • **See**: Project.executeSync()
                                Param Type Description
                                ...executables Executable

                                Executable or executables.

                                project.getConcurrentlyArgs(scripts, [options], [killOthers]) ⇒ Array.<string>

                                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> -

                                • Arguments to use with concurrently.
                                • 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.

                                      project.fromRoot(...part) ⇒ string

                                      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 -

                                      • Path in root.
                                      • 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

                                        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 -

                                        • Path in root.
                                        • 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

                                          Checks whether given file is a tracked data file.

                                          Kind: instance method of Project
                                          Returns: boolean -

                                          • Whether given file is a tracked data file.
                                          • 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.

                                              project.isBrokenLink(projectFile) ⇒ boolena

                                              Returns whether given project file is a broken link. (Links which points to non-existing paths)

                                              Kind: instance method of Project
                                              Returns: boolena -

                                              • Whether given project file is a broken link.
                                              • Param Type Description
                                                projectFile string

                                                Project file to check.

                                                project.saveSync() ⇒ void

                                                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

                                                project.resetSync() ⇒ void

                                                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

                                                project.resetFileSync(projectFile) ⇒ void

                                                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

                                                project.getFileDetailsSync(projectFile, options) ⇒ FileDetail

                                                Returns file details related to given file path relative to root.

                                                Kind: instance method of Project
                                                Returns: FileDetail -

                                                • File details
                                                • **Throws**:
                                                  • 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.

                                                  project.getFileHashSync(projectFile) ⇒ string

                                                  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 -

                                                  • Calculated hash for file.
                                                  • Param Type Description
                                                    projectFile string

                                                    File path of the file relative to root to calculate hash for.

                                                    project.getDataObjectSync(projectFile, [options]) ⇒ DataObject

                                                    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 -

                                                    • [DataObject](#DataObject) instance.
                                                    • **Throws**:
                                                      • 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. (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

                                                      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.
                                                      createSymLink(here("../../config.json"), "tsconfig.json");

                                                      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: * -

                                                      • Content of the file.
                                                      • **Throws**:
                                                        • 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)

                                                        project.readFileDetailedSync(projectFile, [options]) ⇒ Object

                                                        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 -

                                                        • Content of the file.
                                                        • **Throws**:
                                                          • 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)

                                                          project.writeFileSync(projectFile, data, [options]) ⇒ void

                                                          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. 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

                                                          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.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

                                                          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.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

                                                          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.createDir("path/to/dir"); // Created "path", "to" and "dir" as necessary.

                                                          project.deleteDirSync(projectDir, [options]) ⇒ void

                                                          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

                                                          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 silky, verbose, info, warn, error.

                                                          dataObject.isChanged : boolean

                                                          Whether data is changed.

                                                          Kind: instance property of DataObject
                                                          Read only: true

                                                          dataObject.data : Data

                                                          Stored data.

                                                          Kind: instance property of DataObject
                                                          Read only: true

                                                          dataObject.original : Data

                                                          Original state of the data after operations applied to reset into its original state.

                                                          Kind: instance property of DataObject
                                                          Read only: true

                                                          dataObject.snapshot : Data

                                                          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.hasProp(["scripts.build", "scripts.build:doc"], "yes", "no");

                                                            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.hasSubProp("scripts", ["build", "build:doc"]);
                                                              const result2 = project.hasSubProp("address.home", ["street.name", "street.no"]);

                                                              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: * -

                                                              • Data stored at given key.
                                                              • Param Type Description
                                                                path Path

                                                                Path to get data from

                                                                dataObject.set(path, value, [options]) ⇒ this

                                                                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 -

                                                                • Object instance.
                                                                • 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

                                                                  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 -

                                                                  • Object instance.
                                                                  • 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

                                                                    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 -

                                                                    • Object instance.
                                                                    • 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>

                                                                      Resets data and snapshot to its original states.

                                                                      Kind: instance method of DataObject
                                                                      Returns: Array.<Operation> -

                                                                      • Unapplied operations
                                                                      • replaceArgumentName(args, names, newName) ⇒ Array

                                                                        Returns a new array, after replacing output destination argument name with a new name. Does not mutate original array.

                                                                        Kind: global function
                                                                        Returns: Array -

                                                                        • Index number of parameter whose name found in arguments.ü
                                                                        • 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

                                                                          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

                                                                          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]

                                                                          Kind: global typedef
                                                                          Example

                                                                          const bin = "tsc";
                                                                          const binWithArgs = ["tsc", ["--strict", "--target", "ESNext"]];
                                                                          const binWithOptions = ["tsc", ["--strict", "--target", "ESNext"], { encoding: "utf-8" }];

                                                                          ScriptResult : Object

                                                                          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)

                                                                          Script : function

                                                                          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.

                                                                          Package Sidebar

                                                                          Install

                                                                          npm i script-helper

                                                                          Weekly Downloads

                                                                          20

                                                                          Version

                                                                          0.8.9

                                                                          License

                                                                          MIT

                                                                          Unpacked Size

                                                                          409 kB

                                                                          Total Files

                                                                          80

                                                                          Last publish

                                                                          Collaborators

                                                                          • ozum