From 2856df79ac43b56e38d88d17afbca854d9d68529 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 23 Oct 2014 10:52:02 -0700 Subject: [PATCH] core: Vagrant.has_plugin? can take version requirements [GH-4650] --- CHANGELOG.md | 2 ++ lib/vagrant.rb | 17 +++++++++++++---- test/unit/vagrant_test.rb | 10 ++++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 063cee7bd..bcf268202 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ IMPROVEMENTS: + - core: `has_plugin?` function now takes a second argument which is a + version constraint requirement. [GH-4650] - guests/arch: Support predictable network interface naming. [GH-4468] - guests/suse: Support NFS client install, rsync setup. [GH-4492] - guests/tinycore: Support changing host names. [GH-4469] diff --git a/lib/vagrant.rb b/lib/vagrant.rb index 26ed01820..d3ab6f37c 100644 --- a/lib/vagrant.rb +++ b/lib/vagrant.rb @@ -141,13 +141,22 @@ module Vagrant # This checks if a plugin with the given name is installed. This can # be used from the Vagrantfile to easily branch based on plugin # availability. - def self.has_plugin?(name) - # We check the plugin names first because those are cheaper to check - return true if plugin("2").manager.registered.any? { |p| p.name == name } + def self.has_plugin?(name, version=nil) + if !version + # We check the plugin names first because those are cheaper to check + return true if plugin("2").manager.registered.any? { |p| p.name == name } + end + + # Make the requirement object + version = Gem::Requirement.new([version]) if version # Now check the plugin gem names require "vagrant/plugin/manager" - Plugin::Manager.instance.installed_specs.any? { |s| s.name == name } + Plugin::Manager.instance.installed_specs.any? do |s| + match = s.name == name + next match if !version + next version.satisfied_by?(s.version) + end end # Returns a superclass to use when creating a plugin for Vagrant. diff --git a/test/unit/vagrant_test.rb b/test/unit/vagrant_test.rb index 03bb1126e..613e3a98b 100644 --- a/test/unit/vagrant_test.rb +++ b/test/unit/vagrant_test.rb @@ -74,6 +74,16 @@ describe Vagrant do expect(described_class.has_plugin?("foo")).to be_true expect(described_class.has_plugin?("bar")).to be_false end + + it "finds plugins by gem version" do + specs = [Gem::Specification.new] + specs[0].name = "foo" + specs[0].version = "1.2.3" + Vagrant::Plugin::Manager.instance.stub(installed_specs: specs) + + expect(described_class.has_plugin?("foo", "~> 1.2.0")).to be_true + expect(described_class.has_plugin?("foo", "~> 1.0.0")).to be_false + end end describe "require_version" do