From fd088a7381c65346ff743a0d80f173a3f180e1c6 Mon Sep 17 00:00:00 2001 From: nikhil2611 Date: Mon, 22 May 2023 12:04:11 +0530 Subject: [PATCH] using chef:version from chef gem to validate cookbook versions Signed-off-by: nikhil2611 --- lib/berkshelf/validator.rb | 11 +++++++++++ spec/unit/berkshelf/validator_spec.rb | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/berkshelf/validator.rb b/lib/berkshelf/validator.rb index b081557f4..780161630 100644 --- a/lib/berkshelf/validator.rb +++ b/lib/berkshelf/validator.rb @@ -1,3 +1,5 @@ +require 'chef/version_class' + module Berkshelf module Validator class << self @@ -25,10 +27,19 @@ def validate_files(cookbooks) base, name = Pathname.new(cookbook.path.to_s).split files = Dir.glob("#{name}/**/*.rb", base: base.to_s).select { |f| f =~ /[[:space:]]/ } + validate_versions(cookbook) raise InvalidCookbookFiles.new(cookbook, files) unless files.empty? end end + + def validate_versions(cookbook) + cookbook_dependencies = cookbook.dependencies + cookbook_dependencies.each do |cookbook_name, cookbook_version| + version = cookbook_version.gsub(/[^\d,\.]/, '') + Chef::Version.new(version) + end + end end end end diff --git a/spec/unit/berkshelf/validator_spec.rb b/spec/unit/berkshelf/validator_spec.rb index 58c270fd5..5dab23691 100644 --- a/spec/unit/berkshelf/validator_spec.rb +++ b/spec/unit/berkshelf/validator_spec.rb @@ -6,6 +6,7 @@ it "raises an error when the cookbook has spaces in the files" do allow(Dir).to receive(:glob).and_return(["/there are/spaces/in this/recipes/default.rb"]) + allow(cookbook).to receive(:dependencies).and_return({"cookbook" => "1.0.0"}) expect do subject.validate_files(cookbook) end.to raise_error(Berkshelf::InvalidCookbookFiles) @@ -13,6 +14,21 @@ it "does not raise an error when the cookbook is valid" do allow(Dir).to receive(:glob).and_return(["/there-are/no-spaces/in-this/recipes/default.rb"]) + allow(cookbook).to receive(:dependencies).and_return({"cookbook" => "1.0.0"}) + expect do + subject.validate_files(cookbook) + end.to_not raise_error + end + + it "raises an error when the cookbook version is not valid" do + allow(cookbook).to receive(:dependencies).and_return({"cookbook" => "1"}) + expect do + subject.validate_files(cookbook) + end.to raise_error + end + + it "does not raise an error when the cookbook version is valid" do + allow(cookbook).to receive(:dependencies).and_return({"cookbook" => "1.0"}) expect do subject.validate_files(cookbook) end.to_not raise_error