resettable-file
TypeScript icon, indicating that this package has built-in type declarations

0.3.13 • Public • Published

resettable-file

Resettable files for creating and maintaining boilerplates and configurations

Commitizen friendly

Description

Provides utility class and methods for boilerplate projects to create/copy/remove files, directories and data files (json/yaml). Created files, directories and data files are tracked and recorded to a json file, and modifications done by this library can be undone by reset() method.

Please note that, this module does not try to be a version conrol system. Main purpose of this module is to modify and reverse selected files only.

Synopsis

Written using TypeScript

const ResettableFile = require("resettable-file");
 
// Set "warn" (default) or "error" for less noise
const resettableFile = new ResettableFile("./registry.json", { logLevel: "info" });
 
// Track changes by key/value level
const packageData = resettableFile.getDataObjectSync("./package.1.json");
 
// Modify package.json
packageData.set("scripts.myscript", "some-cmd").set("scripts.ls", "ls -al");
 
// Write data to file
resettableFile.writeFileSync("some.txt", "Some text data here");
 
// Create a symbolic link
resettableFile.createSymLinkSync("/some/where/tsconfig.json", "tsconfig.json");
 
// Create directory tree
resettableFile.createDirSync("some/deep/path");
 
// Save changes to registry
resettableFile.saveSync();
// Delete created keys in package.json, delete file and symbolic link if not changed
// and delete directory tree if they are empty:
resettableFile.resetSync();

Reset

Can

  • Delete created files by this library if they are not changed outside.
  • Delete created symbolic links if they are not changed outside.
  • Delete created directories,
    • if they are empty
    • or all files in directories are created by this libray and they are not changed outside.
  • Reset key/value pairs in data files (modifictions made by this library)
    • Delete created keys,
    • Create old keys and values for deleted keys,
    • Write old values to replaced keys,
    • Delete created values from arrays
    • Insert deleted values in to arrays (closest index possible)

Can't

  • Create deleted files.
  • Create deleted directories.
  • Replace old content of files (except data files)
  • Recreate deleted directories
  • Recreate deleted symbolic links

As seen from what can and can't be done, ResettableFile is a utility to create and modify text based files and data files (json and yaml) and not a backup/version control for deleted files.

API

Classes

DataObject

This class is used for modifications of the given object.

ResettableFile

Provides utility class and methods for boilerplate projects to create/copy/remove files, directories and data files (json/yaml). Created files, directories and data files are tracked and recorded to a json file, and modifications done by this library can be undone by reset() method.

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

                Provides utility class and methods for boilerplate projects to create/copy/remove files, directories and data files (json/yaml). Created files, directories and data files are tracked and recorded to a json file, and modifications done by this library can be undone by reset() method.

                Kind: global class

                new ResettableFile(registryFile, [options])

                Param Type Default Description
                registryFile string

                Path of the registry file. Registry file's directory is also root directory.

                [options] Object

                Options

                [options.sourceRoot] string

                Source root. If provided all source files are calculated relative to this path for copy, symbolic link etc.

                [options.track] boolean

                Sets default tracking option for methods.

                [options.logLevel] string "&quot;warn&quot;"

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

                [options.logger] BasicLogger

                A looger instance such as winston. Must implement info, warn, error, verbose, silly.

                resettableFile.root : string

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

                Kind: instance property of ResettableFile
                Read only: true

                resettableFile.sourceRoot : string

                Source root path for files to be managed. It is the source root directory given during object construction.

                Kind: instance property of ResettableFile
                Read only: true

                resettableFile.track : boolean

                Whether files of the project are tracked by default.

                Kind: instance property of ResettableFile
                Read only: true

                resettableFile.logger : BasicLogger

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

                Kind: instance property of ResettableFile
                Read only: true

                resettableFile.logLevel : string

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

                Kind: instance property of ResettableFile

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

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

                    resettableFile.isDataFile(projectFile) ⇒ boolean

                    Checks whether given file is a tracked data file.

                    Kind: instance method of ResettableFile
                    Returns: boolean -

                    • Whether given file is a tracked data file.
                    • Param Type Description
                      projectFile string

                      File to check

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

                        resettableFile.isBrokenLink(projectFile) ⇒ boolena

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

                        Kind: instance method of ResettableFile
                        Returns: boolena -

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

                          Project file to check.

                          resettableFile.saveSync() ⇒ void

                          Saves data files and registry file. Must be called if any changes are made.

                          Kind: instance method of ResettableFile
                          Throws:

                          • VError
                            • Throws error if files cannot be written

                          resettableFile.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 ResettableFile
                          Throws:

                          • VError
                            • Throws error if files cannot be written

                          resettableFile.resetFileSync(projectFile) ⇒ void

                          Resets given file.

                          Kind: instance method of ResettableFile
                          Throws:

                          • VError
                            • Throws error if file cannot be reset.
                          Param Type Description
                          projectFile string

                          File to reset

                          resettableFile.getFileDetailsSync(projectFile, options) ⇒ FileDetail

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

                          Kind: instance method of ResettableFile
                          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.

                            resettableFile.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 ResettableFile
                            Returns: string -

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

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

                              resettableFile.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 ResettableFile
                              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"

                                resettableFile.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 ResettableFile
                                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");

                                resettableFile.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 ResettableFile
                                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)

                                  resettableFile.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 ResettableFile
                                  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)

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

                                    Creates and writes given data to a file in project.

                                    Kind: instance method of ResettableFile
                                    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.

                                    resettableFile.deleteFileSync(projectFile, [options]) ⇒ void

                                    Deletes a file from project. Path should be given relative to project root.

                                    Kind: instance method of ResettableFile
                                    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.

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

                                    resettableFile.createDirSync(projectDir, [options]) ⇒ void

                                    Creates given directory and its tree relative to project root.

                                    Kind: instance method of ResettableFile
                                    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.

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

                                    Package Sidebar

                                    Install

                                    npm i resettable-file

                                    Weekly Downloads

                                    14

                                    Version

                                    0.3.13

                                    License

                                    MIT

                                    Unpacked Size

                                    196 kB

                                    Total Files

                                    42

                                    Last publish

                                    Collaborators

                                    • ozum