diff --git a/README.markdown b/README.markdown index e9ad53b8b..d3d119077 100644 --- a/README.markdown +++ b/README.markdown @@ -95,6 +95,16 @@ string - *Type*: rvalue +basename +------- +Returns the `basename` of a path. + +*Examples:* + + basename('/path/to/a/file.ext') + +Would return: 'file.ext' + bool2num -------- Converts a boolean to a number. Converts the values: diff --git a/lib/puppet/parser/functions/basename.rb b/lib/puppet/parser/functions/basename.rb new file mode 100644 index 000000000..c1b9d6e34 --- /dev/null +++ b/lib/puppet/parser/functions/basename.rb @@ -0,0 +1,12 @@ +module Puppet::Parser::Functions + newfunction(:basename, :type => :rvalue, :arity => 1, doc => <<-EOS + Returns the basename of a path. + EOS + ) do |arguments| + + path = arguments[0] + return File.basename(path) + end +end + +# vim: set ts=2 sw=2 et : diff --git a/spec/acceptance/basename_spec.rb b/spec/acceptance/basename_spec.rb new file mode 100755 index 000000000..2a7db8f26 --- /dev/null +++ b/spec/acceptance/basename_spec.rb @@ -0,0 +1,42 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'basename function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + context 'absolute path' do + it 'returns the basename' do + pp = <<-EOS + $a = '/path/to/a/file.txt' + $b = 'file.txt' + $o = basename($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + context 'relative path' do + it 'returns the basename' do + pp = <<-EOS + $a = 'path/to/a/file.txt' + $b = 'file.txt' + $o = basename($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/spec/functions/basename_spec.rb b/spec/functions/basename_spec.rb new file mode 100755 index 000000000..b5eb8b9c4 --- /dev/null +++ b/spec/functions/basename_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the basename function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + expect(Puppet::Parser::Functions.function("basename")).to eq("function_basename") + end + + it "should raise a ParseError if there is less than 1 arguments" do + expect { scope.function_basename([]) }.to( raise_error(Puppet::ParseError)) + end + + it "should return basename for an absolute path" do + result = scope.function_basename(['/path/to/a/file.ext']) + expect(result).to(eq('file.ext')) + end + + it "should return basename for a relative path" do + result = scope.function_basename(['path/to/a/file.ext']) + expect(result).to(eq('file.ext')) + end +end