Skip to content

Commit

Permalink
update requirements parsing for package.json -> engines
Browse files Browse the repository at this point in the history
  • Loading branch information
kbukum1 committed Nov 25, 2024
1 parent a095c7f commit 37a0210
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
30 changes: 17 additions & 13 deletions npm_and_yarn/lib/dependabot/npm_and_yarn/package_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -287,21 +287,25 @@ def package_manager
def find_engine_constraints_as_requirement(name)
return nil unless @engines.is_a?(Hash) && @engines[name]

constraint = @engines[name].to_s.strip
return nil if constraint.empty?

# Handle shorthand cases
if constraint.match?(/^\d+$/) # Major only, e.g., "3"
major_version = constraint.to_i
constraint = ">=#{major_version}.0.0 <#{major_version + 1}.0.0"
elsif constraint.match?(/^\d+\.\d+$/) # Major and minor, e.g., "3.2"
major, minor = constraint.split(".").map(&:to_i)
constraint = ">=#{major}.#{minor}.0 <#{major}.#{minor + 1}.0"
elsif constraint.match?(/^\d+\.\d+\.\d+$/) # Full version, e.g., "3.2.1"
constraint = "=#{constraint}" # Exact match
raw_constraint = @engines[name].to_s.strip

return nil if raw_constraint.empty?

raw_constraints = raw_constraint.split

constraints = raw_constraints.map do |constraint|
if constraint.match?(/^\d+$/)
">=#{constraint}.0.0 <#{constraint.to_i + 1}.0.0"
elsif constraint.match?(/^\d+\.\d+$/)
">=#{constraint} <#{constraint.split('.').first.to_i + 1}.0.0"
elsif constraint.match?(/^\d+\.\d+\.\d+$/)
"=#{constraint}"
else
constraint
end
end

Requirement.new(constraint)
Requirement.new(constraints)
rescue StandardError => e
Dependabot.logger.error("Failed to parse engines constraint for #{name}: #{e.message}")
nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,18 @@

describe "#find_engine_constraints_as_requirement" do
context "when the engines field contains valid constraints" do
let(:package_json) do
{
"name" => "example",
"version" => "1.0.0",
"engines" => {
"npm" => ">=6.0.0 <8.0.0",
"yarn" => ">=1.22.0 <2.0.0",
"pnpm" => "7.5.0"
}
}
end

it "returns a requirement for npm with the correct constraints" do
requirement = helper.find_engine_constraints_as_requirement("npm")
expect(requirement).to be_a(Dependabot::NpmAndYarn::Requirement)
Expand Down

0 comments on commit 37a0210

Please sign in to comment.