Skip to content

Instantly share code, notes, and snippets.

@natemccurdy
Created May 16, 2019 18:13
Show Gist options
  • Save natemccurdy/95239a7161ada403b21e5e845f47f068 to your computer and use it in GitHub Desktop.
Save natemccurdy/95239a7161ada403b21e5e845f47f068 to your computer and use it in GitHub Desktop.
Puppet function to list the files in a module's 'files' directory
#
# get_module_files.rb
#
module Puppet::Parser::Functions
newfunction(:get_module_files, :type => :rvalue, :doc => <<-DOC
Returns an array of relative files names for a given module and optional
sub directory. Do not include 'files' in the optional relative path as it
is assumed.
Returns an empty array if no files are found.
Errors if the requested module does not exist.
Example:
With a files directory of:
files/
foo.sh
bar.txt
default-configs/
file1.txt
file2.xml
get_module_files($module_name)
Returns: ['foo.sh', 'bar.txt', 'default-configs/file1.txt', 'default-configs/file2.xml']
get_module_files("${module_name}/default-configs")
Returns: ['file1.txt', 'file2.xml']
DOC
) do |args|
raise(Puppet::ParseError, 'get_module_files(): Wrong number of arguments, expects one') unless args.size == 1
# Parse the module name and optional sub directory out of the arguments.
module_name, *sub_directory = args[0].split('/')
# Ask the compiler for the path to the module.
module_path = Puppet::Module.find(module_name, compiler.environment.to_s)
raise(Puppet::ParseError, "Could not find module #{module_name} in environment #{compiler.environment}") unless module_path
# Build the abosolute path of the directory to search through.
# Uses splat and compact to account for a possibly nil sub_directory.
paths = [module_path.path, 'files', sub_directory].flatten.compact
search_path = File.join(*paths)
# Search for files.
files = Dir[File.join(search_path,'**','*')]
.select { |e| File.file?(e) } # Select only real files, not directories.
.collect { |f| f.sub("#{search_path}/", '') } # Strip the module path out of the result.
# Return the array of found files.
files
end
end
@natemccurdy
Copy link
Author

Or just use functions from stdlib:

$module_path = get_module_path($module_name)
$files = glob("${module_path}/files/**/*").regsubst("${module_path}/files/",'')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment