Git Product home page Git Product logo

check-dependencies's Introduction

check-dependencies

Checks if currently installed npm dependencies are installed in the exact same versions that are specified in package.json

GitHub build Version Downloads MIT License

Installation

To install the package and add it to your package.json, invoke:

npm install check-dependencies --save-dev

Rationale

When dependencies are changed in package.json, whether it's a version bump or a new package, one can forget to invoke npm install and continue using the application, possibly encountering errors caused by obsolete package versions. To avoid it, use the check-dependencies module at the top of the entry point of your application; it will inform about not up-to-date setup and optionally install the dependencies.

Another option would be to always invoke npm install at the top of the main file, but it can be slow and check-dependencies is fast.

Usage

Once the package has been installed, it may be used via:

CLI

$ check-dependencies

All options from the API except log and error can be passed to the CLI in their kebab-case versions, not camelCase ones. Example:

$ check-dependencies --verbose --package-manager pnpm --scope-list dependencies

Options accepting array values in the API (like scopeList) should have each value passed individually, example:

$ check-dependencies --scope-list dependencies --scope-list devDependencies

API

The exported function returns a promise which should eventually be fulfilled (never rejected).

const output = await require('check-dependencies')(config);

where config is a configuration object.

output is an object containing fields:

{
    status: number,      // 0 if successful, 1 otherwise
    depsWereOk: boolean, // true if dependencies were already satisfied
    log: array,          // array of logged messages
    error: array,        // array of logged errors
}

There is a synchronous alternative -- the following code:

const output = require('check-dependencies').sync(config);

will assign to output the same object to which the returned promise would otherwise resolve to.

The config object may have the following fields:

packageManager

Package manager to check against. Example values: 'npm', yarn, pnpm.

NOTE: The value passed to this parameter will be invoked if the install option is set to true. Do not pass untrusted input here. In the worst case, it may lead to arbitrary code execution! Also, versions below 1.1.1 did no validation of this parameter; versions 1.1.1 and newer ensure it matches the regex /^[a-z][a-z0-9-]*$/i. It is still not safe to provide untrusted input in versions 1.1.1 or newer, though.

Type: string

Default: 'npm'

packageDir

Path to the directory containing package.json.

Type: string

Default: the closest directory containing package.json when going up the tree, starting from the current one

onlySpecified

Ensures all installed dependencies are specified in package.json.

NOTE: Don't use this option with npm 3.0.0 or newer as it deduplicates the file dependency tree by default so check-dependencies will think many modules are excessive whereas in fact they will not.

Type: boolean

Default: false

install

Installs packages if they don't match. With the onlySpecified option enabled it installs if excessive packages are present as well.

Type: boolean

Default: false

scopeList

The list of keys in package.json where to look for package names & versions.

Type: array

Default: ['dependencies', 'devDependencies']

optionalScopeList

The list of keys in package.json where to look for optional package names & versions. An optional package is not required to be installed but if it's installed, it's supposed to match the specified version range.

This list is also consulted when using onlySpecified: true.

Type: array

Default: ['optionalDependencies']

checkGitUrls

By default, check-dependencies will skip version check for packages whose version contains the full repository path. For example:

    "dependencies": {
      "semver": "https://github.com/npm/node-semver.git#0.5.9"
    }

If checkGitUrls is enabled, check-dependencies will parse the version number (after the path to the git repository and the hash) and check it against the version of the installed package.

Type: boolean

Default: false

verbose

Prints messages to the console.

Type: boolean

Default: false

log

A function logging debug messages (applies only if verbose: true).

Type: function

Default: console.log.bind(console)

error

A function logging error messages (applies only if verbose: true).

Type: function

Default: console.error.bind(console)

Usage Examples

The most basic usage:

const output = await require('check-dependencies')();

This will check packages' versions and report an error to output if packages' versions are mismatched.

The following:

await require('check-dependencies')({
    install: true,
    verbose: true,
});

will install mismatched ones.

Supported Node.js versions

This project aims to support all Node.js versions supported upstream (see Release README for more details).

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using npm test.

License

Copyright (c) Michał Gołębiowski-Owczarek. Licensed under the MIT license.

check-dependencies's People

Contributors

dependabot[bot] avatar felixfurtmayr avatar icecreamyou avatar mfgcode avatar mgol avatar pruge avatar shvaikalesh avatar sitegui avatar thesavior avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

check-dependencies's Issues

Feature request: support git url with semver tags

Hello,

I wanted to ask your opinion about this feature.

in a project with git, we use semver tags for our releases. (I put a link at the end for more info)

So, in our projects we can use this way of declaring dependencies in package.json for npm:

  "dependencies": {
    "project1": "git+ssh://[email protected]:sspinc/project1.git#0.5.9",
    "project2": "git+ssh://[email protected]:sspinc/project2.git#1.10.6"
  }

I was able to check correctly the dependencies adding the following lines to your code:

        if (/^git/.test(versionString)) {
          versionString = (/\#(.+)$/.exec(versionString))[1]
          if (!semver.valid(versionString))
            return;
        }

This works only if it finds a valid semver tag.
Would you agree with that? if yes I could send you a pull request

Infos

http://stackoverflow.com/questions/2006265/is-there-a-standard-naming-convention-for-git-tags

NPM shrinkwrap support?

Hi, this is more of a question than an "issue". I tried the library, and it doesn't appear to have support for "NPM Shrinkwrap". Am I missing something, or does this library not support it?
Our team shrinkwraps our modules, so we would essentially need the npm-shrinkwrap.json file to take precedence over what is defined in package.json.

Don't print errors in non-verbose mode when run with the install option

If check-dependencies is run in non-verbose mode with the install option enabled, it shouldn't print detailed info about mismatched packages as it creates an impression that the whole command failed.

Optionally it could print it but with a clear message that it was the first try and that it later succeeded.

Locally installed bower and --packageDir

Hi, I have a bit of an esoteric bug to report.
Imagine my folder structure as:

  • package.json
  • other
    • bower.json

package.json installs bower and check-dependencies as devDependencies for the project.
So, I run, back to back:

$(npm bin)/check-dependencies --verbose --install
$(npm bin)/check-dependencies --verbose --install --package-manager bower --packageDir other/

but, if no bower_components are currently installed, the second command fails:
/bin/sh: 1: bower: not found
Invoking bower install...
and proceeds to not install anything.

I then noticed, if I replace with:

$(npm bin)/check-dependencies --verbose --install --package-manager $(npm bin)/bower --packageDir other/

Then it can find it and properly installs all the packages.
However, if I then re-run, and bower_components have been installed, it'll tell me that every package is not installed. So if I return to our first command, $(npm bin)/check-dependencies --verbose --install --package-manager bower --packageDir other/ now that bower_components are installed, then it'll report the correct versions and everything.

Finally, my solution ends up being:

echo -e "\e[93m\e[1mChecking Bower Packages...\e[0m"
$(npm bin)/check-dependencies --verbose --install --package-manager bower --packageDir other/ || $(npm bin)/check-dependencies --verbose --install --package-manager $(npm bin)/bower --packageDir other/

So here, on first run (no bower_components) the first command fails, therefor invoking the second version. Once that's done, all subsequent runs work with the first version.

Like I said, a bit esoteric but I figured I'd report it anyway. Thanks for the package, earlier I had tried rolling my own with npm ls and it was unacceptably slow. This package saved me a lot of time and I appreciate it!

Support for custom dependencies folder and support to allow taking into account resolutions

Hey Michał , thanks for writing this plugin it has been very useful in the current project I am working on.

I hope you would consider adding support for the following issues;

  1. Is it possible to have support for an option to use a custom node_modules or bower_components folder to check against?

My current use case is that I have two node_modules folder, one for third party public libraries and one for inhouse developed modules which we have packaged as npm modules.

Currently to get that to work I am adding something like this as an override (check-dependencies.js L65):

if (options.customDepsDir) { depsDirName = options.customDepsDir; } else { depsDirName = options.packageManager === 'npm' ? node_modules' : 'bower_components'; }

  1. If package.json or bower.json has resolutions it is not taken into account. Would it be possible to have an option to take into account resolutions?

For example in the following package.json, check dependencies will throw an error that 2.0.0 is installed and 1.0.0 is required:

{ "dependencies" : { "my-node-module" :" 1.0.0" }, "resolutions" : { "my-node-module" : "2.0.0" } }

To get resolutions taken into account I am adding the following lines (check-dependencies.js L195):

const resolutionsMappings = getDepsMappingsFromScopeList(['resolutions']); const fullDepsMappings = Object.assign({}, depsMappings, optionalDepsMappings, resolutionsMappings);

Maybe an option can be added to allow resolutions to override what is set in dependencies version.

I am able to work on these changes and send you a PR for review if you decide to include these features.

Thanks for your time.

New package release?

The last release, 1.1.0, was in 2017. There have been quite a few updates since then. Any chance we can get a version bump?

Figure out the story for onlySpecified in npm@3

npm 3 dedupes sub-dependencies by default which means node_modules contains many dependencies of dependencies directly, making the onlySpecified option to not work as it should.

We need to figure out what to do in such a case. Currently README contains a warning against using this option with npm@3. npm ls prints such info but it's very slow, way more than in npm@2 and one of the main goals of this module was to make this whole checking as fast as possible.

This option is still useful for bower so I don't think we want to depreciate it.

A problem with determination of installed versions for Bower packages

In the discussion of #10 (comment) was found a problem with determination of installed versions for the Bower packages, for which those versions aren't valid semvers.

If the used version (git tag) isn't a valid semver, the generated .bower.json won't contain the version field (but will contain the _release field in all cases):

bower install susy#2.2.0.beta.3
{
  "name": "susy",
 ...
  "_release": "2.2.0.beta.3",
 ...
}

and

bower install susy#2.2.2
{
  "name": "susy",
  "version": "2.2.2",
 ...
  "_release": "2.2.2",
 ...
}

UPD: If the target version of the package is set to "*" (and there are no any valid versions), the _release field will contain the last commit hash:

bower install sass-meyer-reset
{
  "name": "sass-meyer-reset",
 ...
  "_release": "1dc79b9776",
 ... 
  "_target": "*",
 ...
}

Exclude Dependencies

Hi all,

Can we exclude some dependencies for checking? For example, "color-thief" plugin doesn't have semver tag and check-dependencies gives error for that. This feature will fix problematic dependencies.

Thanks!

bower: checkCustomPackageNames doesn't seem to work (possibly for commit hashes or branch names)

Dependencies with custom package names seem to be ignored. At first I thought this was just for packages that specify something other than a tag for their version, but the output below shows the package being ignored the first time, too.

After an initial bower install:

> var fs = require('fs'),
...   checkDependencies = require('check-dependencies');
undefined
> fs.readFile('bower.json', 'utf-8', function(_, data) {
...   console.log(data);
... });
undefined
> {
  "name": "check-dependecies-test",
  "version": "0.0.0",
  "devDependencies": {
    "util": "dojo/util#1.10.4"
  }
}


(^C again to quit)
> checkDependencies({
...     packageManager: 'bower',
...     verbose: true,
...     checkCustomPackageNames: true
... }, console.log.bind(console));
{ log: [], error: [], depsWereOk: true, status: 0 }
{ _bitField: 268435456,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _progressHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _settledValue: { log: [], error: [], depsWereOk: true, status: 0 } }
> fs.readFile('bower.json', 'utf-8', function(_, data) {
...   console.log(data);
... });
undefined
> {
  "name": "check-dependecies-test",
  "version": "0.0.0",
  "devDependencies": {
    "util": "dojo/util#7085ef15f71a4dbd7b8662044d7155f185dc60c9"
  }
}


(^C again to quit)
> checkDependencies({
...     packageManager: 'bower',
...     verbose: true,
...     checkCustomPackageNames: true
... }, console.log.bind(console));
{ log: [], error: [], depsWereOk: true, status: 0 }
{ _bitField: 268435456,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _progressHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _settledValue: { log: [], error: [], depsWereOk: true, status: 0 } }

That's:

  • show the contents of bower.json, where dojo/util#1.10.4 is specified as the only dev dependency
  • run check-dependencies, with checkCustomPackageNames set to true, for sanity; note that there's no output about the specified and installed versions here
  • change bower.json (not shown in node transcript); then show the contents of bower.json again, where dojo/util#7085ef15f71a4dbd7b8662044d7155f185dc60c9 is specified; that hash is the current – as of this writing – head of master, and is a different hash than the 1.10.4 tag
  • run check-dependencies again with the same options

There's no output and the report says everything is ok even though the installed version is different than the version specified in bower.json.

The second check-dependencies run doesn't seem to work even if we use something like master or even another tag name like 1.10.3 for the version, so it looks like checkCustomPackageNames might be broken for more than just commit hashes.

Yarn support and/or callback

Per your request, re-opening here.

Currently this package doesn't support Yarn. This could be ameliorated either by:

  • Adding support for Yarn
  • Or, adding semi-generic support for package managers that come along (that support the package.json format, like Yarn does). This could be done by offering in the options to specify a callback function that's called if the dependencies are out of date. In there I could manually run Yarn or whatever else.

support hoisted node_modules

right now it only searches the sibling node_modules folder, but it would be nice to search node_modules that may be hoisted up further in the tree, since node will be able to resolve them.

e.g.:

root
	package.json
	node_modules/
		a-module-dep
	packages/
		a-module
		package.json

this way I could use yarn workspaces, which hoists node_modules of subpackages in a monorepo

git urls can't handle a version range

when specifying a git url for the package (or, probably but not tested, a custom package name) the version check fails if it is a range (eg ~0.0.1). This is because it's being validated with semver.valid() which is intended to validate a specific version string, not a range.

I would suggest that neither case should use semver.valid(), as it's an additional amount of validation that doesn't get applied to a "regular" version string.

Support Node.js & npm versions defined in `engines` section of `package.json`

A package.json file can have an engines section where Node.js and npm required versions can be defined, it would be great if check-dependencies supported this.

Ref: https://docs.npmjs.com/files/package.json#engines

Example:

"engines": {
  "node": ">=6.9.1",
  "npm": "^5.2.0"
}

The above is what I plan on changing a few projects I work on and if grunt-check-dependencies were to then throw a warning that a user has an older npm 3.x or 4.x, 5.0.x or 5.1.x installed that would be fantastic.

packageDir as an array

we have multiple package.json files in project (nested in different folders), it would be good to have ability to enter "packageDir" as an array

cli tool

is it possible to include a command line interface for it?
like install it globally and run it from project root as in npm-check-updates package

continue option does not work

Hi ,

according the documentation in npmjs

// If true, instead of aborting the task after checking (and installing), the task will continue.
// Default: false.
continue: boolean,

i configured the option, but the task is anyway aborted. At the same time I wouldn't use --force.

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.