Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple NPM version checker
class NpmCheck
# Checks package.json against the local node_modules directory
# to assert that every package specified in package.json is
# present in node_modules. If possible, it performs a basic
# "newer or equal than" check on the package's version. Without
# access to npm's semver primitizes & parsing it is a bit more difficult
# to perform proper version matching checks.
#
# Requires https://github.com/jlindsey/semantic to parse versions.
#
# `npm ls` will also do these things .. which I learned after writing this code!
#
# Copyright (c) 2016 Marketplacer
# Licensed under the MIT License https://opensource.org/licenses/MIT
def initialize package_json_path, node_modules_path: nil
@package_json_path = package_json_path
@node_modules_path = node_modules_path
@node_modules_path ||= File.expand_path('../node_modules', package_json_path)
end
def missing_dependencies check_dev_deps: false
package_json = JSON.parse(File.read(@package_json_path))
dependencies = package_json['dependencies']
if check_dev_deps
dependencies = dependencies.merge(package_json['devDependencies'])
end
results = dependencies.map do |name, version|
check_dep name, version
end
results.reject(&:nil?)
end
private
def check_dep name, version
path = File.join(@node_modules_path, name, 'package.json')
return "'#{name}' is missing (#{version} required)" if !File.exist?(path)
version = begin
Semantic::Version.new(version)
rescue ArgumentError
# Not a parseable version, eg 'github:marketplacer/react-dnd-html5-backend',
# so abort here.
return nil
end
dep_json = JSON.parse(File.read(path))
package_version = Semantic::Version.new(dep_json['version'])
if package_version < version
return "old version of '#{name}' (#{package_version} found < #{version} required)"
end
nil
end
end
#!/usr/bin/env ruby
require 'bundler/setup'
require_relative '../lib/npm_check'
require 'semantic'
require 'json'
missing = NpmCheck.new(File.expand_path('../../package.json', __FILE__)).missing_dependencies
if missing.length > 0
$stderr.puts "NPM modules missing or out of date:"
$stderr.puts
$stderr.puts missing.map {|m| " * #{m}"}.join("\n")
$stderr.puts
$stderr.puts "Run `npm install` to resolve."
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment