# frozen_string_literal: true require "json" module NeetoCompliance class PackageDependenciesVersionVerifier < Base def valid? @common_package_json = load_json_file(common_packages_latest_file) @project_package_json = load_json_file("package.json") @incorrect_dependencies = { dependencies: find_incorrect_dependencies(:dependencies), devDependencies: find_incorrect_dependencies(:devDependencies) } @incorrect_dependencies[:misplacedDependencies] = find_misplaced_dependencies @incorrect_dependencies.keys.all? { |key| @incorrect_dependencies[key].empty? } end def auto_correct! end def autofix_command command = "" command += "yarn remove #{@incorrect_dependencies[:misplacedDependencies] .join(" ")}\n" unless @incorrect_dependencies[:misplacedDependencies].empty? command += "yarn add #{@incorrect_dependencies[:dependencies] .join(" ")}\n" unless @incorrect_dependencies[:dependencies].empty? command += "yarn add -D #{@incorrect_dependencies[:devDependencies] .join(" ")}\n" unless @incorrect_dependencies[:devDependencies].empty? command end private def common_packages_latest_file NeetoCompliance::NeetoCommons.path.join "common_files/package-common.json" end def find_misplaced_dependencies project_dependencies = @project_package_json[:dependencies] @common_package_json[:devDependencies].inject([]) do |result, (package_name, latest_version)| next result unless project_dependencies.key?(package_name) @incorrect_dependencies[:devDependencies] |= ["\"#{package_name}@#{latest_version}\""] result.push("#{package_name}") end end def find_incorrect_dependencies(key) project_dependencies = @project_package_json[key] @common_package_json[key].inject([]) do |result, (package_name, latest_version)| next result if project_dependencies[package_name] == latest_version result.push("\"#{package_name}@#{latest_version}\"") end end def load_json_file(url) JSON.parse(open(url).read, symbolize_names: true) end end end