Skip to content

Commit

Permalink
update npm_version detection
Browse files Browse the repository at this point in the history
  • Loading branch information
kbukum1 committed Oct 8, 2024
1 parent 7c4f6c8 commit 95a9715
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
36 changes: 25 additions & 11 deletions npm_and_yarn/lib/dependabot/npm_and_yarn/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,37 @@ module Helpers
YARN_DEFAULT_VERSION = YARN_V3
YARN_FALLBACK_VERSION = YARN_V1

# NPM 7 uses lockfileVersion 2
# NPN 8 uses lockfileVersion 2
# NPN 9 uses lockfileVersion 3
# Determines the npm version based on the lockfile version
# - NPM 7 uses lockfileVersion 2
# - NPM 8 uses lockfileVersion 2
# - NPM 9 uses lockfileVersion 3

sig { params(lockfile: DependencyFile).returns(Integer) }
def self.npm_version_numeric(lockfile)
lockfile_content = T.must(lockfile.content)
lockfile_version = JSON.parse(lockfile_content)["lockfileVersion"].to_i
lockfile_content = lockfile.content

# Return default NPM version if there's no lockfile or it's empty
return NPM_DEFAULT_VERSION if lockfile_content.nil? || lockfile_content.strip.empty?

parsed_lockfile = JSON.parse(lockfile_content)

return NPM_V8 if lockfile_version == 2 # Corresponds to npm 7, 8
return NPM_V9 if lockfile_version == 3 # Corresponds to npm 9
lockfile_version_str = parsed_lockfile["lockfileVersion"]

# Default to npm 9 if lockfileVersion is not in the specific range
return NPM_DEFAULT_VERSION if lockfile_version < 2 || lockfile_version > 3
# Default to npm default version if lockfileVersion is missing or empty
return NPM_DEFAULT_VERSION if lockfile_version_str.nil? || lockfile_version_str.to_s.strip.empty?

NPM_FALLBACK_VERSION # Default fallback to npm 8
lockfile_version = lockfile_version_str.to_i

case lockfile_version
when 2
NPM_V8 # Corresponds to npm 7, 8
when 3
NPM_V9 # Corresponds to npm 9
else
NPM_FALLBACK_VERSION # Default fallback if unexpected version
end
rescue JSON::ParserError
NPM_FALLBACK_VERSION # Fallback to npm 8 if parsing fails
NPM_DEFAULT_VERSION # Fallback to default npm version if parsing fails
end

sig { params(yarn_lock: DependencyFile).returns(Integer) }
Expand Down
4 changes: 3 additions & 1 deletion npm_and_yarn/lib/dependabot/npm_and_yarn/package_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ def guessed_version(name)
lockfile = @lockfiles[name.to_sym]
return unless lockfile

Helpers.send(:"#{name}_version_numeric", lockfile)
version = Helpers.send(:"#{name}_version_numeric", lockfile)

Dependabot.logger.info("Guessed version info \"#{name}\" : \"#{version}\"")
end

sig { params(name: T.untyped).returns(T.nilable(String)) }
Expand Down

0 comments on commit 95a9715

Please sign in to comment.