diff --git a/lib/puppet/parameter.rb b/lib/puppet/parameter.rb index ff7cab22b..29d60fc66 100644 --- a/lib/puppet/parameter.rb +++ b/lib/puppet/parameter.rb @@ -1,302 +1,304 @@ require 'puppet/util/methodhelper' require 'puppet/util/log_paths' require 'puppet/util/logging' require 'puppet/util/docs' require 'puppet/util/cacher' class Puppet::Parameter include Puppet::Util include Puppet::Util::Errors include Puppet::Util::LogPaths include Puppet::Util::Logging include Puppet::Util::MethodHelper include Puppet::Util::Cacher require 'puppet/parameter/value_collection' class << self include Puppet::Util include Puppet::Util::Docs attr_reader :validater, :munger, :name, :default, :required_features, :value_collection attr_accessor :metaparam # Define the default value for a given parameter or parameter. This # means that 'nil' is an invalid default value. This defines # the 'default' instance method. def defaultto(value = nil, &block) if block define_method(:default, &block) else if value.nil? raise Puppet::DevError, "Either a default value or block must be provided" end define_method(:default) do value end end end # Return a documentation string. If there are valid values, # then tack them onto the string. def doc @doc ||= "" unless defined?(@addeddocvals) @doc += value_collection.doc if f = self.required_features @doc += " Requires features #{f.flatten.collect { |f| f.to_s }.join(" ")}." end @addeddocvals = true end @doc end def nodefault undef_method :default if public_method_defined? :default end # Store documentation for this parameter. def desc(str) @doc = str end def initvars @value_collection = ValueCollection.new end # This is how we munge the value. Basically, this is our # opportunity to convert the value from one form into another. def munge(&block) # I need to wrap the unsafe version in begin/rescue parameterments, # but if I directly call the block then it gets bound to the # class's context, not the instance's, thus the two methods, # instead of just one. define_method(:unsafe_munge, &block) end # Does the parameter supports reverse munge? # This will be called when something wants to access the parameter # in a canonical form different to what the storage form is. def unmunge(&block) define_method(:unmunge, &block) end # Mark whether we're the namevar. def isnamevar @isnamevar = true @required = true end # Is this parameter the namevar? Defaults to false. def isnamevar? @isnamevar end # This parameter is required. def isrequired @required = true end # Specify features that are required for this parameter to work. def required_features=(*args) @required_features = args.flatten.collect { |a| a.to_s.downcase.intern } end # Is this parameter required? Defaults to false. def required? @required end # Verify that we got a good value def validate(&block) define_method(:unsafe_validate, &block) end # Define a new value for our parameter. def newvalues(*names) @value_collection.newvalues(*names) end def aliasvalue(name, other) @value_collection.aliasvalue(name, other) end end # Just a simple method to proxy instance methods to class methods def self.proxymethods(*values) values.each { |val| define_method(val) do self.class.send(val) end } end # And then define one of these proxies for each method in our # ParamHandler class. proxymethods("required?", "isnamevar?") attr_accessor :resource # LAK 2007-05-09: Keep the @parent around for backward compatibility. attr_accessor :parent [:line, :file, :version].each do |param| define_method(param) do resource.send(param) end end def devfail(msg) self.fail(Puppet::DevError, msg) end def expirer resource.catalog end def fail(*args) type = nil if args[0].is_a?(Class) type = args.shift else type = Puppet::Error end error = type.new(args.join(" ")) error.line = @resource.line if @resource and @resource.line error.file = @resource.file if @resource and @resource.file raise error end # Basic parameter initialization. def initialize(options = {}) options = symbolize_options(options) if resource = options[:resource] self.resource = resource options.delete(:resource) else raise Puppet::DevError, "No resource set for #{self.class.name}" end set_options(options) end def log(msg) send_log(resource[:loglevel], msg) end # Is this parameter a metaparam? def metaparam? self.class.metaparam end # each parameter class must define the name method, and parameter # instances do not change that name this implicitly means that a given # object can only have one parameter instance of a given parameter # class def name self.class.name end # for testing whether we should actually do anything def noop @noop ||= false tmp = @noop || self.resource.noop || Puppet[:noop] || false #debug "noop is #{tmp}" tmp end # return the full path to us, for logging and rollback; not currently # used def pathbuilder if @resource return [@resource.pathbuilder, self.name] else return [self.name] end end # If the specified value is allowed, then munge appropriately. # If the developer uses a 'munge' hook, this method will get overridden. def unsafe_munge(value) self.class.value_collection.munge(value) end # no unmunge by default def unmunge(value) value end # A wrapper around our munging that makes sure we raise useful exceptions. def munge(value) begin ret = unsafe_munge(value) rescue Puppet::Error => detail Puppet.debug "Reraising #{detail}" raise rescue => detail raise Puppet::DevError, "Munging failed for value #{value.inspect} in class #{self.name}: #{detail}", detail.backtrace end ret end # Verify that the passed value is valid. # If the developer uses a 'validate' hook, this method will get overridden. def unsafe_validate(value) self.class.value_collection.validate(value) end # A protected validation method that only ever raises useful exceptions. def validate(value) begin unsafe_validate(value) rescue ArgumentError => detail fail detail.to_s rescue Puppet::Error, TypeError raise rescue => detail raise Puppet::DevError, "Validate method failed for class #{self.name}: #{detail}", detail.backtrace end end def remove @resource = nil end def value unmunge(@value) unless @value.nil? end # Store the value provided. All of the checking should possibly be # late-binding (e.g., users might not exist when the value is assigned # but might when it is asked for). def value=(value) validate(value) @value = munge(value) end # Retrieve the resource's provider. Some types don't have providers, in which # case we return the resource object itself. def provider @resource.provider end # The properties need to return tags so that logs correctly collect them. def tags unless defined?(@tags) @tags = [] # This might not be true in testing @tags = @resource.tags if @resource.respond_to? :tags @tags << self.name.to_s end @tags end def to_s name.to_s end end + +require 'puppet/parameter/path' diff --git a/lib/puppet/parameter/path.rb b/lib/puppet/parameter/path.rb new file mode 100644 index 000000000..44886afd0 --- /dev/null +++ b/lib/puppet/parameter/path.rb @@ -0,0 +1,42 @@ +require 'puppet/parameter' + +class Puppet::Parameter::Path < Puppet::Parameter + def self.accept_arrays(bool = true) + @accept_arrays = !!bool + end + def self.arrays? + @accept_arrays + end + + def validate_path(paths) + if paths.is_a?(Array) and ! self.class.arrays? then + fail "#{name} only accepts a single path, not an array of paths" + end + + # We *always* support Unix path separators, as Win32 does now too. + absolute = "[/#{::Regexp.quote(::File::SEPARATOR)}]" + win32 = Puppet.features.microsoft_windows? + + Array(paths).each do |path| + next if path =~ %r{^#{absolute}} + next if win32 and path =~ %r{^(?:[a-zA-Z]:)?#{absolute}} + fail("#{name} must be a fully qualified path") + end + + paths + end + + # This will be overridden if someone uses the validate option, which is why + # it just delegates to the other, useful, method. + def unsafe_validate(paths) + validate_path(paths) + end + + # Likewise, this might be overridden, but by default... + def unsafe_munge(paths) + if paths.is_a?(Array) and ! self.class.arrays? then + fail "#{name} only accepts a single path, not an array of paths" + end + paths + end +end diff --git a/spec/shared_behaviours/path_parameters.rb b/spec/shared_behaviours/path_parameters.rb new file mode 100644 index 000000000..b5a907900 --- /dev/null +++ b/spec/shared_behaviours/path_parameters.rb @@ -0,0 +1,185 @@ +# In order to use this correctly you must define a method to get an instance +# of the type being tested, so that this code can remain generic: +# +# it_should_behave_like "all path parameters", :path do +# def instance(path) +# Puppet::Type.type(:example).new( +# :name => 'foo', :require => 'bar', :path_param => path +# ) +# end +# +# That method will be invoked for each test to create the instance that we +# subsequently test through the system; you should ensure that the minimum of +# possible attributes are set to keep the tests clean. +# +# You must also pass the symbolic name of the parameter being tested to the +# block, and optionally can pass a hash of additional options to the block. +# +# The known options are: +# :array :: boolean, does this support arrays of paths, default true. + +shared_examples_for "all pathname parameters with arrays" do |win32| + path_types = { + "unix absolute" => "/foo/bar", + "unix relative" => "foo/bar", + "win32 absolute" => %q{\foo\bar}, + "win32 relative" => %q{foo\bar}, + "drive absolute" => %q{c:\foo\bar}, + "drive relative" => %q{c:foo\bar} + } + + describe "when given an array of paths" do + (1..path_types.length).each do |n| + path_types.keys.combination(n) do |set| + data = path_types.collect { |k, v| set.member?(k) ? v : nil } .compact + reject = true + only_absolute = set.find { |k| k =~ /relative/ } .nil? + only_unix = set.reject { |k| k =~ /unix/ } .length == 0 + + if only_absolute and (only_unix or win32) then + reject = false + end + + it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")}" do + if reject then + expect { instance(data) }. + should raise_error Puppet::Error, /fully qualified/ + else + instance = instance(data) + instance[@param].should == data + end + end + + it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")} doubled" do + if reject then + expect { instance(data + data) }. + should raise_error Puppet::Error, /fully qualified/ + else + instance = instance(data + data) + instance[@param].should == (data + data) + end + end + end + end + end +end + + +shared_examples_for "all path parameters" do |param, options| + # Extract and process options to the block. + options ||= {} + array = options[:array].nil? ? true : options.delete(:array) + if options.keys.length > 0 then + fail "unknown options for 'all path parameters': " + + options.keys.sort.join(', ') + end + + def instance(path) + fail "we didn't implement the 'instance(path)' method in the it_should_behave_like block" + end + + ######################################################################## + # The actual testing code... + before :all do + @param = param + end + + before :each do + @file_separator = File::SEPARATOR + end + after :each do + with_verbose_disabled do + verbose, $VERBOSE = $VERBOSE, nil + File::SEPARATOR = @file_separator + $VERBOSE = verbose + end + end + + describe "on a Unix-like platform it" do + before :each do + with_verbose_disabled do + File::SEPARATOR = '/' + end + Puppet.features.stubs(:microsoft_windows?).returns(false) + Puppet.features.stubs(:posix?).returns(true) + end + + if array then + it_should_behave_like "all pathname parameters with arrays", false + end + + it "should accept a fully qualified path" do + path = File.join('', 'foo') + instance = instance(path) + instance[@param].should == path + end + + it "should give a useful error when the path is not absolute" do + path = 'foo' + expect { instance(path) }. + should raise_error Puppet::Error, /fully qualified/ + end + + { "Unix" => '/', "Win32" => '\\' }.each do |style, slash| + %w{q Q a A z Z c C}.sort.each do |drive| + it "should reject drive letter '#{drive}' with #{style} path separators" do + path = "#{drive}:#{slash}Program Files" + expect { instance(path) }. + should raise_error Puppet::Error, /fully qualified/ + end + end + end + end + + describe "on a Windows-like platform it" do + before :each do + with_verbose_disabled do + File::SEPARATOR = '\\' + end + Puppet.features.stubs(:microsoft_windows?).returns(true) + Puppet.features.stubs(:posix?).returns(false) + end + + if array then + it_should_behave_like "all pathname parameters with arrays", true + end + + it "should accept a fully qualified path" do + path = File.join('', 'foo') + instance = instance(path) + instance[@param].should == path + end + + it "should give a useful error when the path is not absolute" do + path = 'foo' + expect { instance(path) }. + should raise_error Puppet::Error, /fully qualified/ + end + + it "also accepts Unix style path separators" do + path = '/Program Files' + instance = instance(path) + instance[@param].should == path + end + + { "Unix" => '/', "Win32" => '\\' }.each do |style, slash| + %w{q Q a A z Z c C}.sort.each do |drive| + it "should accept drive letter '#{drive}' with #{style} path separators " do + path = "#{drive}:#{slash}Program Files" + instance = instance(path) + instance[@param].should == path + end + end + end + + { "UNC paths" => %q{\\foo\bar}, + "unparsed local paths" => %q{\\?\c:\foo}, + "unparsed UNC paths" => %q{\\?\foo\bar} + }.each do |name, path| + it "should accept #{name} as absolute" do + instance = instance(path) + instance[@param].should == path + end + end + end +end diff --git a/spec/unit/parameter/path_spec.rb b/spec/unit/parameter/path_spec.rb new file mode 100644 index 000000000..08a26de33 --- /dev/null +++ b/spec/unit/parameter/path_spec.rb @@ -0,0 +1,24 @@ +#!/usr/bin/env ruby +require File.expand_path(File.join(File.dirname(__FILE__), '../../spec_helper')) + +require 'puppet/parameter/path' + +[false, true].each do |arrays| + describe "Puppet::Parameter::Path with arrays #{arrays}" do + it_should_behave_like "all path parameters", :path, :array => arrays do + # The new type allows us a test that is guaranteed to go direct to our + # validation code, without passing through any "real type" overrides or + # whatever on the way. + Puppet::newtype(:test_puppet_parameter_path) do + newparam(:path, :parent => Puppet::Parameter::Path, :arrays => arrays) do + isnamevar + accept_arrays arrays + end + end + + def instance(path) + Puppet::Type.type(:test_puppet_parameter_path).new(:path => path) + end + end + end +end